Skip to content

Commit

Permalink
Merge pull request #330 from blinko-space/dev
Browse files Browse the repository at this point in the history
fix: support file upload loading tips
  • Loading branch information
blinko-space authored Dec 17, 2024
2 parents 8ea847a + 66f1cbe commit 817b921
Show file tree
Hide file tree
Showing 27 changed files with 370 additions and 80 deletions.
41 changes: 28 additions & 13 deletions app/api/file/upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,35 @@ export const POST = async (req: NextRequest, res: NextResponse) => {
if (!token) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
const formData = await req.formData();
const file = formData.getAll('file')[0]
if (!file) {
return NextResponse.json({ error: "No files received." }, { status: 400 });
}

if (process.env.IS_DEMO) {
return NextResponse.json({ error: "In Demo App" }, { status: 401 });
}
//@ts-ignore
const buffer = Buffer.from(await file.arrayBuffer());
//@ts-ignore
const originalName = (file.name).replaceAll(" ", "_");
const extension = path.extname(originalName);
const filePath = await FileService.uploadFile(buffer, originalName)
//@ts-ignore
return NextResponse.json({ Message: "Success", status: 200, ...filePath, type: file?.type ?? '', size: file?.size ?? 0 });

try {
const formData = await req.formData();
const file = formData.getAll('file')[0] as File;

if (!file) {
return NextResponse.json({ error: "No files received." }, { status: 400 });
}

const originalName = file.name.replaceAll(" ", "_");
const stream = file.stream();

const filePath = await FileService.uploadFileStream(stream, originalName, file.size);

return NextResponse.json({
Message: "Success",
status: 200,
...filePath,
type: file.type,
size: file.size
});

} catch (error) {
console.error('Upload error:', error);
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
}
};

6 changes: 5 additions & 1 deletion public/locales/ar/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -345,5 +345,9 @@
"context": "السياق",
"paste-to-note-or-attachment": "هل أنت متأكد من لصق النص في السياق أو المرفق؟",
"attachment": "المرفق",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "بعد الحذف، سيتم مسح جميع بيانات المستخدم ولن يمكن استرجاعها."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "بعد الحذف، سيتم مسح جميع بيانات المستخدم ولن يمكن استرجاعها.",
"upload-completed": "تم الرفع بنجاح",
"upload-cancelled": "تم إلغاء التحميل",
"upload-failed": "فشل التحميل",
"import-from-bko-tip": "تحميل إلى s3 للإسترداد غير مدعوم في الوقت الحالي. يُرجى تعطيل الخيار s3 مؤقتًا عند رغبتك في الاسترداد."
}
6 changes: 5 additions & 1 deletion public/locales/de/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -332,5 +332,9 @@
"context": "Kontext",
"paste-to-note-or-attachment": "Sind Sie sicher, dass Sie in den Kontext oder als Anhang einfügen möchten?",
"attachment": "Anhang",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Nach dem Löschen werden alle Benutzerdaten gelöscht und können nicht wiederhergestellt werden."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Nach dem Löschen werden alle Benutzerdaten gelöscht und können nicht wiederhergestellt werden.",
"upload-completed": "Hochladen abgeschlossen",
"upload-cancelled": "Upload abgebrochen",
"upload-failed": "Upload fehlgeschlagen",
"import-from-bko-tip": "Das Hochladen zur Wiederherstellung auf S3 wird derzeit nicht unterstützt. Deaktivieren Sie die S3-Option vorübergehend, wenn Sie eine Wiederherstellung durchführen möchten."
}
6 changes: 5 additions & 1 deletion public/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -343,5 +343,9 @@
"paste-to-note-or-attachment": "Are you sure to paste to context or attachment? ",
"context": "Context",
"attachment": "Attachment",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "After deletion, all user data will be cleared and unrecoverable."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "After deletion, all user data will be cleared and unrecoverable.",
"upload-completed": "Upload completed",
"upload-cancelled": "Upload cancelled",
"upload-failed": "Upload Failed",
"import-from-bko-tip": "Uploading to s3 for recovery is not supported at this time. Please disable the s3 option temporarily when you want to recover."
}
6 changes: 5 additions & 1 deletion public/locales/es/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -323,5 +323,9 @@
"context": "Contexto",
"paste-to-note-or-attachment": "¿Estás seguro de pegar en el contexto o adjuntar?",
"attachment": "Adjunto",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Después de la eliminación, todos los datos de usuario serán borrados y no se podrán recuperar."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Después de la eliminación, todos los datos de usuario serán borrados y no se podrán recuperar.",
"upload-completed": "Carga completada",
"upload-cancelled": "Subida cancelada",
"upload-failed": "Error al subir",
"import-from-bko-tip": "La carga a s3 para recuperación no está soportada en este momento. Por favor, deshabilite temporalmente la opción s3 cuando desee recuperar."
}
6 changes: 5 additions & 1 deletion public/locales/fr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -320,5 +320,9 @@
"context": "Contexte",
"paste-to-note-or-attachment": "Êtes-vous sûr de coller dans le contexte ou en pièce jointe ?",
"attachment": "Pièce jointe",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Après la suppression, toutes les données utilisateur seront effacées et définitivement irrécupérables."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Après la suppression, toutes les données utilisateur seront effacées et définitivement irrécupérables.",
"upload-completed": "Téléchargement terminé",
"upload-cancelled": "Téléchargement annulé",
"upload-failed": "Téléchargement échoué",
"import-from-bko-tip": "Le téléversement vers s3 pour la récupération n'est pas pris en charge actuellement. Veuillez désactiver temporairement l'option s3 lorsque vous souhaitez récupérer."
}
6 changes: 5 additions & 1 deletion public/locales/ja/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -305,5 +305,9 @@
"context": "コンテクスト",
"paste-to-note-or-attachment": "コンテキストや添付ファイルに貼り付けることを確認しますか?",
"attachment": "添付",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "削除後、すべてのユーザーデータは消去され、回復不能になります。"
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "削除後、すべてのユーザーデータは消去され、回復不能になります。",
"upload-completed": "アップロードが完了しました",
"upload-cancelled": "アップロードがキャンセルされました",
"upload-failed": "アップロードに失敗しました",
"import-from-bko-tip": "この時点では、S3 へのアップロードによるリカバリはサポートされていません。リカバリを行う際には一時的に S3 オプションを無効にしてください。"
}
6 changes: 5 additions & 1 deletion public/locales/ko/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -327,5 +327,9 @@
"context": "문맥",
"paste-to-note-or-attachment": "컨텍스트나 첨부 파일에 붙여 넣을 확신이 있습니까?",
"attachment": "첨부 파일",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "삭제 후 모든 사용자 데이터가 지워지고 복구할 수 없게 됩니다."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "삭제 후 모든 사용자 데이터가 지워지고 복구할 수 없게 됩니다.",
"upload-completed": "업로드가 완료되었습니다.",
"upload-cancelled": "업로드가 취소되었습니다.",
"upload-failed": "업로드 실패",
"import-from-bko-tip": "현재 s3로의 업로드는 복구되지 않습니다. 복구를 원할 경우 s3 옵션을 일시적으로 비활성화하십시오."
}
6 changes: 5 additions & 1 deletion public/locales/pt/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -255,5 +255,9 @@
"context": "Contexto",
"paste-to-note-or-attachment": "Tem certeza de que deseja colar no contexto ou no anexo?",
"attachment": "Anexo",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Após a exclusão, todos os dados do usuário serão apagados e não poderão ser recuperados."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Após a exclusão, todos os dados do usuário serão apagados e não poderão ser recuperados.",
"upload-completed": "Carregamento concluído",
"upload-cancelled": "Envio cancelado",
"upload-failed": "Falha ao Carregar",
"import-from-bko-tip": "O envio para o s3 para recuperação não é suportado neste momento. Por favor, desative temporariamente a opção s3 quando desejar recuperar."
}
6 changes: 5 additions & 1 deletion public/locales/ru/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -260,5 +260,9 @@
"context": "Контекст",
"paste-to-note-or-attachment": "Вы уверены, что хотите вставить в контекст или прикрепление?",
"attachment": "Прикрепление",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "После удаления все данные пользователей будут очищены и не поддадутся восстановлению."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "После удаления все данные пользователей будут очищены и не поддадутся восстановлению.",
"upload-completed": "Загрузка завершена",
"upload-cancelled": "Загрузка отменена",
"upload-failed": "Не удалось загрузить",
"import-from-bko-tip": "Загрузка в s3 для восстановления в настоящее время не поддерживается. Пожалуйста, временно отключите опцию s3, когда планируете выполнить восстановление."
}
6 changes: 5 additions & 1 deletion public/locales/tr/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -273,5 +273,9 @@
"context": "Bağlam",
"paste-to-note-or-attachment": "Metin veya ek dosyaya yapıştırmak istediğinizden emin misiniz?",
"attachment": "Eklenti",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Silme işleminden sonra, tüm kullanıcı verileri temizlenecek ve kurtarılamaz hale gelecektir."
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "Silme işleminden sonra, tüm kullanıcı verileri temizlenecek ve kurtarılamaz hale gelecektir.",
"upload-completed": "Yükleme tamamlandı",
"upload-cancelled": "Yükleme iptal edildi",
"upload-failed": "Yükleme Başarısız oldu",
"import-from-bko-tip": "Bu zamanda s3'e yükleme yapılmamaktadır. Kurtarma işlemi gerçekleştirmek istediğinizde lütfen geçici olarak s3 seçeneğini devre dışı bırakın."
}
6 changes: 5 additions & 1 deletion public/locales/zh-TW/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -357,5 +357,9 @@
"context": "正文",
"paste-to-note-or-attachment": "您確定要貼上到內容或附件嗎?",
"attachment": "附件",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "刪除後,所有用戶資料將被清空且無法恢復。"
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "刪除後,所有用戶資料將被清空且無法恢復。",
"upload-completed": "上傳完成",
"upload-cancelled": "上傳已取消",
"upload-failed": "上傳失敗",
"import-from-bko-tip": "目前不支援上傳至 s3 進行還原。當您想要進行恢復操作時,請暫時停用 s3 選項。"
}
6 changes: 5 additions & 1 deletion public/locales/zh/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -357,5 +357,9 @@
"paste-to-note-or-attachment": "您确定要粘贴到上下文或附件吗?",
"context": "正文",
"attachment": "附件",
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "删除后,所有用户数据将被清除且无法恢复。"
"after-deletion-all-user-data-will-be-cleared-and-unrecoverable": "删除后,所有用户数据将被清除且无法恢复。",
"upload-completed": "上传完成",
"upload-cancelled": "上传已取消",
"upload-failed": "上传失败",
"import-from-bko-tip": "目前不支持将上传到S3进行恢复。当您想要恢复时,请暂时禁用S3选项。"
}
10 changes: 5 additions & 5 deletions public/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,28 @@
"short_name": "Blinko",
"icons": [
{
"src": "/logo/icon-128x128.png",
"src": "/icons/icon-128x128.png",
"sizes": "128x128",
"type": "image/png",
"purpose": "any maskable"
},
{
"src": "/logo/icon-144x144.png",
"src": "/icons/icon-144x144.png",
"sizes": "144x144",
"type": "image/png"
},
{
"src": "/logo/icon-152x152.png",
"src": "/icons/icon-152x152.png",
"sizes": "152x152",
"type": "image/png"
},
{
"src": "/logo/icon-192x192.png",
"src": "/icons/icon-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "/logo/icon-256x256.png",
"src": "/icons/icon-256x256.png",
"sizes": "256x256",
"type": "image/png"
}
Expand Down
5 changes: 2 additions & 3 deletions src/components/BlinkoSettings/BasicSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import React, { useEffect, useState } from "react";
import { motion, AnimatePresence } from "motion/react";
import { ShowGen2FATokenModal } from "../Common/TwoFactorModal/gen2FATokenModal";
import { CollapsibleCard } from "../Common/CollapsibleCard";
import { eventBus } from "@/lib/event";

export const BasicSetting = observer(() => {
const [isCollapsed, setIsCollapsed] = useState(false);
Expand Down Expand Up @@ -240,9 +241,7 @@ export const BasicSetting = observer(() => {
<Tooltip placement="bottom" content={t('logout')}>
<Button isIconOnly startContent={<Icon icon="hugeicons:logout-05" width="20" height="20" />} color='danger' onPress={async () => {
await signOut({ redirect: false })
router.push('/signin')
localStorage.removeItem('username')
localStorage.removeItem('password')
eventBus.emit('user:signout')
}}></Button>
</Tooltip>
} />
Expand Down
5 changes: 2 additions & 3 deletions src/components/BlinkoSettings/ImportSetting.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { helper } from "@/lib/helper";
import dayjs from "@/lib/dayjs";
import { Icon } from "@iconify/react";
import { api, streamApi } from "@/lib/trpc";
import { Item } from "./Item";
import { Item, ItemWithTooltip } from "./Item";
import { useTranslation } from "react-i18next";
import { UploadFileWrapper } from "../Common/UploadFile";
import { ToastPlugin } from "@/store/module/Toast/Toast";
Expand All @@ -26,13 +26,12 @@ export const ImportSetting = observer(() => {
title={t('import')}
>
<Item
leftContent={<>{t('import-from-bko')}</>}
leftContent={<ItemWithTooltip content={t('import-from-bko')} toolTipContent={<div>{t('import-from-bko-tip')}</div>} />}
rightContent={<>
<UploadFileWrapper onUpload={async ({ filePath, fileName }) => {
if (!fileName.endsWith('.bko')) {
return RootStore.Get(ToastPlugin).error(t('not-a-bko-file'))
}
// PromiseCall(api.task.restoreDB.query({ fileName }))
ShowBlinkoProgressDialog(filePath)
}}>
</UploadFileWrapper>
Expand Down
16 changes: 8 additions & 8 deletions src/components/BlinkoSettings/StorageSetting.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { observer } from "mobx-react-lite";
import { Button, Card, DropdownItem, DropdownMenu, DropdownTrigger, Dropdown, Input } from "@nextui-org/react";
import { Button, DropdownItem, DropdownMenu, DropdownTrigger, Dropdown, Input } from "@nextui-org/react";
import { RootStore } from "@/store";
import { BlinkoStore } from "@/store/blinkoStore";
import { PromiseCall } from "@/store/standard/PromiseState";
Expand All @@ -10,6 +10,7 @@ import { useTranslation } from "react-i18next";
import { useMediaQuery } from "usehooks-ts";
import { useEffect } from "react";
import { PasswordInput } from "@/components/Common/PasswordInput";
import { CollapsibleCard } from "@/components/Common/CollapsibleCard";


export const StorageSetting = observer(() => {
Expand All @@ -35,13 +36,12 @@ export const StorageSetting = observer(() => {
}, [blinko.config.value])


return <Card shadow="none" className="flex flex-col p-4 bg-background">
<div className='text-desc flex items-center gap-2'>
<Icon icon="tabler:brush" width="20" height="20" />
<div className="text-sm">{t('storage')}</div>
</div>
return <CollapsibleCard
icon="tabler:brush"
title={t('storage')}
>
<Item
leftContent={<div className="flex flex-col gap-2">
leftContent={<div className="flex flex-col gap-2">
<div>{t('object-storage')}</div>
</div>}
rightContent={<div>
Expand Down Expand Up @@ -129,5 +129,5 @@ export const StorageSetting = observer(() => {
}} />} />
</>
}
</Card>
</CollapsibleCard>
})
13 changes: 9 additions & 4 deletions src/components/Common/Editor/editorStore.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import i18n from '@/lib/i18n';
import { DialogStandaloneStore } from '@/store/module/DialogStandalone';
import { handlePaste } from '@/lib/hooks';
import { Button } from '@nextui-org/react';
import axios from 'axios';
import { ToastPlugin } from '@/store/module/Toast/Toast';
export class EditorStore {
files: FileType[] = []
lastRange: Range | null = null
Expand Down Expand Up @@ -132,11 +134,14 @@ export class EditorStore {
function: async () => {
const formData = new FormData();
formData.append('file', file)
const response = await fetch('/api/file/upload', {
method: 'POST',
body: formData,
const { onUploadProgress } = RootStore.Get(ToastPlugin)
.setSizeThreshold(40)
.uploadProgress(file);

const response = await axios.post('/api/file/upload', formData, {
onUploadProgress
});
const data = await response.json();
const data = response.data;
this.speechToText(data.filePath)
if (data.filePath) {
return data.filePath
Expand Down
4 changes: 2 additions & 2 deletions src/components/Common/TipsDialog/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,11 @@ export const TipsPopover = observer((props: { children: React.ReactNode, content
<div className="font-bold mb-2">{props.content}</div>
</div>
<div className='flex my-1 gap-2'>
<Button startContent={<Icon icon="iconoir:cancel" width="20" height="20" />} variant="flat" size="sm" className="w-1/2" color='default' onPress={e => {
<Button startContent={<Icon icon="iconoir:cancel" width="20" height="20" />} variant="flat" size="sm" className="ml-auto" color='default' onPress={e => {
RootStore.Get(DialogStandaloneStore).close()
props.onCancel?.()
}}>{t('cancel')}</Button>
<Button startContent={<Icon icon="cil:check-alt" width="20" height="20" />} isLoading={isLoading} className="w-1/2" size="sm" color='danger' onPress={async e => {
<Button startContent={<Icon icon="cil:check-alt" width="20" height="20" />} isLoading={isLoading} size="sm" color='danger' onPress={async e => {
props.onConfirm?.()
}}>{t('confirm')}</Button>
</div>
Expand Down
Loading

0 comments on commit 817b921

Please sign in to comment.