From 8badb80600986be2321addeb33453f4dcfd58f2c Mon Sep 17 00:00:00 2001 From: Orion Date: Fri, 11 Sep 2026 16:51:50 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(core):=20=E5=AE=9E=E7=8E=B0?= =?UTF-8?q?=E7=AE=A1=E7=90=86=E7=AB=AF=E5=90=8E=E5=8F=B0=E7=95=8C=E9=9D=A2?= =?UTF-8?q?=E5=8F=8A=E6=A0=B8=E5=BF=83=E5=8A=9F=E8=83=BD=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 初始化后台管理布局与路由框架 * 新增文件管理、仪表盘、系统设置及日志视图 * 实现文件上传预签名、提取流程及发送记录管理 * 构建常用组件库如模态框、表格、分页及进度条 * 引入多语言支持(中英文)及主题切换功能 * 封装后台业务逻辑 Hooks 和数据持久化存储功能 --- Dockerfile 2 | 13 + src/App 2.vue | 128 + src/assets/font/DingTalk 2.ttf | Bin 0 -> 85552 bytes src/assets/style/main 2.css | 451 +++ src/components/common/AlertComponent 2.vue | 88 + src/components/common/BaseButton 2.vue | 84 + src/components/common/BaseModal 2.vue | 174 ++ src/components/common/BorderProgressBar 2.vue | 154 + .../common/ContentPreviewModal 2.vue | 195 ++ src/components/common/DataPagination 2.vue | 130 + src/components/common/DataTable 2.vue | 67 + .../common/ExpirationSelector 2.vue | 112 + src/components/common/FileDetailModal 2.vue | 153 + src/components/common/FileEditField 2.vue | 75 + src/components/common/FileRecordList 2.vue | 52 + src/components/common/FileUploadArea 2.vue | 345 +++ src/components/common/FormInput 2.vue | 60 + src/components/common/LanguageSwitcher 2.vue | 111 + src/components/common/NativeDateSelect 2.vue | 271 ++ src/components/common/PageFooter 2.vue | 72 + src/components/common/PageHeader 2.vue | 65 + src/components/common/RetrieveForm 2.vue | 107 + src/components/common/SendTypeSelector 2.vue | 56 + .../common/SentRecordDetailModal 2.vue | 273 ++ src/components/common/SentRecordList 2.vue | 56 + .../common/SettingNumberInput 2.vue | 41 + src/components/common/SettingSwitch 2.vue | 40 + src/components/common/SideDrawer 2.vue | 131 + src/components/common/SmoothTrendCanvas 2.vue | 551 ++++ src/components/common/StatCard 2.vue | 79 + src/components/common/TextInputArea 2.vue | 94 + src/components/common/ThemeToggle 2.vue | 31 + src/components/common/scrollLock 2.ts | 22 + src/composables/index 2.ts | 17 + src/composables/useAdminActivities 2.ts | 13 + src/composables/useAdminFiles 2.ts | 1849 ++++++++++++ src/composables/useAdminLogin 2.ts | 61 + src/composables/useAdminSession 2.ts | 40 + src/composables/useAdminTrash 2.ts | 16 + src/composables/useAppShell 2.ts | 62 + src/composables/useClipboard 2.ts | 6 + src/composables/useDashboardStats 2.ts | 188 ++ src/composables/useInjectedDarkMode 2.ts | 7 + src/composables/usePresignedUpload 2.ts | 355 +++ src/composables/usePublicConfigBootstrap 2.ts | 26 + src/composables/useRetrieveFlow 2.ts | 249 ++ src/composables/useRouteLoading 2.ts | 44 + src/composables/useSendFlow 2.ts | 361 +++ src/composables/useSendSubmit 2.ts | 131 + src/composables/useSystemConfig 2.ts | 216 ++ src/composables/useTheme 2.ts | 139 + src/composables/useTransferAnalytics 2.ts | 13 + src/constants/index 2.ts | 102 + src/hooks/index 2.ts | 14 + src/i18n/index 2.ts | 51 + src/i18n/locales/en-US 2.ts | 1037 +++++++ src/i18n/locales/zh-CN 2.ts | 1057 +++++++ src/layout/AdminLayout/AdminLayout 2.vue | 353 +++ src/main 2.ts | 18 + src/router/index 2.ts | 123 + src/services/activity 2.ts | 10 + src/services/auth 2.ts | 16 + src/services/client 2.ts | 61 + src/services/config 2.ts | 52 + src/services/file 2.ts | 272 ++ src/services/index 2.ts | 9 + src/services/presign-upload 2.ts | 58 + src/services/shared 2.ts | 20 + src/services/stats 2.ts | 17 + src/services/trash 2.ts | 20 + src/services/upload-client 2.ts | 26 + src/services/upload-strategy 2.ts | 103 + src/stores/adminStore 2.ts | 82 + src/stores/alertStore 2.ts | 61 + src/stores/configStore 2.ts | 76 + src/stores/fileData 2.ts | 55 + src/types/activity 2.ts | 48 + src/types/api 2.ts | 11 + src/types/auth 2.ts | 7 + src/types/config 2.ts | 68 + src/types/dashboard 2.ts | 142 + src/types/file 2.ts | 496 ++++ src/types/index 2.ts | 9 + src/types/presign-upload 2.ts | 55 + src/types/trash 2.ts | 27 + src/types/ui 2.ts | 26 + src/utils/api 2.ts | 2 + src/utils/auth-storage 2.ts | 26 + src/utils/clipboard 2.ts | 129 + src/utils/clipboard-paste 2.ts | 40 + src/utils/common 2.ts | 236 ++ src/utils/config-form 2.ts | 107 + src/utils/config-storage 2.ts | 108 + src/utils/content-preview 2.ts | 42 + src/utils/convert 2.ts | 10 + src/utils/download-action 2.ts | 84 + src/utils/file-processing 2.ts | 59 + src/utils/preference-storage 2.ts | 20 + src/utils/record-storage 2.ts | 23 + src/utils/retrieval-code 2.ts | 25 + src/utils/send-record 2.ts | 99 + src/utils/sent-record-actions 2.ts | 17 + src/utils/share-url 2.ts | 38 + src/views/RetrievewFileView 2.vue | 110 + src/views/SendFileView 2.vue | 278 ++ src/views/manage/ActivityLogView 2.vue | 150 + src/views/manage/DashboardView 2.vue | 694 +++++ src/views/manage/FileManageView 2.vue | 2617 +++++++++++++++++ src/views/manage/LoginView 2.vue | 230 ++ src/views/manage/SystemSettingsView 2.vue | 838 ++++++ src/views/manage/TrashView 2.vue | 127 + src/vite-env.d 2.ts | 16 + tailwind.config 2.js | 12 + tsconfig.node 2.json | 19 + 114 files changed, 18812 insertions(+) create mode 100644 Dockerfile 2 create mode 100644 src/App 2.vue create mode 100644 src/assets/font/DingTalk 2.ttf create mode 100644 src/assets/style/main 2.css create mode 100644 src/components/common/AlertComponent 2.vue create mode 100644 src/components/common/BaseButton 2.vue create mode 100644 src/components/common/BaseModal 2.vue create mode 100644 src/components/common/BorderProgressBar 2.vue create mode 100644 src/components/common/ContentPreviewModal 2.vue create mode 100644 src/components/common/DataPagination 2.vue create mode 100644 src/components/common/DataTable 2.vue create mode 100644 src/components/common/ExpirationSelector 2.vue create mode 100644 src/components/common/FileDetailModal 2.vue create mode 100644 src/components/common/FileEditField 2.vue create mode 100644 src/components/common/FileRecordList 2.vue create mode 100644 src/components/common/FileUploadArea 2.vue create mode 100644 src/components/common/FormInput 2.vue create mode 100644 src/components/common/LanguageSwitcher 2.vue create mode 100644 src/components/common/NativeDateSelect 2.vue create mode 100644 src/components/common/PageFooter 2.vue create mode 100644 src/components/common/PageHeader 2.vue create mode 100644 src/components/common/RetrieveForm 2.vue create mode 100644 src/components/common/SendTypeSelector 2.vue create mode 100644 src/components/common/SentRecordDetailModal 2.vue create mode 100644 src/components/common/SentRecordList 2.vue create mode 100644 src/components/common/SettingNumberInput 2.vue create mode 100644 src/components/common/SettingSwitch 2.vue create mode 100644 src/components/common/SideDrawer 2.vue create mode 100644 src/components/common/SmoothTrendCanvas 2.vue create mode 100644 src/components/common/StatCard 2.vue create mode 100644 src/components/common/TextInputArea 2.vue create mode 100644 src/components/common/ThemeToggle 2.vue create mode 100644 src/components/common/scrollLock 2.ts create mode 100644 src/composables/index 2.ts create mode 100644 src/composables/useAdminActivities 2.ts create mode 100644 src/composables/useAdminFiles 2.ts create mode 100644 src/composables/useAdminLogin 2.ts create mode 100644 src/composables/useAdminSession 2.ts create mode 100644 src/composables/useAdminTrash 2.ts create mode 100644 src/composables/useAppShell 2.ts create mode 100644 src/composables/useClipboard 2.ts create mode 100644 src/composables/useDashboardStats 2.ts create mode 100644 src/composables/useInjectedDarkMode 2.ts create mode 100644 src/composables/usePresignedUpload 2.ts create mode 100644 src/composables/usePublicConfigBootstrap 2.ts create mode 100644 src/composables/useRetrieveFlow 2.ts create mode 100644 src/composables/useRouteLoading 2.ts create mode 100644 src/composables/useSendFlow 2.ts create mode 100644 src/composables/useSendSubmit 2.ts create mode 100644 src/composables/useSystemConfig 2.ts create mode 100644 src/composables/useTheme 2.ts create mode 100644 src/composables/useTransferAnalytics 2.ts create mode 100644 src/constants/index 2.ts create mode 100644 src/hooks/index 2.ts create mode 100644 src/i18n/index 2.ts create mode 100644 src/i18n/locales/en-US 2.ts create mode 100644 src/i18n/locales/zh-CN 2.ts create mode 100644 src/layout/AdminLayout/AdminLayout 2.vue create mode 100644 src/main 2.ts create mode 100644 src/router/index 2.ts create mode 100644 src/services/activity 2.ts create mode 100644 src/services/auth 2.ts create mode 100644 src/services/client 2.ts create mode 100644 src/services/config 2.ts create mode 100644 src/services/file 2.ts create mode 100644 src/services/index 2.ts create mode 100644 src/services/presign-upload 2.ts create mode 100644 src/services/shared 2.ts create mode 100644 src/services/stats 2.ts create mode 100644 src/services/trash 2.ts create mode 100644 src/services/upload-client 2.ts create mode 100644 src/services/upload-strategy 2.ts create mode 100644 src/stores/adminStore 2.ts create mode 100644 src/stores/alertStore 2.ts create mode 100644 src/stores/configStore 2.ts create mode 100644 src/stores/fileData 2.ts create mode 100644 src/types/activity 2.ts create mode 100644 src/types/api 2.ts create mode 100644 src/types/auth 2.ts create mode 100644 src/types/config 2.ts create mode 100644 src/types/dashboard 2.ts create mode 100644 src/types/file 2.ts create mode 100644 src/types/index 2.ts create mode 100644 src/types/presign-upload 2.ts create mode 100644 src/types/trash 2.ts create mode 100644 src/types/ui 2.ts create mode 100644 src/utils/api 2.ts create mode 100644 src/utils/auth-storage 2.ts create mode 100644 src/utils/clipboard 2.ts create mode 100644 src/utils/clipboard-paste 2.ts create mode 100644 src/utils/common 2.ts create mode 100644 src/utils/config-form 2.ts create mode 100644 src/utils/config-storage 2.ts create mode 100644 src/utils/content-preview 2.ts create mode 100644 src/utils/convert 2.ts create mode 100644 src/utils/download-action 2.ts create mode 100644 src/utils/file-processing 2.ts create mode 100644 src/utils/preference-storage 2.ts create mode 100644 src/utils/record-storage 2.ts create mode 100644 src/utils/retrieval-code 2.ts create mode 100644 src/utils/send-record 2.ts create mode 100644 src/utils/sent-record-actions 2.ts create mode 100644 src/utils/share-url 2.ts create mode 100644 src/views/RetrievewFileView 2.vue create mode 100644 src/views/SendFileView 2.vue create mode 100644 src/views/manage/ActivityLogView 2.vue create mode 100644 src/views/manage/DashboardView 2.vue create mode 100644 src/views/manage/FileManageView 2.vue create mode 100644 src/views/manage/LoginView 2.vue create mode 100644 src/views/manage/SystemSettingsView 2.vue create mode 100644 src/views/manage/TrashView 2.vue create mode 100644 src/vite-env.d 2.ts create mode 100644 tailwind.config 2.js create mode 100644 tsconfig.node 2.json diff --git a/Dockerfile 2 b/Dockerfile 2 new file mode 100644 index 0000000..11a06e3 --- /dev/null +++ b/Dockerfile 2 @@ -0,0 +1,13 @@ +FROM python:3.9.5 +LABEL author="Lan" +LABEL email="vast@tom.com" +LABEL version="1.0" + + +COPY . /app +RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime +RUN echo 'Asia/Shanghai' >/etc/timezone +WORKDIR /app +RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple/ +EXPOSE 123456 +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "12345"] \ No newline at end of file diff --git a/src/App 2.vue b/src/App 2.vue new file mode 100644 index 0000000..bf17389 --- /dev/null +++ b/src/App 2.vue @@ -0,0 +1,128 @@ + + + + + diff --git a/src/assets/font/DingTalk 2.ttf b/src/assets/font/DingTalk 2.ttf new file mode 100644 index 0000000000000000000000000000000000000000..a5b78e63fdde9a1a53e1bd54ed818470effb561e GIT binary patch literal 85552 zcmeEvcVHaF_5Z%v>qYIPJ9S-=?$p~!I?1+*o7}5pTef9mxp!<_F~u?66g%`1LIM~E z2pvLALQMiO;DiJM!C-1AA(RwC5^L}Gnc2P5>D11A^ZPG4-Rgv&I_8bbv3&mx zNiwdKBuo3Oj;h)%%XW53QtDmEzih>(o-N+DuB(%zG}M=L*P5PfTaa#*B=@7d{xus< zUp=>bUJZ4g+js9>*LW_j(T4Sb zji;{Y$z8DUDv7F0failvJ-fHams71ob)O->dvnjGRkvRJNsmPJXrJxea_YA2Uw&G- zUZT)>lH@$J<+N2>wlH0qL^F#yJos{K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BU*^#}fHcaBM2SQgs2I%k9daqN{9>k2gaIW|u88{6)=$tt3tkOU?6&>Wj0Qqs{Pw__%Bmm#V zH^pDo!M96|XtfoI{J<9Bu!a0M9kQbeTa*j7fa`R~jw) * { + position: relative; +} + +.theme-2026-card-hover { + transition: + transform 220ms ease, + border-color 220ms ease, + box-shadow 220ms ease, + background-color 220ms ease; +} + +.theme-2026-card-hover:hover { + border-color: rgba(116, 153, 165, 0.86); + box-shadow: 0 16px 34px rgba(114, 143, 150, 0.26); +} + +.fcb-lifecycle-card { + border-color: rgba(191, 208, 211, 0.78) !important; + transition: + border-color 260ms ease, + box-shadow 260ms cubic-bezier(0.22, 1, 0.36, 1), + transform 260ms cubic-bezier(0.22, 1, 0.36, 1), + background-color 260ms ease; +} + +.fcb-lifecycle-card:hover { + border-color: rgba(95, 135, 150, 0.9) !important; + box-shadow: 0 10px 24px rgba(86, 118, 126, 0.18); + transform: translate3d(0, -1px, 0); +} + +.fcb-interactive-row { + position: relative; + z-index: 0; + transition: + background-color 180ms ease, + border-color 180ms ease, + box-shadow 180ms ease, + transform 180ms ease; +} + +.fcb-interactive-row:hover { + z-index: 1; + box-shadow: inset 3px 0 0 rgba(95, 135, 150, 0.7), 0 10px 22px rgba(86, 118, 126, 0.16); + transform: translateY(-1px); +} + +.dark .theme-2026-card { + border-color: rgba(68, 86, 94, 0.82); + background: + linear-gradient(135deg, rgba(34, 49, 56, 0.96), rgba(24, 35, 42, 0.92)), + radial-gradient(circle at 14% 10%, rgba(102, 142, 156, 0.18), transparent 32%); + box-shadow: 0 16px 36px rgba(4, 10, 14, 0.34); +} + +.dark .theme-2026-card-hover:hover { + border-color: rgba(113, 153, 168, 0.68); + box-shadow: 0 20px 44px rgba(4, 10, 14, 0.46); +} + +.dark .fcb-lifecycle-card { + border-color: rgba(68, 86, 94, 0.86) !important; +} + +.dark .fcb-lifecycle-card:hover { + border-color: rgba(113, 153, 168, 0.82) !important; + box-shadow: 0 14px 30px rgba(4, 10, 14, 0.38); +} + +.data-table-2026 thead th { + background: rgba(236, 244, 246, 0.76); +} + +.data-table-2026 tbody tr { + transition: + background-color 180ms ease, + opacity 180ms ease; +} + +.data-table-2026 tbody tr:hover { + background: rgba(226, 236, 238, 0.46); +} + +.data-table-2026 tbody tr.is-selected { + background: rgba(213, 228, 230, 0.72); +} + +.data-table-2026 tbody tr.is-muted { + opacity: 0.74; +} + +.dark .data-table-2026 thead th { + background: rgba(31, 45, 52, 0.82); +} + +.dark .data-table-2026 tbody tr:hover { + background: rgba(45, 71, 81, 0.42); +} + +.dark .data-table-2026 tbody tr.is-selected-dark { + background: rgba(42, 64, 72, 0.68); +} + +.bg-indigo-50, +.bg-blue-50 { + background-color: #dce8eb !important; +} + +.bg-indigo-100, +.bg-blue-100 { + background-color: #d1e0e3 !important; +} + +.bg-indigo-500, +.bg-blue-500, +.bg-cyan-500 { + background-color: #6f98a6 !important; +} + +.bg-indigo-600, +.bg-blue-600, +.bg-cyan-600 { + background-color: #5f8796 !important; +} + +.bg-indigo-700, +.bg-blue-700, +.bg-cyan-700 { + background-color: #527887 !important; +} + +.bg-green-50 { + background-color: #e1eee8 !important; +} + +.bg-green-100 { + background-color: #d4e5dd !important; +} + +.bg-green-500, +.bg-green-600 { + background-color: #6f9688 !important; +} + +.bg-green-700 { + background-color: #5f8377 !important; +} + +.bg-red-50 { + background-color: #f1e2e5 !important; +} + +.bg-red-100 { + background-color: #e8d3d7 !important; +} + +.bg-red-500, +.bg-red-600 { + background-color: #9b6a72 !important; +} + +.bg-red-700 { + background-color: #895c63 !important; +} + +.bg-purple-50 { + background-color: #e7e2ea !important; +} + +.bg-purple-100 { + background-color: #ddd6e2 !important; +} + +.bg-purple-500, +.bg-pink-500 { + background-color: #8c8294 !important; +} + +.bg-purple-600, +.bg-pink-600 { + background-color: #7b7284 !important; +} + +.text-indigo-200, +.text-blue-200 { + color: #d8e8eb !important; +} + +.text-indigo-300, +.text-blue-300 { + color: #b8d4dc !important; +} + +.text-indigo-400, +.text-blue-400, +.text-cyan-400 { + color: #8fb2bf !important; +} + +.text-indigo-500, +.text-blue-500, +.text-cyan-500 { + color: #6f98a6 !important; +} + +.text-indigo-600, +.text-blue-600, +.text-cyan-600 { + color: #5f8796 !important; +} + +.text-indigo-700, +.text-blue-700 { + color: #3f6a77 !important; +} + +.text-green-300, +.text-green-400 { + color: #b6d6ca !important; +} + +.text-green-500, +.text-green-600, +.text-green-700 { + color: #5f8377 !important; +} + +.text-red-200, +.text-red-300, +.text-red-400 { + color: #e5c5ca !important; +} + +.text-red-500, +.text-red-600, +.text-red-700 { + color: #8b5962 !important; +} + +.text-purple-300, +.text-purple-400 { + color: #d4c8dc !important; +} + +.text-purple-500, +.text-purple-600, +.text-purple-700 { + color: #6f6379 !important; +} + +.border-indigo-100, +.border-blue-100 { + border-color: #cfe1e4 !important; +} + +.border-indigo-300, +.border-blue-300 { + border-color: #9db6bd !important; +} + +.border-indigo-400, +.border-indigo-500, +.border-blue-500 { + border-color: #8fb2bf !important; +} + +.border-indigo-600 { + border-color: #5f8796 !important; +} + +.border-red-100 { + border-color: #e8d3d7 !important; +} + +.border-red-200, +.border-red-500 { + border-color: #c9a4aa !important; +} + +.focus\:ring-indigo-500:focus, +.focus\:ring-blue-500:focus, +.focus\:ring-cyan-500:focus, +.focus\:ring-purple-500:focus { + --tw-ring-color: #8fb2bf !important; +} + +.focus\:border-indigo-500:focus, +.focus\:border-cyan-500:focus { + border-color: #8fb2bf !important; +} + +.hover\:bg-indigo-100:hover, +.hover\:bg-blue-100:hover { + background-color: #cfe1e4 !important; +} + +.hover\:bg-indigo-500:hover, +.hover\:bg-blue-500:hover, +.hover\:bg-cyan-500:hover { + background-color: #6f98a6 !important; +} + +.hover\:bg-indigo-600:hover, +.hover\:bg-blue-600:hover, +.hover\:bg-cyan-600:hover { + background-color: #527887 !important; +} + +.hover\:bg-indigo-700:hover, +.hover\:bg-blue-700:hover, +.hover\:bg-cyan-700:hover { + background-color: #466b78 !important; +} + +.hover\:bg-green-100:hover { + background-color: #d4e5dd !important; +} + +.hover\:bg-green-400:hover, +.hover\:bg-green-600:hover, +.hover\:bg-green-700:hover { + background-color: #5f8377 !important; +} + +.hover\:bg-red-100:hover { + background-color: #e8d3d7 !important; +} + +.hover\:bg-red-400:hover, +.hover\:bg-red-600:hover, +.hover\:bg-red-700:hover { + background-color: #895c63 !important; +} + +.hover\:border-indigo-500:hover { + border-color: #8fb2bf !important; +} + +.from-indigo-500, +.from-indigo-600, +.from-cyan-500, +.from-cyan-600 { + --tw-gradient-from: #5f8796 var(--tw-gradient-from-position) !important; + --tw-gradient-to: rgba(95, 135, 150, 0) var(--tw-gradient-to-position) !important; + --tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to) !important; +} + +.via-purple-500, +.via-purple-600 { + --tw-gradient-to: rgba(140, 130, 148, 0) var(--tw-gradient-to-position) !important; + --tw-gradient-stops: + var(--tw-gradient-from), + #8c8294 var(--tw-gradient-via-position), + var(--tw-gradient-to) !important; +} + +.to-purple-500, +.to-purple-600, +.to-pink-500, +.to-pink-600 { + --tw-gradient-to: #6f9688 var(--tw-gradient-to-position) !important; +} diff --git a/src/components/common/AlertComponent 2.vue b/src/components/common/AlertComponent 2.vue new file mode 100644 index 0000000..53d69fd --- /dev/null +++ b/src/components/common/AlertComponent 2.vue @@ -0,0 +1,88 @@ + + + + + diff --git a/src/components/common/BaseButton 2.vue b/src/components/common/BaseButton 2.vue new file mode 100644 index 0000000..f84ee00 --- /dev/null +++ b/src/components/common/BaseButton 2.vue @@ -0,0 +1,84 @@ + + + diff --git a/src/components/common/BaseModal 2.vue b/src/components/common/BaseModal 2.vue new file mode 100644 index 0000000..f3cf217 --- /dev/null +++ b/src/components/common/BaseModal 2.vue @@ -0,0 +1,174 @@ + + + + + diff --git a/src/components/common/BorderProgressBar 2.vue b/src/components/common/BorderProgressBar 2.vue new file mode 100644 index 0000000..b3adc70 --- /dev/null +++ b/src/components/common/BorderProgressBar 2.vue @@ -0,0 +1,154 @@ + + + + + diff --git a/src/components/common/ContentPreviewModal 2.vue b/src/components/common/ContentPreviewModal 2.vue new file mode 100644 index 0000000..0cfad8e --- /dev/null +++ b/src/components/common/ContentPreviewModal 2.vue @@ -0,0 +1,195 @@ + + + + + \ No newline at end of file diff --git a/src/components/common/DataPagination 2.vue b/src/components/common/DataPagination 2.vue new file mode 100644 index 0000000..6c4257d --- /dev/null +++ b/src/components/common/DataPagination 2.vue @@ -0,0 +1,130 @@ + + + diff --git a/src/components/common/DataTable 2.vue b/src/components/common/DataTable 2.vue new file mode 100644 index 0000000..e7d2caa --- /dev/null +++ b/src/components/common/DataTable 2.vue @@ -0,0 +1,67 @@ + + + diff --git a/src/components/common/ExpirationSelector 2.vue b/src/components/common/ExpirationSelector 2.vue new file mode 100644 index 0000000..3136740 --- /dev/null +++ b/src/components/common/ExpirationSelector 2.vue @@ -0,0 +1,112 @@ + + + diff --git a/src/components/common/FileDetailModal 2.vue b/src/components/common/FileDetailModal 2.vue new file mode 100644 index 0000000..d163991 --- /dev/null +++ b/src/components/common/FileDetailModal 2.vue @@ -0,0 +1,153 @@ + + + + + diff --git a/src/components/common/FileEditField 2.vue b/src/components/common/FileEditField 2.vue new file mode 100644 index 0000000..5a78305 --- /dev/null +++ b/src/components/common/FileEditField 2.vue @@ -0,0 +1,75 @@ + + + diff --git a/src/components/common/FileRecordList 2.vue b/src/components/common/FileRecordList 2.vue new file mode 100644 index 0000000..7222e80 --- /dev/null +++ b/src/components/common/FileRecordList 2.vue @@ -0,0 +1,52 @@ + + + + + diff --git a/src/components/common/FileUploadArea 2.vue b/src/components/common/FileUploadArea 2.vue new file mode 100644 index 0000000..99cf711 --- /dev/null +++ b/src/components/common/FileUploadArea 2.vue @@ -0,0 +1,345 @@ + + + diff --git a/src/components/common/FormInput 2.vue b/src/components/common/FormInput 2.vue new file mode 100644 index 0000000..c9f9868 --- /dev/null +++ b/src/components/common/FormInput 2.vue @@ -0,0 +1,60 @@ + + + \ No newline at end of file diff --git a/src/components/common/LanguageSwitcher 2.vue b/src/components/common/LanguageSwitcher 2.vue new file mode 100644 index 0000000..7166ffe --- /dev/null +++ b/src/components/common/LanguageSwitcher 2.vue @@ -0,0 +1,111 @@ + + + diff --git a/src/components/common/NativeDateSelect 2.vue b/src/components/common/NativeDateSelect 2.vue new file mode 100644 index 0000000..224516d --- /dev/null +++ b/src/components/common/NativeDateSelect 2.vue @@ -0,0 +1,271 @@ + + + + + diff --git a/src/components/common/PageFooter 2.vue b/src/components/common/PageFooter 2.vue new file mode 100644 index 0000000..57e1c2e --- /dev/null +++ b/src/components/common/PageFooter 2.vue @@ -0,0 +1,72 @@ + + + diff --git a/src/components/common/PageHeader 2.vue b/src/components/common/PageHeader 2.vue new file mode 100644 index 0000000..8da010d --- /dev/null +++ b/src/components/common/PageHeader 2.vue @@ -0,0 +1,65 @@ + + + + + \ No newline at end of file diff --git a/src/components/common/RetrieveForm 2.vue b/src/components/common/RetrieveForm 2.vue new file mode 100644 index 0000000..72a6708 --- /dev/null +++ b/src/components/common/RetrieveForm 2.vue @@ -0,0 +1,107 @@ + + + + + \ No newline at end of file diff --git a/src/components/common/SendTypeSelector 2.vue b/src/components/common/SendTypeSelector 2.vue new file mode 100644 index 0000000..6bb8d1c --- /dev/null +++ b/src/components/common/SendTypeSelector 2.vue @@ -0,0 +1,56 @@ + + + \ No newline at end of file diff --git a/src/components/common/SentRecordDetailModal 2.vue b/src/components/common/SentRecordDetailModal 2.vue new file mode 100644 index 0000000..cbefc44 --- /dev/null +++ b/src/components/common/SentRecordDetailModal 2.vue @@ -0,0 +1,273 @@ + + + + + diff --git a/src/components/common/SentRecordList 2.vue b/src/components/common/SentRecordList 2.vue new file mode 100644 index 0000000..7e367f7 --- /dev/null +++ b/src/components/common/SentRecordList 2.vue @@ -0,0 +1,56 @@ + + + + + diff --git a/src/components/common/SettingNumberInput 2.vue b/src/components/common/SettingNumberInput 2.vue new file mode 100644 index 0000000..e566efa --- /dev/null +++ b/src/components/common/SettingNumberInput 2.vue @@ -0,0 +1,41 @@ + + + diff --git a/src/components/common/SettingSwitch 2.vue b/src/components/common/SettingSwitch 2.vue new file mode 100644 index 0000000..1a9643d --- /dev/null +++ b/src/components/common/SettingSwitch 2.vue @@ -0,0 +1,40 @@ + + + diff --git a/src/components/common/SideDrawer 2.vue b/src/components/common/SideDrawer 2.vue new file mode 100644 index 0000000..372a948 --- /dev/null +++ b/src/components/common/SideDrawer 2.vue @@ -0,0 +1,131 @@ + + + + + diff --git a/src/components/common/SmoothTrendCanvas 2.vue b/src/components/common/SmoothTrendCanvas 2.vue new file mode 100644 index 0000000..8c4c96a --- /dev/null +++ b/src/components/common/SmoothTrendCanvas 2.vue @@ -0,0 +1,551 @@ + + + diff --git a/src/components/common/StatCard 2.vue b/src/components/common/StatCard 2.vue new file mode 100644 index 0000000..e1bdb12 --- /dev/null +++ b/src/components/common/StatCard 2.vue @@ -0,0 +1,79 @@ + + + diff --git a/src/components/common/TextInputArea 2.vue b/src/components/common/TextInputArea 2.vue new file mode 100644 index 0000000..169377e --- /dev/null +++ b/src/components/common/TextInputArea 2.vue @@ -0,0 +1,94 @@ + + + + + \ No newline at end of file diff --git a/src/components/common/ThemeToggle 2.vue b/src/components/common/ThemeToggle 2.vue new file mode 100644 index 0000000..5510417 --- /dev/null +++ b/src/components/common/ThemeToggle 2.vue @@ -0,0 +1,31 @@ + + + diff --git a/src/components/common/scrollLock 2.ts b/src/components/common/scrollLock 2.ts new file mode 100644 index 0000000..9bad0a6 --- /dev/null +++ b/src/components/common/scrollLock 2.ts @@ -0,0 +1,22 @@ +type ScrollLockOwner = symbol + +let owners = new Set() +let previousOverflow = '' + +export function lockBodyScroll(): ScrollLockOwner { + const owner = Symbol('scroll-lock-owner') + if (owners.size === 0) { + previousOverflow = document.body.style.overflow + document.body.style.overflow = 'hidden' + } + owners.add(owner) + return owner +} + +export function unlockBodyScroll(owner: ScrollLockOwner | null | undefined): void { + if (!owner || !owners.delete(owner)) return + if (owners.size === 0) { + document.body.style.overflow = previousOverflow + previousOverflow = '' + } +} diff --git a/src/composables/index 2.ts b/src/composables/index 2.ts new file mode 100644 index 0000000..bfac958 --- /dev/null +++ b/src/composables/index 2.ts @@ -0,0 +1,17 @@ +export { useAdminActivities } from './useAdminActivities' +export { useAdminTrash } from './useAdminTrash' +export { useAdminFiles } from './useAdminFiles' +export { useAdminLogin } from './useAdminLogin' +export { useAdminSession } from './useAdminSession' +export { useAppShell } from './useAppShell' +export { useDashboardStats } from './useDashboardStats' +export { useInjectedDarkMode } from './useInjectedDarkMode' +export { useClipboard } from './useClipboard' +export { usePresignedUpload } from './usePresignedUpload' +export { usePublicConfigBootstrap } from './usePublicConfigBootstrap' +export { useRetrieveFlow } from './useRetrieveFlow' +export { useRouteLoading } from './useRouteLoading' +export { useSendFlow } from './useSendFlow' +export { useSystemConfig } from './useSystemConfig' +export { useTheme } from './useTheme' +export { useTransferAnalytics } from './useTransferAnalytics' diff --git a/src/composables/useAdminActivities 2.ts b/src/composables/useAdminActivities 2.ts new file mode 100644 index 0000000..3405e8a --- /dev/null +++ b/src/composables/useAdminActivities 2.ts @@ -0,0 +1,13 @@ +import { ActivityService } from '@/services' +import type { AdminActivityListParams, AdminActivityListResponse } from '@/types' + +export function useAdminActivities() { + const fetchAdminActivities = async ( + params: AdminActivityListParams + ): Promise => { + const response = await ActivityService.getAdminActivities(params) + return response.detail || null + } + + return { fetchAdminActivities } +} diff --git a/src/composables/useAdminFiles 2.ts b/src/composables/useAdminFiles 2.ts new file mode 100644 index 0000000..059c061 --- /dev/null +++ b/src/composables/useAdminFiles 2.ts @@ -0,0 +1,1849 @@ +import { computed, ref } from 'vue' +import { useI18n } from 'vue-i18n' +import { FileService } from '@/services' +import { useAlertStore } from '@/stores/alertStore' +import type { + AdminBatchEditForm, + AdminBatchDeleteFilesResponse, + AdminBatchPolicyActionRequest, + AdminBatchPolicyActionResponse, + AdminBatchUpdateFilesRequest, + AdminBatchUpdateFilesResponse, + AdminFileDetailResponse, + AdminFileDetailTimelineItem, + AdminFileDetailViewItem, + AdminFileMetadataRequest, + AdminFileInsightSeverity, + AdminFilePatchPayload, + AdminFileHealthFilter, + AdminFileListParams, + AdminFilePolicyAction, + AdminFilePolicyActionRequest, + AdminFileStatusFilter, + AdminFileSummary, + AdminFileTypeFilter, + AdminFileViewPreset, + AdminFileViewPresetParams, + AdminFileViewPresetRequest, + AdminFileViewItem, + ApiResponse, + FileEditForm, + FileListItem +} from '@/types' +import { copyToClipboard } from '@/utils/clipboard' +import { formatDuration, formatFileSize, formatTimestamp, getErrorMessage } from '@/utils/common' +import { + downloadAdminManagedFile, + exportAdminTextFile, + getSafeFilename +} from '@/utils/download-action' +import { buildRetrieveUrl } from '@/utils/share-url' + +const emptySummary = (): AdminFileSummary => ({ + totalFiles: 0, + activeCount: 0, + expiredCount: 0, + textCount: 0, + fileCount: 0, + chunkedCount: 0, + healthAttentionCount: 0, + healthDangerCount: 0, + healthWarningCount: 0, + expiringSoonCount: 0, + storageIssueCount: 0, + neverRetrievedCount: 0, + healthyCount: 0, + permanentCount: 0, + storageUsed: 0, + usedCount: 0 +}) + +const normalizeCount = (value: number | string | null | undefined) => Number(value || 0) + +const isExpiredByDate = (value: string | null | undefined) => { + if (!value) return false + const timestamp = new Date(value).getTime() + return Number.isFinite(timestamp) && timestamp < Date.now() +} + +type ErrorWithResponse = { + response?: { + status?: number + } +} + +const isLegacyEndpointUnavailable = (error: unknown) => { + const status = (error as ErrorWithResponse)?.response?.status + return status === 404 || status === 405 +} + +const legacyForeverExpiresAt = '2099-12-31T23:59' +const detailPolicyDownloadLimit = 5 +const hourInMilliseconds = 60 * 60 * 1000 +const dayInMilliseconds = 24 * 60 * 60 * 1000 +const adminPageSizeOptions = [5, 10, 20, 50, 100] as const +const defaultAdminPageSize = 10 +const legacyUsedCountTimelineKeys = new Set(['legacy-used-count', 'legacy_used_count']) + +type DetailPolicyActionOption = { + action: AdminFilePolicyAction + label: string + description: string + disabled?: boolean +} + +type BatchPolicyActionOption = DetailPolicyActionOption + +type HealthFilterOption = { + value: AdminFileHealthFilter + label: string + count?: number +} + +const emptyBatchEditForm = (): AdminBatchEditForm => ({ + mode: 'expiresAt', + expired_at: '', + expired_count: null, + relative_expire_value: null, + relative_expire_unit: 'hours' +}) + +const metadataTagSeparatorPattern = /[,,\n]+/ + +const emptyDetailMetadataForm = () => ({ + note: '', + tagsText: '' +}) + +const padDatePart = (value: number) => String(value).padStart(2, '0') + +const formatLocalDateTime = (date: Date) => { + const year = date.getFullYear() + const month = padDatePart(date.getMonth() + 1) + const day = padDatePart(date.getDate()) + const hours = padDatePart(date.getHours()) + const minutes = padDatePart(date.getMinutes()) + + return `${year}-${month}-${day}T${hours}:${minutes}` +} + +const builtInAllViewPresetId = 'built_in_all' +const adminFileStatusFilters: AdminFileStatusFilter[] = ['all', 'active', 'expired'] +const adminFileTypeFilters: AdminFileTypeFilter[] = ['all', 'file', 'text', 'chunked'] +const adminFileHealthFilters: AdminFileHealthFilter[] = [ + 'all', + 'attention', + 'danger', + 'warning', + 'healthy', + 'expired', + 'expiring_soon', + 'storage_issue', + 'never_retrieved', + 'permanent' +] +const adminFileSortFields = [ + 'created_at', + 'expired_at', + 'name', + 'size', + 'used_count', + 'code' +] as const +const adminFileSortOrders = ['asc', 'desc'] as const + +type RawViewPresetParams = Partial< + Record +> + +const normalizePresetChoice = ( + value: unknown, + allowedValues: readonly T[], + fallback: T +): T => { + const normalizedValue = String(value ?? fallback) + .replace('-', '_') + .trim() + .toLowerCase() + return allowedValues.includes(normalizedValue as T) ? (normalizedValue as T) : fallback +} + +const normalizePresetSize = (value: unknown) => { + const normalizedSize = Number(value) + const pageSize = Number.isFinite(normalizedSize) ? Math.trunc(normalizedSize) : defaultAdminPageSize + return adminPageSizeOptions.includes(pageSize as (typeof adminPageSizeOptions)[number]) + ? pageSize + : defaultAdminPageSize +} + +const buildDefaultViewPresetParams = (): AdminFileViewPresetParams => ({ + keyword: '', + status: 'all', + type: 'all', + health: 'all', + sortBy: 'created_at', + sortOrder: 'desc', + size: defaultAdminPageSize +}) + +const normalizeViewPresetParams = (params: unknown): AdminFileViewPresetParams => { + const defaults = buildDefaultViewPresetParams() + const rawParams = + params && typeof params === 'object' + ? (params as RawViewPresetParams) + : ({} as RawViewPresetParams) + + return { + keyword: String(rawParams.keyword ?? defaults.keyword).trim(), + status: normalizePresetChoice(rawParams.status, adminFileStatusFilters, defaults.status), + type: normalizePresetChoice(rawParams.type, adminFileTypeFilters, defaults.type), + health: normalizePresetChoice(rawParams.health, adminFileHealthFilters, defaults.health), + sortBy: normalizePresetChoice( + rawParams.sortBy ?? rawParams.sort_by, + adminFileSortFields, + defaults.sortBy + ), + sortOrder: normalizePresetChoice( + rawParams.sortOrder ?? rawParams.sort_order, + adminFileSortOrders, + defaults.sortOrder + ), + size: normalizePresetSize(rawParams.size ?? defaults.size) + } +} + +export function useAdminFiles() { + const { t } = useI18n() + const alertStore = useAlertStore() + + const tableData = ref([]) + const hasLoadError = ref(false) + const isLoading = ref(false) + const isSaving = ref(false) + const summary = ref(emptySummary()) + const params = ref({ + page: 1, + size: defaultAdminPageSize, + total: 0, + keyword: '', + status: 'all', + type: 'all', + health: 'all', + sortBy: 'created_at', + sortOrder: 'desc' + }) + + const showEditModal = ref(false) + const editForm = ref({ + id: null, + code: '', + prefix: '', + suffix: '', + expired_at: '', + expired_count: null + }) + const showBatchEditModal = ref(false) + const batchEditForm = ref(emptyBatchEditForm()) + + const showTextPreview = ref(false) + const previewText = ref('') + const previewFile = ref(null) + const previewMetaText = ref('') + const isPreviewLoading = ref(false) + const showFileDetailModal = ref(false) + const selectedFileDetail = ref(null) + const isDetailLoading = ref(false) + const isDetailPolicyActionRunning = ref(false) + const isDetailMetadataSaving = ref(false) + const detailMetadataForm = ref(emptyDetailMetadataForm()) + const downloadingFileId = ref(null) + const selectedFileIds = ref>(new Set()) + const isBatchDeleting = ref(false) + const isBatchUpdating = ref(false) + const isBatchPolicyActionRunning = ref(false) + const savedViewPresets = ref([]) + const selectedViewPresetId = ref(builtInAllViewPresetId) + const isViewPresetLoading = ref(false) + const isViewPresetSaving = ref(false) + const isViewPresetDeleting = ref(false) + let detailRequestSerial = 0 + const isBatchActionRunning = computed( + () => isBatchDeleting.value || isBatchUpdating.value || isBatchPolicyActionRunning.value + ) + const totalPages = computed(() => Math.max(Math.ceil(params.value.total / params.value.size), 1)) + const storageUsedText = computed(() => formatFileSize(summary.value.storageUsed)) + const currentPageSelectedCount = computed( + () => tableData.value.filter((file) => selectedFileIds.value.has(file.id)).length + ) + const selectedCount = computed(() => selectedFileIds.value.size) + const hasSelectedFiles = computed(() => selectedCount.value > 0) + const selectedFilesOnCurrentPage = computed(() => + tableData.value.filter((file) => selectedFileIds.value.has(file.id)) + ) + const selectedHasPermanentFiles = computed(() => + selectedFilesOnCurrentPage.value.some((file) => file.isPermanentFile) + ) + const isAllCurrentPageSelected = computed( + () => tableData.value.length > 0 && currentPageSelectedCount.value === tableData.value.length + ) + const isCurrentPagePartiallySelected = computed( + () => currentPageSelectedCount.value > 0 && !isAllCurrentPageSelected.value + ) + + const requestParams = computed(() => ({ + page: params.value.page, + size: params.value.size, + keyword: params.value.keyword, + status: params.value.status === 'all' ? undefined : params.value.status, + type: params.value.type === 'all' ? undefined : params.value.type, + health: params.value.health === 'all' ? undefined : params.value.health, + sortBy: params.value.sortBy, + sortOrder: params.value.sortOrder + })) + + const hasActiveFilters = computed( + () => + Boolean(params.value.keyword?.trim()) || + params.value.status !== 'all' || + params.value.type !== 'all' || + params.value.health !== 'all' + ) + + const buildCurrentViewPresetParams = (): AdminFileViewPresetParams => ({ + keyword: params.value.keyword || '', + status: params.value.status || 'all', + type: params.value.type || 'all', + health: params.value.health || 'all', + sortBy: params.value.sortBy || 'created_at', + sortOrder: params.value.sortOrder || 'desc', + size: params.value.size || defaultAdminPageSize + }) + + const buildBuiltInViewPreset = ( + id: string, + nameKey: string, + filters: Partial = {} + ): AdminFileViewPreset => { + const presetFilters = normalizeViewPresetParams({ + ...buildDefaultViewPresetParams(), + ...filters + }) + + return { + id, + name: t(nameKey), + filters: presetFilters, + params: presetFilters, + isBuiltIn: true, + isDefault: id === builtInAllViewPresetId, + is_default: id === builtInAllViewPresetId + } + } + + const builtInViewPresets = computed(() => [ + buildBuiltInViewPreset(builtInAllViewPresetId, 'fileManage.viewPresetAll'), + buildBuiltInViewPreset('built_in_attention', 'fileManage.viewPresetAttention', { + health: 'attention' + }), + buildBuiltInViewPreset('built_in_expiring_soon', 'fileManage.viewPresetExpiringSoon', { + health: 'expiring_soon' + }), + buildBuiltInViewPreset('built_in_storage_issue', 'fileManage.viewPresetStorageIssue', { + health: 'storage_issue' + }), + buildBuiltInViewPreset('built_in_never_retrieved', 'fileManage.viewPresetNeverRetrieved', { + health: 'never_retrieved' + }), + buildBuiltInViewPreset('built_in_permanent', 'fileManage.viewPresetPermanent', { + health: 'permanent' + }) + ]) + + const viewPresets = computed(() => [ + ...builtInViewPresets.value, + ...savedViewPresets.value + ]) + + const healthFilterOptions = computed(() => [ + { value: 'all', label: t('fileManage.healthFilters.all'), count: summary.value.totalFiles }, + { + value: 'attention', + label: t('fileManage.healthFilters.attention'), + count: summary.value.healthAttentionCount + }, + { + value: 'danger', + label: t('fileManage.healthFilters.danger'), + count: summary.value.healthDangerCount + }, + { + value: 'warning', + label: t('fileManage.healthFilters.warning'), + count: summary.value.healthWarningCount + }, + { + value: 'expiring_soon', + label: t('fileManage.healthFilters.expiringSoon'), + count: summary.value.expiringSoonCount + }, + { + value: 'storage_issue', + label: t('fileManage.healthFilters.storageIssue'), + count: summary.value.storageIssueCount + }, + { + value: 'never_retrieved', + label: t('fileManage.healthFilters.neverRetrieved'), + count: summary.value.neverRetrievedCount + }, + { + value: 'healthy', + label: t('fileManage.healthFilters.healthy'), + count: summary.value.healthyCount + }, + { + value: 'permanent', + label: t('fileManage.healthFilters.permanent'), + count: summary.value.permanentCount + } + ]) + + const createPolicyActionOptions = (disablePermanentActions = false): DetailPolicyActionOption[] => [ + { + action: 'extend_24h', + label: t('fileManage.policyActions.extend24h'), + description: t('fileManage.policyActionDescriptions.extend24h'), + disabled: disablePermanentActions + }, + { + action: 'extend_7d', + label: t('fileManage.policyActions.extend7d'), + description: t('fileManage.policyActionDescriptions.extend7d'), + disabled: disablePermanentActions + }, + { + action: 'make_permanent', + label: t('fileManage.policyActions.makePermanent'), + description: t('fileManage.policyActionDescriptions.makePermanent'), + disabled: disablePermanentActions + }, + { + action: 'reset_download_limit', + label: t('fileManage.policyActions.resetDownloadLimit', { + count: detailPolicyDownloadLimit + }), + description: t('fileManage.policyActionDescriptions.resetDownloadLimit', { + count: detailPolicyDownloadLimit + }) + } + ] + + const detailPolicyActionOptions = computed(() => + createPolicyActionOptions(Boolean(selectedFileDetail.value?.isPermanentFile)).filter( + (option) => !option.disabled + ) + ) + + const batchPolicyActionOptions = computed( + () => createPolicyActionOptions(selectedHasPermanentFiles.value) + ) + + const inferIsText = (file: FileListItem) => { + if (typeof file.isText === 'boolean') return file.isText + if (typeof file.is_text === 'boolean') return file.is_text + if (file.type) return file.type === 'text' + return Boolean(file.text) + } + + const inferIsExpired = (file: FileListItem) => { + if (typeof file.isExpired === 'boolean') return file.isExpired + if (typeof file.is_expired === 'boolean') return file.is_expired + if ( + file.expired_count !== null && + file.expired_count !== undefined && + file.expired_count === 0 + ) { + return true + } + return isExpiredByDate(file.expired_at) + } + + const inferIsChunked = (file: FileListItem) => Boolean(file.isChunked ?? file.is_chunked) + + const getRemainingDownloads = (file: FileListItem) => { + if (file.remainingDownloads !== undefined) return file.remainingDownloads + if (file.remaining_downloads !== undefined) return file.remaining_downloads + if ( + file.expired_count !== null && + file.expired_count !== undefined && + file.expired_count >= 0 + ) { + return Math.max(file.expired_count, 0) + } + return null + } + + const buildFallbackSummary = (files: AdminFileViewItem[], total: number): AdminFileSummary => ({ + totalFiles: total, + activeCount: files.filter((file) => !file.isExpiredFile).length, + expiredCount: files.filter((file) => file.isExpiredFile).length, + textCount: files.filter((file) => file.isTextFile).length, + fileCount: files.filter((file) => !file.isTextFile).length, + chunkedCount: files.filter((file) => file.isChunkedFile).length, + healthAttentionCount: files.filter((file) => + ['danger', 'warning'].includes(file.statusInsightSeverity) + ).length, + healthDangerCount: files.filter((file) => file.statusInsightSeverity === 'danger').length, + healthWarningCount: files.filter((file) => file.statusInsightSeverity === 'warning').length, + expiringSoonCount: files.filter((file) => file.statusInsightReasons.includes('expires_soon')) + .length, + storageIssueCount: files.filter((file) => + file.statusInsightReasons.includes('storage_metadata_incomplete') + ).length, + neverRetrievedCount: files.filter((file) => + file.statusInsightReasons.includes('never_retrieved') + ).length, + healthyCount: files.filter((file) => file.statusInsightSeverity === 'success').length, + permanentCount: files.filter((file) => file.statusInsightState === 'permanent').length, + storageUsed: files.reduce((totalSize, file) => totalSize + normalizeCount(file.size), 0), + usedCount: files.reduce( + (totalUsed, file) => totalUsed + normalizeCount(file.usedCount ?? file.used_count), + 0 + ) + }) + + const normalizeSummary = ( + rawSummary: Partial | undefined, + files: AdminFileViewItem[], + total: number + ): AdminFileSummary => { + const fallback = buildFallbackSummary(files, total) + if (!rawSummary) return fallback + + return { + totalFiles: normalizeCount(rawSummary.totalFiles ?? fallback.totalFiles), + activeCount: normalizeCount(rawSummary.activeCount ?? fallback.activeCount), + expiredCount: normalizeCount(rawSummary.expiredCount ?? fallback.expiredCount), + textCount: normalizeCount(rawSummary.textCount ?? fallback.textCount), + fileCount: normalizeCount(rawSummary.fileCount ?? fallback.fileCount), + chunkedCount: normalizeCount(rawSummary.chunkedCount ?? fallback.chunkedCount), + healthAttentionCount: normalizeCount( + rawSummary.healthAttentionCount ?? fallback.healthAttentionCount + ), + healthDangerCount: normalizeCount(rawSummary.healthDangerCount ?? fallback.healthDangerCount), + healthWarningCount: normalizeCount( + rawSummary.healthWarningCount ?? fallback.healthWarningCount + ), + expiringSoonCount: normalizeCount(rawSummary.expiringSoonCount ?? fallback.expiringSoonCount), + storageIssueCount: normalizeCount(rawSummary.storageIssueCount ?? fallback.storageIssueCount), + neverRetrievedCount: normalizeCount( + rawSummary.neverRetrievedCount ?? fallback.neverRetrievedCount + ), + healthyCount: normalizeCount(rawSummary.healthyCount ?? fallback.healthyCount), + permanentCount: normalizeCount(rawSummary.permanentCount ?? fallback.permanentCount), + storageUsed: normalizeCount(rawSummary.storageUsed ?? fallback.storageUsed), + usedCount: normalizeCount(rawSummary.usedCount ?? fallback.usedCount) + } + } + + const normalizeInsightSeverity = ( + severity: AdminFileInsightSeverity | undefined + ): AdminFileInsightSeverity => { + if (severity === 'success' || severity === 'warning' || severity === 'danger') { + return severity + } + if (severity === 'info' || severity === 'neutral') { + return severity + } + return 'neutral' + } + + const createFileViewItem = (file: FileListItem): AdminFileViewItem => { + const isTextFile = inferIsText(file) + const isExpiredFile = inferIsExpired(file) + const isChunkedFile = inferIsChunked(file) + const remainingDownloadsValue = getRemainingDownloads(file) + const usedCount = normalizeCount(file.usedCount ?? file.used_count) + const statusInsights = file.statusInsights ?? file.status_insights + const isPermanentFile = + !file.expired_at && + (file.expired_count === null || file.expired_count === undefined || file.expired_count < 0) + const statusInsightState = + statusInsights?.state ?? + (isExpiredFile ? 'expired' : isPermanentFile ? 'permanent' : 'available') + const statusInsightNextAction = + statusInsights?.nextAction ?? statusInsights?.next_action ?? 'monitor' + const statusInsightSeverity = normalizeInsightSeverity(statusInsights?.severity) + + return { + ...file, + displayName: file.name || `${file.prefix}${file.suffix}` || file.code, + displaySize: formatFileSize(file.size), + displayExpiredAt: file.expired_at + ? formatTimestamp(file.expired_at) + : t('send.expiration.units.forever'), + displayUsage: `${usedCount} ${t('common.times')}`, + displayHealthState: t(`fileManage.insightStates.${statusInsightState}`), + displayHealthAction: t(`fileManage.insightActions.${statusInsightNextAction}`), + isTextFile, + isExpiredFile, + isPermanentFile, + isChunkedFile, + remainingDownloadsValue, + canPreviewText: isTextFile, + statusInsightSeverity, + statusInsightState, + statusInsightNextAction, + statusInsightReasons: statusInsights?.reasons || [] + } + } + + const normalizeTimelineNumber = (value: unknown) => { + if (typeof value === 'number' && Number.isFinite(value)) return value + if (typeof value === 'string' && value.trim() !== '') { + const numberValue = Number(value) + if (Number.isFinite(numberValue)) return numberValue + } + return null + } + + const hasNumericTimelineValue = (item: AdminFileDetailTimelineItem) => + normalizeTimelineNumber(item.value) !== null + + const isLegacyUsedCountTimelineValue = (value: unknown) => + typeof value === 'string' && legacyUsedCountTimelineKeys.has(value.trim()) + + const normalizeTimelineItem = ( + item: AdminFileDetailTimelineItem, + fallbackUsedCount: number + ) => { + const normalizedItem = { ...item } + + if (legacyUsedCountTimelineKeys.has(normalizedItem.key)) { + normalizedItem.key = 'retrieved' + } + + if (isLegacyUsedCountTimelineValue(normalizedItem.value)) { + normalizedItem.value = fallbackUsedCount > 0 ? fallbackUsedCount : null + } + + return normalizedItem + } + + const getTimelineTranslationKey = (item: AdminFileDetailTimelineItem) => { + if ( + (item.key === 'retrieved' || + item.key === 'retrieved_event' || + legacyUsedCountTimelineKeys.has(item.key)) && + !hasNumericTimelineValue(item) && + !item.detail + ) { + return 'retrieved_event_unknown' + } + + return item.key + } + + const formatTimelineValue = (item: AdminFileDetailTimelineItem) => { + if (item.key === 'download_limit') { + if (item.status === 'unlimited') return t('fileManage.unlimited') + const numericValue = normalizeTimelineNumber(item.value) + if (numericValue !== null) return t('fileManage.remaining', { count: numericValue }) + } + + if ((item.key === 'retrieved' || item.key === 'retrieved_event') && hasNumericTimelineValue(item)) { + return `${normalizeTimelineNumber(item.value)} ${t('common.times')}` + } + + if (item.key === 'expiration_policy') { + if (item.status === 'unlimited') return t('send.expiration.units.forever') + const numericValue = normalizeTimelineNumber(item.value) + if (numericValue !== null) { + const duration = formatDuration(Math.abs(numericValue), (key) => t(key)) + return numericValue <= 0 + ? t('fileManage.timeline.expiration_policy.overdue', { time: duration }) + : t('fileManage.timeline.expiration_policy.remaining', { time: duration }) + } + } + + if (item.detail) return item.detail + const numericValue = normalizeTimelineNumber(item.value) + if (numericValue !== null) return String(numericValue) + return '' + } + + const formatTimelineTitleValue = (item: AdminFileDetailTimelineItem, valueText: string) => { + if (item.key === 'retrieved_event') { + const numericValue = normalizeTimelineNumber(item.value) + return numericValue === null ? '' : String(numericValue) + } + + return valueText + } + + const createTimelineViewItems = ( + items: AdminFileDetailTimelineItem[] = [], + fallbackUsedCount = 0 + ) => + items.map((rawItem) => { + const item = normalizeTimelineItem(rawItem, fallbackUsedCount) + const timelineKey = getTimelineTranslationKey(item) + const timestampText = item.timestamp ? formatTimestamp(item.timestamp) : '' + const valueText = formatTimelineValue(item) + const titleValue = formatTimelineTitleValue(item, valueText) + const metaParts = [timestampText, valueText].filter(Boolean) + return { + ...item, + severity: normalizeInsightSeverity(item.severity), + displayTitle: t(`fileManage.timeline.${timelineKey}.title`, { + status: t(`fileManage.timeline.status.${item.status || 'pending'}`), + detail: item.detail || '', + value: titleValue + }), + displayDescription: t(`fileManage.timeline.${timelineKey}.description`, { + status: t(`fileManage.timeline.status.${item.status || 'pending'}`), + detail: item.detail || '', + value: valueText || '' + }), + displayMeta: metaParts.length > 0 ? metaParts.join(' · ') : '-' + } + }) + + const normalizeMetadataTags = (tags: string[] | undefined) => + Array.isArray(tags) ? tags.map((tag) => String(tag).trim()).filter(Boolean) : [] + + const parseMetadataTags = (value: string) => + normalizeMetadataTags(value.split(metadataTagSeparatorPattern)) + + const formatMetadataTags = (tags: string[]) => normalizeMetadataTags(tags).join(', ') + + const createFileDetailViewItem = ( + file: FileListItem | AdminFileDetailResponse + ): AdminFileDetailViewItem => { + const detail = file as AdminFileDetailResponse + const policy = detail.policy + const storage = detail.storage + const expiredAt = policy?.expiredAt ?? policy?.expired_at ?? file.expired_at ?? null + const expiredCount = policy?.expiredCount ?? policy?.expired_count ?? file.expired_count ?? null + const prefixedName = `${file.prefix || ''}${file.suffix || ''}` + const displayName = + detail.displayName ?? + detail.display_name ?? + detail.filename ?? + file.name ?? + (prefixedName || file.code) + const normalizedFile: FileListItem = { + ...file, + name: displayName, + expired_at: expiredAt, + expired_count: expiredCount + } + const viewItem = createFileViewItem(normalizedFile) + const remainingDownloadsValue = + policy?.remainingDownloads ?? policy?.remaining_downloads ?? viewItem.remainingDownloadsValue + const canPreviewText = + detail.canPreviewText ?? detail.can_preview_text ?? viewItem.canPreviewText + const canDownloadFile = detail.canDownload ?? detail.can_download ?? !viewItem.isExpiredFile + const textLengthValue = normalizeCount( + detail.textLength ?? detail.text_length ?? detail.text?.length + ) + const isPermanentFile = + detail.isPermanent ?? + detail.is_permanent ?? + policy?.isPermanent ?? + policy?.is_permanent ?? + (!expiredAt && (expiredCount === null || expiredCount === undefined || expiredCount < 0)) + const hasDownloadLimitFile = + detail.hasDownloadLimit ?? + detail.has_download_limit ?? + (expiredCount !== null && expiredCount !== undefined && expiredCount >= 0) + const hasExpirationTimeFile = + detail.hasExpirationTime ?? detail.has_expiration_time ?? Boolean(expiredAt) + const storageBackendValue = + storage?.backend ?? detail.storageBackend ?? detail.storage_backend ?? '-' + const isChunkedStorage = storage?.isChunked ?? storage?.is_chunked ?? viewItem.isChunkedFile + const statusInsights = detail.statusInsights ?? detail.status_insights + const statusInsightState = + statusInsights?.state ?? + (viewItem.isExpiredFile ? 'expired' : isPermanentFile ? 'permanent' : 'available') + const statusInsightNextAction = + statusInsights?.nextAction ?? statusInsights?.next_action ?? 'monitor' + const usedCountValue = normalizeCount( + detail.usedCount ?? + detail.used_count ?? + statusInsights?.metrics?.usedCount ?? + statusInsights?.metrics?.used_count ?? + file.usedCount ?? + file.used_count + ) + const metadata = detail.metadata ?? detail.meta + const metadataNote = detail.note ?? metadata?.note ?? '' + const metadataTags = normalizeMetadataTags(detail.tags ?? metadata?.tags) + const metadataUpdatedAt = + detail.metadataUpdatedAt ?? + detail.metadata_updated_at ?? + metadata?.updatedAt ?? + metadata?.updated_at ?? + null + + return { + ...viewItem, + displayName, + displayExpiredAt: expiredAt ? formatTimestamp(expiredAt) : t('send.expiration.units.forever'), + displayCreatedAt: file.created_at ? formatTimestamp(file.created_at) : '-', + displayRetrieveUrl: buildRetrieveUrl(file.code), + remainingDownloadsValue, + canPreviewText, + textLengthValue, + canDownloadFile, + isPermanentFile, + hasDownloadLimitFile, + hasExpirationTimeFile, + isChunkedStorage: Boolean(isChunkedStorage), + storageBackendValue, + fileHashValue: storage?.fileHash ?? storage?.file_hash ?? detail.fileHash ?? detail.file_hash, + filePathValue: storage?.filePath ?? storage?.file_path ?? detail.filePath ?? detail.file_path, + uuidFileNameValue: + storage?.uuidFileName ?? + storage?.uuid_file_name ?? + detail.uuidFileName ?? + detail.uuid_file_name, + uploadIdValue: storage?.uploadId ?? storage?.upload_id ?? detail.uploadId ?? detail.upload_id, + metadataNote, + metadataTags, + metadataUpdatedAt, + statusInsightSeverity: normalizeInsightSeverity(statusInsights?.severity), + statusInsightState, + statusInsightNextAction, + statusInsightReasons: statusInsights?.reasons || [], + statusInsightMetrics: statusInsights?.metrics, + detailTimeline: createTimelineViewItems(detail.timeline || [], usedCountValue) + } + } + + const syncDetailMetadataForm = (file: AdminFileDetailViewItem | null) => { + detailMetadataForm.value = { + note: file?.metadataNote || '', + tagsText: file ? formatMetadataTags(file.metadataTags) : '' + } + } + + const setSelectedFileDetail = (file: FileListItem | AdminFileDetailResponse) => { + const nextFile = createFileDetailViewItem(file) + selectedFileDetail.value = nextFile + syncDetailMetadataForm(nextFile) + } + + const syncSelectedFilesWithCurrentPage = () => { + const visibleIds = new Set(tableData.value.map((file) => file.id)) + selectedFileIds.value = new Set( + Array.from(selectedFileIds.value).filter((id) => visibleIds.has(id)) + ) + } + + const clearSelection = () => { + selectedFileIds.value = new Set() + } + + const toggleFileSelection = (id: number) => { + const nextSelectedIds = new Set(selectedFileIds.value) + if (nextSelectedIds.has(id)) { + nextSelectedIds.delete(id) + } else { + nextSelectedIds.add(id) + } + selectedFileIds.value = nextSelectedIds + } + + const toggleCurrentPageSelection = () => { + if (isAllCurrentPageSelected.value) { + clearSelection() + return + } + + selectedFileIds.value = new Set(tableData.value.map((file) => file.id)) + } + + const resetEditForm = () => { + editForm.value = { + id: null, + code: '', + prefix: '', + suffix: '', + expired_at: '', + expired_count: null + } + } + + const resetBatchEditForm = () => { + batchEditForm.value = emptyBatchEditForm() + } + + const openBatchEditModal = () => { + if (!hasSelectedFiles.value || isBatchActionRunning.value) return + + resetBatchEditForm() + showBatchEditModal.value = true + } + + const closeBatchEditModal = (force = false) => { + if (isBatchUpdating.value && !force) return + + showBatchEditModal.value = false + resetBatchEditForm() + } + + const buildBatchUpdatePayload = (ids: number[]): AdminBatchUpdateFilesRequest | null => { + const form = batchEditForm.value + + if (form.mode === 'expiresAt') { + if (!form.expired_at) return null + return { + ids, + expired_at: form.expired_at + } + } + + if (form.mode === 'downloadLimit') { + if (form.expired_count === null || !Number.isFinite(form.expired_count)) return null + return { + ids, + expired_count: form.expired_count + } + } + + if (form.mode === 'relativeExpire') { + if ( + form.relative_expire_value === null || + !Number.isFinite(form.relative_expire_value) || + form.relative_expire_value <= 0 + ) { + return null + } + const duration = + form.relative_expire_value * + (form.relative_expire_unit === 'days' ? dayInMilliseconds : hourInMilliseconds) + return { + ids, + expired_at: formatLocalDateTime(new Date(Date.now() + duration)) + } + } + + return { + ids, + clearExpiredAt: true, + clear_expired_at: true + } + } + + const buildLegacyBatchPatchPayload = ( + id: number, + payload: AdminBatchUpdateFilesRequest + ): AdminFilePatchPayload => { + if (payload.clearExpiredAt || payload.clear_expired_at) { + return { + id, + expired_at: legacyForeverExpiresAt, + expired_count: -1 + } + } + + const patchPayload: AdminFilePatchPayload = { id } + if (payload.expired_at !== undefined) { + patchPayload.expired_at = payload.expired_at + } + if (payload.expired_count !== undefined) { + patchPayload.expired_count = payload.expired_count + } + return patchPayload + } + + const buildPolicyActionRequest = ( + file: AdminFileDetailViewItem, + action: AdminFilePolicyAction + ): AdminFilePolicyActionRequest => { + const request: AdminFilePolicyActionRequest = { + id: file.id, + action + } + + if (action === 'reset_download_limit') { + request.downloadLimit = detailPolicyDownloadLimit + request.download_limit = detailPolicyDownloadLimit + } + + return request + } + + const buildBatchPolicyActionRequest = ( + ids: number[], + action: AdminFilePolicyAction + ): AdminBatchPolicyActionRequest => { + const request: AdminBatchPolicyActionRequest = { + ids, + action + } + + if (action === 'reset_download_limit') { + request.downloadLimit = detailPolicyDownloadLimit + request.download_limit = detailPolicyDownloadLimit + } + + return request + } + + const getPolicyActionBaseDate = (file: Pick) => { + const now = new Date() + const expiredAt = file.expired_at ? new Date(file.expired_at) : null + if (!expiredAt || Number.isNaN(expiredAt.getTime()) || expiredAt.getTime() < now.getTime()) { + return now + } + return expiredAt + } + + const buildLegacyPolicyActionPayload = ( + file: Pick, + action: AdminFilePolicyAction + ): AdminFilePatchPayload => { + if (action === 'make_permanent') { + return { + id: file.id, + expired_at: legacyForeverExpiresAt, + expired_count: -1 + } + } + + if (action === 'reset_download_limit') { + return { + id: file.id, + expired_count: detailPolicyDownloadLimit + } + } + + const offsetDays = action === 'extend_7d' ? 7 : 1 + const nextExpiredAt = new Date( + getPolicyActionBaseDate(file).getTime() + offsetDays * dayInMilliseconds + ) + return { + id: file.id, + expired_at: formatLocalDateTime(nextExpiredAt) + } + } + + const getPresetParams = (preset: AdminFileViewPreset) => + normalizeViewPresetParams(preset.filters ?? preset.params) + + const normalizeSavedViewPreset = (preset: AdminFileViewPreset): AdminFileViewPreset | null => { + const id = String(preset.id || '').trim() + const name = String(preset.name || '').trim() + if (!id || !name) return null + + const presetParams = getPresetParams(preset) + return { + ...preset, + id, + name, + filters: presetParams, + params: presetParams, + isBuiltIn: false + } + } + + const upsertSavedViewPreset = (preset: AdminFileViewPreset) => { + const normalizedPreset = normalizeSavedViewPreset(preset) + if (!normalizedPreset) return null + + savedViewPresets.value = [ + ...savedViewPresets.value.filter((item) => item.id !== normalizedPreset.id), + normalizedPreset + ] + return normalizedPreset + } + + const buildViewPresetRequest = (name: string, id?: string): AdminFileViewPresetRequest | null => { + const normalizedName = name.trim() + if (!normalizedName) return null + + const filters = normalizeViewPresetParams(buildCurrentViewPresetParams()) + return { + id, + name: normalizedName, + filters, + params: filters + } + } + + const markViewPresetDirty = () => { + selectedViewPresetId.value = '' + } + + const loadViewPresets = async () => { + isViewPresetLoading.value = true + try { + const response = await FileService.getAdminFileViewPresets() + const rawPresets = response.detail?.presets ?? response.detail?.items ?? [] + savedViewPresets.value = rawPresets + .map((preset) => normalizeSavedViewPreset(preset)) + .filter((preset): preset is AdminFileViewPreset => Boolean(preset)) + + if ( + selectedViewPresetId.value && + !viewPresets.value.some((preset) => preset.id === selectedViewPresetId.value) + ) { + selectedViewPresetId.value = builtInAllViewPresetId + } + } catch (error: unknown) { + savedViewPresets.value = [] + alertStore.showAlert( + isLegacyEndpointUnavailable(error) + ? t('fileManage.viewPresetLoadFailed') + : getErrorMessage(error, t('fileManage.viewPresetLoadFailed')), + 'warning' + ) + } finally { + isViewPresetLoading.value = false + } + } + + const applyViewPreset = async (idOrPreset: string | AdminFileViewPreset) => { + const preset = + typeof idOrPreset === 'string' + ? viewPresets.value.find((item) => item.id === idOrPreset) + : idOrPreset + if (!preset) return + + const presetParams = getPresetParams(preset) + params.value.keyword = presetParams.keyword + params.value.status = presetParams.status + params.value.type = presetParams.type + params.value.health = presetParams.health + params.value.sortBy = presetParams.sortBy + params.value.sortOrder = presetParams.sortOrder + params.value.size = presetParams.size + params.value.page = 1 + selectedViewPresetId.value = preset.id + clearSelection() + await loadFiles() + } + + const saveCurrentViewPreset = async (name: string) => { + const request = buildViewPresetRequest(name) + if (!request || isViewPresetSaving.value) return null + + isViewPresetSaving.value = true + try { + const response = await FileService.saveAdminFileViewPreset(request) + const savedPreset = response.detail ? upsertSavedViewPreset(response.detail) : null + selectedViewPresetId.value = savedPreset?.id || selectedViewPresetId.value + alertStore.showAlert(t('fileManage.viewPresetSaveSuccess'), 'success') + return savedPreset + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.viewPresetSaveFailed')), 'error') + return null + } finally { + isViewPresetSaving.value = false + } + } + + const updateSelectedViewPreset = async () => { + const preset = savedViewPresets.value.find((item) => item.id === selectedViewPresetId.value) + if (!preset || isViewPresetSaving.value) return null + + const request = buildViewPresetRequest(preset.name, preset.id) + if (!request) return null + + isViewPresetSaving.value = true + try { + const response = await FileService.saveAdminFileViewPreset(request) + const savedPreset = response.detail ? upsertSavedViewPreset(response.detail) : null + selectedViewPresetId.value = savedPreset?.id || preset.id + alertStore.showAlert(t('fileManage.viewPresetSaveSuccess'), 'success') + return savedPreset + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.viewPresetSaveFailed')), 'error') + return null + } finally { + isViewPresetSaving.value = false + } + } + + const deleteSelectedViewPreset = async () => { + const preset = savedViewPresets.value.find((item) => item.id === selectedViewPresetId.value) + if (!preset || isViewPresetDeleting.value) return + if (!window.confirm(t('fileManage.viewPresetDeleteConfirm', { name: preset.name }))) return + + isViewPresetDeleting.value = true + try { + await FileService.deleteAdminFileViewPreset(preset.id) + savedViewPresets.value = savedViewPresets.value.filter((item) => item.id !== preset.id) + markViewPresetDirty() + alertStore.showAlert(t('fileManage.viewPresetDeleteSuccess'), 'success') + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.viewPresetDeleteFailed')), 'error') + } finally { + isViewPresetDeleting.value = false + } + } + + const refreshSelectedFileDetail = async (fileId: number, detail?: AdminFileDetailResponse) => { + if (detail) { + setSelectedFileDetail(detail) + return + } + + const fallbackFile = tableData.value.find((file) => file.id === fileId) + if (fallbackFile) { + setSelectedFileDetail(fallbackFile) + } + + try { + const response = await FileService.getAdminFileDetail(fileId) + if (response.detail) { + setSelectedFileDetail(response.detail) + } + } catch (error: unknown) { + if (!isLegacyEndpointUnavailable(error)) { + throw error + } + } + } + + const loadFiles = async () => { + isLoading.value = true + try { + hasLoadError.value = false + const res = await FileService.getAdminFileList(requestParams.value) + if (!res.detail) return + + tableData.value = res.detail.data.map(createFileViewItem) + params.value.total = res.detail.total + summary.value = normalizeSummary(res.detail.summary, tableData.value, res.detail.total) + syncSelectedFilesWithCurrentPage() + } catch (error) { + hasLoadError.value = true + alertStore.showAlert( + getErrorMessage(error, t('manage.fileManage.loadFileListFailed')), + 'error' + ) + } finally { + isLoading.value = false + } + } + + const handleSearch = async () => { + markViewPresetDirty() + params.value.page = 1 + await loadFiles() + } + + const refreshFiles = async () => { + await loadFiles() + } + + const resetFilters = async () => { + params.value.page = 1 + params.value.keyword = '' + params.value.status = 'all' + params.value.type = 'all' + params.value.health = 'all' + params.value.sortBy = 'created_at' + params.value.sortOrder = 'desc' + selectedViewPresetId.value = builtInAllViewPresetId + clearSelection() + await loadFiles() + } + + const setStatusFilter = async (status: AdminFileStatusFilter) => { + markViewPresetDirty() + params.value.status = status + params.value.page = 1 + await loadFiles() + } + + const setTypeFilter = async (type: AdminFileTypeFilter) => { + markViewPresetDirty() + params.value.type = type + params.value.page = 1 + await loadFiles() + } + + const setHealthFilter = async (health: AdminFileHealthFilter) => { + markViewPresetDirty() + params.value.health = health + params.value.page = 1 + await loadFiles() + } + + const handlePageChange = async (page: number | string) => { + if (typeof page === 'string') return + if (page < 1 || page > totalPages.value) return + + params.value.page = page + await loadFiles() + } + + const handlePageSizeChange = async (size: number) => { + params.value.size = normalizePresetSize(size) + params.value.page = 1 + markViewPresetDirty() + await loadFiles() + } + + const openEditModal = (file: FileListItem) => { + editForm.value = { + id: file.id, + code: file.code, + prefix: file.prefix, + suffix: file.suffix, + expired_at: file.expired_at ? file.expired_at.slice(0, 16) : '', + expired_count: file.expired_count + } + showEditModal.value = true + } + + const closeEditModal = () => { + showEditModal.value = false + resetEditForm() + } + + const handleUpdate = async () => { + if (isSaving.value) return + + isSaving.value = true + try { + await FileService.updateFile(editForm.value) + await loadFiles() + closeEditModal() + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('manage.fileManage.updateFailed')), 'error') + } finally { + isSaving.value = false + } + } + + const deleteFile = async (id: number) => { + if (!window.confirm(t('manage.fileManage.deleteConfirm'))) { + return + } + + try { + await FileService.deleteAdminFile(id) + if (tableData.value.length === 1 && params.value.page > 1) { + params.value.page -= 1 + } + selectedFileIds.value.delete(id) + selectedFileIds.value = new Set(selectedFileIds.value) + await loadFiles() + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('manage.fileManage.deleteFailed')), 'error') + } + } + + const deleteAdminFilesWithFallback = async ( + ids: number[] + ): Promise> => { + try { + return await FileService.deleteAdminFiles(ids) + } catch (error: unknown) { + if (!isLegacyEndpointUnavailable(error)) { + throw error + } + + await Promise.all(ids.map((id) => FileService.deleteAdminFile(id))) + return { + code: 200, + detail: { + deletedCount: ids.length, + deleted_count: ids.length, + deleted: ids, + missing: [], + failed: [] + } + } + } + } + + const updateAdminFilesWithFallback = async ( + ids: number[], + payload: AdminBatchUpdateFilesRequest + ): Promise> => { + try { + return await FileService.updateAdminFiles(payload) + } catch (error: unknown) { + if (!isLegacyEndpointUnavailable(error)) { + throw error + } + + await Promise.all( + ids.map((id) => FileService.updateFile(buildLegacyBatchPatchPayload(id, payload))) + ) + + return { + code: 200, + detail: { + updatedCount: ids.length, + updated_count: ids.length, + updated: ids, + missing: [], + failed: [] + } + } + } + } + + const applyAdminFilesPolicyActionWithFallback = async ( + ids: number[], + action: AdminFilePolicyAction + ): Promise> => { + const request = buildBatchPolicyActionRequest(ids, action) + try { + return await FileService.applyAdminFilesPolicyAction(request) + } catch (error: unknown) { + if (!isLegacyEndpointUnavailable(error)) { + throw error + } + + const filesById = new Map(tableData.value.map((file) => [file.id, file])) + const updated: number[] = [] + const missing: number[] = [] + const failed: { id: number; reason: string }[] = [] + + for (const id of ids) { + const file = filesById.get(id) + if (!file) { + missing.push(id) + continue + } + + try { + await FileService.updateFile(buildLegacyPolicyActionPayload(file, action)) + updated.push(id) + } catch (legacyError: unknown) { + failed.push({ id, reason: getErrorMessage(legacyError, t('common.unknownError')) }) + } + } + + return { + code: 200, + detail: { + requestedCount: ids.length, + requested_count: ids.length, + uniqueCount: ids.length, + unique_count: ids.length, + updatedCount: updated.length, + updated_count: updated.length, + missingCount: missing.length, + missing_count: missing.length, + failedCount: failed.length, + failed_count: failed.length, + action, + updated, + missing, + failed + } + } + } + } + + const deleteSelectedFiles = async () => { + if (!hasSelectedFiles.value || isBatchActionRunning.value) return + + const ids = Array.from(selectedFileIds.value) + if (!window.confirm(t('fileManage.batchDeleteConfirm', { count: ids.length }))) { + return + } + + isBatchDeleting.value = true + try { + const response = await deleteAdminFilesWithFallback(ids) + const detail = response.detail + const deletedCount = detail?.deletedCount ?? detail?.deleted_count ?? ids.length + const failedCount = detail?.failedCount ?? detail?.failed_count ?? 0 + + if (tableData.value.length <= deletedCount && params.value.page > 1) { + params.value.page -= 1 + } + + clearSelection() + await loadFiles() + alertStore.showAlert( + t( + failedCount > 0 + ? 'fileManage.batchDeletePartialSuccess' + : 'fileManage.batchDeleteSuccess', + { + count: deletedCount, + failed: failedCount + } + ), + failedCount > 0 ? 'warning' : 'success' + ) + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.batchDeleteFailed')), 'error') + } finally { + isBatchDeleting.value = false + } + } + + const handleBatchUpdate = async () => { + if (!hasSelectedFiles.value || isBatchActionRunning.value) return + + const ids = Array.from(selectedFileIds.value) + const payload = buildBatchUpdatePayload(ids) + if (!payload) { + alertStore.showAlert(t('fileManage.batchUpdateNoFields'), 'warning') + return + } + + if (!window.confirm(t('fileManage.batchUpdateConfirm', { count: ids.length }))) { + return + } + + isBatchUpdating.value = true + try { + const response = await updateAdminFilesWithFallback(ids, payload) + const detail = response.detail + const updatedCount = detail?.updatedCount ?? detail?.updated_count ?? ids.length + const failedCount = detail?.failedCount ?? detail?.failed_count ?? 0 + + clearSelection() + await loadFiles() + closeBatchEditModal(true) + alertStore.showAlert( + t( + failedCount > 0 + ? 'fileManage.batchUpdatePartialSuccess' + : 'fileManage.batchUpdateSuccess', + { + count: updatedCount, + failed: failedCount + } + ), + failedCount > 0 ? 'warning' : 'success' + ) + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.batchUpdateFailed')), 'error') + } finally { + isBatchUpdating.value = false + } + } + + const applySelectedPolicyAction = async (action: AdminFilePolicyAction) => { + if (!hasSelectedFiles.value || isBatchActionRunning.value) return + const selectedAction = batchPolicyActionOptions.value.find((option) => option.action === action) + if (selectedAction?.disabled) return + + const ids = Array.from(selectedFileIds.value) + const actionLabel = selectedAction?.label || action + if ( + !window.confirm( + t('fileManage.batchPolicyActionConfirm', { + count: ids.length, + action: actionLabel + }) + ) + ) { + return + } + + isBatchPolicyActionRunning.value = true + try { + const response = await applyAdminFilesPolicyActionWithFallback(ids, action) + const detail = response.detail + const updatedCount = detail?.updatedCount ?? detail?.updated_count ?? ids.length + const failedCount = + (detail?.failedCount ?? detail?.failed_count ?? 0) + + (detail?.missingCount ?? detail?.missing_count ?? 0) + + clearSelection() + await loadFiles() + alertStore.showAlert( + t( + failedCount > 0 + ? 'fileManage.batchPolicyActionPartialSuccess' + : 'fileManage.batchPolicyActionSuccess', + { + count: updatedCount, + failed: failedCount + } + ), + failedCount > 0 ? 'warning' : 'success' + ) + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.batchPolicyActionFailed')), 'error') + } finally { + isBatchPolicyActionRunning.value = false + } + } + + const openTextPreview = async (file: AdminFileViewItem) => { + if (!file.isTextFile || isPreviewLoading.value) return + + previewFile.value = file + previewText.value = file.text || '' + previewMetaText.value = '' + showTextPreview.value = true + isPreviewLoading.value = true + + try { + const response = await FileService.previewAdminFile(file.id) + if (!response.detail) { + throw new Error(t('fileManage.previewFailed')) + } + + previewText.value = response.detail.content + previewMetaText.value = response.detail.truncated + ? t('fileManage.previewTruncated', { + shown: response.detail.previewLength ?? response.detail.preview_length ?? 0, + total: response.detail.length + }) + : t('fileManage.previewComplete', { count: response.detail.length }) + } catch (error: unknown) { + if (file.text) { + previewText.value = file.text + previewMetaText.value = t('fileManage.previewFallback') + return + } + + closeTextPreview() + alertStore.showAlert(getErrorMessage(error, t('fileManage.previewFailed')), 'error') + } finally { + isPreviewLoading.value = false + } + } + + const closeTextPreview = () => { + showTextPreview.value = false + previewText.value = '' + previewFile.value = null + previewMetaText.value = '' + } + + const openFileDetail = async (file: AdminFileViewItem) => { + const requestSerial = ++detailRequestSerial + setSelectedFileDetail(file) + showFileDetailModal.value = true + isDetailLoading.value = true + + try { + const response = await FileService.getAdminFileDetail(file.id) + if (response.detail && requestSerial === detailRequestSerial) { + setSelectedFileDetail(response.detail) + } + } catch (error: unknown) { + if (isLegacyEndpointUnavailable(error)) return + + alertStore.showAlert(getErrorMessage(error, t('fileManage.detailFailed')), 'error') + } finally { + if (requestSerial === detailRequestSerial) { + isDetailLoading.value = false + } + } + } + + const applyDetailPolicyAction = async (action: AdminFilePolicyAction) => { + const file = selectedFileDetail.value + if (!file || isDetailPolicyActionRunning.value) return + if ( + file.isPermanentFile && + (action === 'extend_24h' || action === 'extend_7d' || action === 'make_permanent') + ) { + return + } + + isDetailPolicyActionRunning.value = true + try { + let nextDetail: AdminFileDetailResponse | undefined + + try { + const response = await FileService.applyAdminFilePolicyAction( + buildPolicyActionRequest(file, action) + ) + nextDetail = response.detail + } catch (error: unknown) { + if (!isLegacyEndpointUnavailable(error)) { + throw error + } + await FileService.updateFile(buildLegacyPolicyActionPayload(file, action)) + } + + await loadFiles() + await refreshSelectedFileDetail(file.id, nextDetail) + alertStore.showAlert(t('fileManage.policyActionSuccess'), 'success') + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.policyActionFailed')), 'error') + } finally { + isDetailPolicyActionRunning.value = false + } + } + + const updateDetailMetadata = async () => { + const file = selectedFileDetail.value + if (!file || isDetailMetadataSaving.value) return + + const payload: AdminFileMetadataRequest = { + id: file.id, + note: detailMetadataForm.value.note, + tags: parseMetadataTags(detailMetadataForm.value.tagsText) + } + + isDetailMetadataSaving.value = true + try { + const response = await FileService.updateAdminFileMetadata(payload) + if (response.detail) { + setSelectedFileDetail(response.detail) + } else { + await refreshSelectedFileDetail(file.id) + } + alertStore.showAlert(t('fileManage.metadataSaveSuccess'), 'success') + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.metadataSaveFailed')), 'error') + } finally { + isDetailMetadataSaving.value = false + } + } + + const closeFileDetail = () => { + detailRequestSerial += 1 + showFileDetailModal.value = false + selectedFileDetail.value = null + syncDetailMetadataForm(null) + isDetailLoading.value = false + } + + const copyText = async () => { + await copyToClipboard(previewText.value, { + successMsg: t('fileManage.copySuccess'), + errorMsg: t('fileManage.copyFailed'), + notify: (message, type) => alertStore.showAlert(message, type) + }) + } + + const copyDetailRetrieveCode = async () => { + if (!selectedFileDetail.value) return + + await copyToClipboard(selectedFileDetail.value.code, { + successMsg: t('fileManage.copyCodeSuccess'), + errorMsg: t('fileManage.copyFailed'), + notify: (message, type) => alertStore.showAlert(message, type) + }) + } + + const copyDetailRetrieveLink = async () => { + if (!selectedFileDetail.value) return + + await copyToClipboard(selectedFileDetail.value.displayRetrieveUrl, { + successMsg: t('fileManage.copyLinkSuccess'), + errorMsg: t('fileManage.copyFailed'), + notify: (message, type) => alertStore.showAlert(message, type) + }) + } + + const exportPreviewText = () => { + if (!previewFile.value || !previewText.value) return + exportAdminTextFile(previewFile.value, previewText.value) + } + + const downloadFile = async (file: AdminFileViewItem) => { + if (downloadingFileId.value) return + + downloadingFileId.value = file.id + try { + const response = await FileService.downloadAdminFile(file.id) + await downloadAdminManagedFile(file, response) + alertStore.showAlert( + t(file.isTextFile ? 'fileManage.exportSuccess' : 'fileManage.downloadSuccess', { + name: getSafeFilename(file.displayName || file.code) + }), + 'success' + ) + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('fileManage.downloadFailed')), 'error') + } finally { + downloadingFileId.value = null + } + } + + return { + tableData, + hasLoadError, + hasActiveFilters, + isLoading, + isAllCurrentPageSelected, + isBatchActionRunning, + isBatchDeleting, + isBatchPolicyActionRunning, + isBatchUpdating, + isCurrentPagePartiallySelected, + isDetailLoading, + isDetailMetadataSaving, + isDetailPolicyActionRunning, + isPreviewLoading, + isSaving, + isViewPresetDeleting, + isViewPresetLoading, + isViewPresetSaving, + batchEditForm, + batchPolicyActionOptions, + detailPolicyActionOptions, + detailMetadataForm, + downloadingFileId, + healthFilterOptions, + hasSelectedFiles, + params, + previewFile, + previewMetaText, + selectedFileDetail, + selectedCount, + selectedFileIds, + selectedHasPermanentFiles, + selectedViewPresetId, + storageUsedText, + summary, + showBatchEditModal, + showEditModal, + showFileDetailModal, + editForm, + showTextPreview, + previewText, + totalPages, + viewPresets, + applyViewPreset, + closeEditModal, + closeBatchEditModal, + closeFileDetail, + closeTextPreview, + copyDetailRetrieveCode, + copyDetailRetrieveLink, + copyText, + clearSelection, + deleteFile, + deleteSelectedFiles, + deleteSelectedViewPreset, + downloadFile, + exportPreviewText, + handlePageChange, + handlePageSizeChange, + handleSearch, + applyDetailPolicyAction, + applySelectedPolicyAction, + handleBatchUpdate, + handleUpdate, + loadViewPresets, + loadFiles, + openBatchEditModal, + openEditModal, + openFileDetail, + openTextPreview, + refreshFiles, + resetFilters, + saveCurrentViewPreset, + setHealthFilter, + setStatusFilter, + setTypeFilter, + updateSelectedViewPreset, + updateDetailMetadata, + toggleCurrentPageSelection, + toggleFileSelection + } +} diff --git a/src/composables/useAdminLogin 2.ts b/src/composables/useAdminLogin 2.ts new file mode 100644 index 0000000..8146e49 --- /dev/null +++ b/src/composables/useAdminLogin 2.ts @@ -0,0 +1,61 @@ +import { ref } from 'vue' +import { AuthService } from '@/services' +import { useAdminStore } from '@/stores/adminStore' +import { useAlertStore } from '@/stores/alertStore' +import { getErrorMessage } from '@/utils/common' +import { useI18n } from 'vue-i18n' + +export function useAdminLogin() { + const { t } = useI18n() + const alertStore = useAlertStore() + const adminStore = useAdminStore() + const password = ref('') + const isLoading = ref(false) + + const validateForm = () => { + if (!password.value) { + alertStore.showAlert(t('manage.login.invalidPassword'), 'error') + return false + } + + if (password.value.length < 6) { + alertStore.showAlert(t('manage.login.passwordTooShort'), 'error') + return false + } + + return true + } + + const handleSubmit = async () => { + if (!validateForm()) return false + + isLoading.value = true + try { + const response = await AuthService.login(password.value) + if (!response.detail?.token) { + alertStore.showAlert(t('manage.login.noValidToken'), 'error') + return false + } + + adminStore.login({ + id: response.detail.id || 'admin', + username: response.detail.username || 'admin', + token: response.detail.token, + token_type: response.detail.token_type, + expires_at: response.detail.expires_at + }) + return true + } catch (error: unknown) { + alertStore.showAlert(getErrorMessage(error, t('manage.login.loginFailed')), 'error') + return false + } finally { + isLoading.value = false + } + } + + return { + password, + isLoading, + handleSubmit + } +} diff --git a/src/composables/useAdminSession 2.ts b/src/composables/useAdminSession 2.ts new file mode 100644 index 0000000..f120f4d --- /dev/null +++ b/src/composables/useAdminSession 2.ts @@ -0,0 +1,40 @@ +import { AuthService } from '@/services' +import { useAdminStore } from '@/stores/adminStore' + +export function useAdminSession() { + const adminStore = useAdminStore() + + const verifySession = async () => { + if (!adminStore.hasToken) return false + + try { + const response = await AuthService.verifyToken() + // The current stored bearer token is what was just verified by the server. + // Do not redirect a valid session merely because an adapter omits a token + // field in the verification payload; only replace it when one is supplied. + if (response.code === 200) { + if (response.detail?.token) { + adminStore.login(response.detail) + } + return true + } + } catch { + adminStore.logout() + } + + return false + } + + const logout = async () => { + try { + await AuthService.logout() + } finally { + adminStore.logout() + } + } + + return { + verifySession, + logout + } +} diff --git a/src/composables/useAdminTrash 2.ts b/src/composables/useAdminTrash 2.ts new file mode 100644 index 0000000..b4bd797 --- /dev/null +++ b/src/composables/useAdminTrash 2.ts @@ -0,0 +1,16 @@ +import { TrashService } from '@/services' +import type { TrashListParams, TrashListResponse } from '@/types' + +export function useAdminTrash() { + const fetchTrash = async (params: TrashListParams): Promise => { + const response = await TrashService.list(params) + return response.detail || null + } + + const restoreTrashItem = async (id: number) => TrashService.restore(id) + const purgeTrashItem = async (id: number) => TrashService.purge(id) + const updateTrashRetention = async (id: number, retentionDays: number) => + TrashService.updateRetention(id, retentionDays) + + return { fetchTrash, restoreTrashItem, purgeTrashItem, updateTrashRetention } +} diff --git a/src/composables/useAppShell 2.ts b/src/composables/useAppShell 2.ts new file mode 100644 index 0000000..434a2af --- /dev/null +++ b/src/composables/useAppShell 2.ts @@ -0,0 +1,62 @@ +import { computed, onMounted, onUnmounted, provide } from 'vue' +import { useRoute, useRouter } from 'vue-router' +import { AUTH_EVENTS } from '@/services' +import { ROUTES } from '@/constants' +import { useTheme } from './useTheme' +import { usePublicConfigBootstrap } from './usePublicConfigBootstrap' +import { useRouteLoading } from './useRouteLoading' + +export function useAppShell() { + const route = useRoute() + const router = useRouter() + const { isDarkMode, toggleTheme, initTheme } = useTheme() + const { isLoading, setupRouteLoading } = useRouteLoading(router) + const { syncPublicConfig } = usePublicConfigBootstrap() + const showGlobalControls = computed(() => route.meta.showGlobalControls !== false) + const routeTransitionName = computed(() => String(route.meta.routeTransition || 'fade')) + const routeTransitionMode = computed(() => (route.meta.routeTransition ? undefined : 'out-in')) + const routeViewKey = computed(() => + route.path === ROUTES.ADMIN || route.path.startsWith(`${ROUTES.ADMIN}/`) + ? ROUTES.ADMIN + : route.fullPath + ) + + let cleanupThemeListener: (() => void) | null = null + + const handleUnauthorized = () => { + if (router.currentRoute.value.path !== ROUTES.LOGIN) { + void router.push({ + path: ROUTES.LOGIN, + query: { + redirect: router.currentRoute.value.fullPath + } + }) + } + } + + onMounted(() => { + cleanupThemeListener = initTheme() + setupRouteLoading() + window.addEventListener(AUTH_EVENTS.UNAUTHORIZED, handleUnauthorized) + void syncPublicConfig() + }) + + onUnmounted(() => { + cleanupThemeListener?.() + window.removeEventListener(AUTH_EVENTS.UNAUTHORIZED, handleUnauthorized) + }) + + provide('isDarkMode', isDarkMode) + provide('toggleTheme', toggleTheme) + provide('isLoading', isLoading) + + return { + isDarkMode, + isLoading, + route, + routeTransitionMode, + routeTransitionName, + routeViewKey, + showGlobalControls + } +} diff --git a/src/composables/useClipboard 2.ts b/src/composables/useClipboard 2.ts new file mode 100644 index 0000000..27cae4f --- /dev/null +++ b/src/composables/useClipboard 2.ts @@ -0,0 +1,6 @@ +import { copyToClipboard as copy } from '@/utils/clipboard' + +export function useClipboard() { + const copyToClipboard = (value: string) => copy(value) + return { copyToClipboard } +} diff --git a/src/composables/useDashboardStats 2.ts b/src/composables/useDashboardStats 2.ts new file mode 100644 index 0000000..7c31123 --- /dev/null +++ b/src/composables/useDashboardStats 2.ts @@ -0,0 +1,188 @@ +import { computed, ref, reactive } from 'vue' +import { useI18n } from 'vue-i18n' +import { StatsService } from '@/services' +import type { DashboardData, DashboardHealthSummary, DashboardViewData } from '@/types' +import { formatFileSize, getErrorMessage } from '@/utils/common' + +type UseDashboardStatsOptions = { + loadFailedMessage?: string +} + +const emptyDashboardData = (): DashboardViewData => ({ + hasExtendedStats: false, + totalFiles: 0, + storageUsed: 0, + yesterdayCount: 0, + todayCount: 0, + yesterdaySize: 0, + todaySize: 0, + sysUptime: null, + activeCount: 0, + expiredCount: 0, + textCount: 0, + fileCount: 0, + chunkedCount: 0, + usedCount: 0, + storageBackend: '-', + uploadSizeLimit: 0, + openUpload: 0, + enableChunk: 0, + maxSaveSeconds: 0, + healthAttentionCount: 0, + healthDangerCount: 0, + healthWarningCount: 0, + expiringSoonCount: 0, + storageIssueCount: 0, + neverRetrievedCount: 0, + healthyCount: 0, + permanentCount: 0, + storageUsedText: '0 Bytes', + yesterdaySizeText: '0 Bytes', + todaySizeText: '0 Bytes', + uploadSizeLimitText: '0 Bytes', + sysUptimeText: '-', + activeRatio: 0, + textRatio: 0, + fileRatio: 0, + healthyRatio: 0, + healthAttentionRatio: 0, + todaySizeRatio: 0 +}) + +const toNumber = (value: number | string | null | undefined) => Number(value || 0) + +const clampRatio = (value: number) => Math.max(0, Math.min(100, Math.round(value))) + +const hasOwn = (target: object, key: string) => Object.prototype.hasOwnProperty.call(target, key) + +const formatDuration = (startTimestamp: number | null, dayLabel: string, hourLabel: string) => { + if (!startTimestamp) return '-' + const uptime = Date.now() - startTimestamp + const days = Math.floor(uptime / (24 * 60 * 60 * 1000)) + const hours = Math.floor((uptime % (24 * 60 * 60 * 1000)) / (60 * 60 * 1000)) + return `${days}${dayLabel} ${hours}${hourLabel}` +} + +const healthSummaryKeys: (keyof DashboardHealthSummary)[] = [ + 'healthAttentionCount', + 'healthDangerCount', + 'healthWarningCount', + 'expiringSoonCount', + 'storageIssueCount', + 'neverRetrievedCount', + 'healthyCount', + 'permanentCount' +] + +const normalizeHealthSummary = (detail: DashboardData): DashboardHealthSummary => ({ + healthAttentionCount: toNumber( + detail.healthSummary?.healthAttentionCount ?? detail.healthAttentionCount + ), + healthDangerCount: toNumber(detail.healthSummary?.healthDangerCount ?? detail.healthDangerCount), + healthWarningCount: toNumber( + detail.healthSummary?.healthWarningCount ?? detail.healthWarningCount + ), + expiringSoonCount: toNumber(detail.healthSummary?.expiringSoonCount ?? detail.expiringSoonCount), + storageIssueCount: toNumber(detail.healthSummary?.storageIssueCount ?? detail.storageIssueCount), + neverRetrievedCount: toNumber( + detail.healthSummary?.neverRetrievedCount ?? detail.neverRetrievedCount + ), + healthyCount: toNumber(detail.healthSummary?.healthyCount ?? detail.healthyCount), + permanentCount: toNumber(detail.healthSummary?.permanentCount ?? detail.permanentCount) +}) + +export function useDashboardStats(options: UseDashboardStatsOptions = {}) { + const { t, locale } = useI18n() + const dashboardData = reactive(emptyDashboardData()) + const isLoading = ref(false) + const errorMessage = ref('') + const lastUpdatedAt = ref(null) + const lastUpdatedText = computed(() => + lastUpdatedAt.value + ? new Intl.DateTimeFormat(locale.value, { dateStyle: 'medium', timeStyle: 'short' }).format(lastUpdatedAt.value) + : '-' + ) + + const fetchDashboardData = async () => { + isLoading.value = true + errorMessage.value = '' + + try { + const response = await StatsService.getDashboard() + if (!response.detail) { + throw new Error('No dashboard data') + } + + const detail = response.detail + dashboardData.totalFiles = toNumber(detail.totalFiles) + dashboardData.storageUsed = toNumber(detail.storageUsed) + dashboardData.yesterdayCount = toNumber(detail.yesterdayCount) + dashboardData.todayCount = toNumber(detail.todayCount) + dashboardData.yesterdaySize = toNumber(detail.yesterdaySize) + dashboardData.todaySize = toNumber(detail.todaySize) + dashboardData.sysUptime = detail.sysUptime + dashboardData.hasExtendedStats = hasOwn(detail, 'activeCount') + dashboardData.activeCount = dashboardData.hasExtendedStats + ? toNumber(detail.activeCount) + : dashboardData.totalFiles + dashboardData.expiredCount = toNumber(detail.expiredCount) + dashboardData.textCount = toNumber(detail.textCount) + dashboardData.fileCount = toNumber(detail.fileCount) + dashboardData.chunkedCount = toNumber(detail.chunkedCount) + dashboardData.usedCount = toNumber(detail.usedCount) + dashboardData.storageBackend = detail.storageBackend || '-' + dashboardData.uploadSizeLimit = toNumber(detail.uploadSizeLimit) + dashboardData.openUpload = toNumber(detail.openUpload) + dashboardData.enableChunk = toNumber(detail.enableChunk) + dashboardData.maxSaveSeconds = toNumber(detail.maxSaveSeconds) + const healthSummary = normalizeHealthSummary(detail) + healthSummaryKeys.forEach((key) => { + dashboardData[key] = healthSummary[key] + }) + + dashboardData.storageUsedText = formatFileSize(dashboardData.storageUsed) + dashboardData.yesterdaySizeText = formatFileSize(dashboardData.yesterdaySize) + dashboardData.todaySizeText = formatFileSize(dashboardData.todaySize) + dashboardData.uploadSizeLimitText = formatFileSize(dashboardData.uploadSizeLimit) + dashboardData.sysUptimeText = formatDuration( + dashboardData.sysUptime, + t('common.dayShort'), + t('common.hourShort') + ) + dashboardData.activeRatio = dashboardData.totalFiles + ? clampRatio((dashboardData.activeCount / dashboardData.totalFiles) * 100) + : 0 + dashboardData.textRatio = dashboardData.totalFiles + ? clampRatio((dashboardData.textCount / dashboardData.totalFiles) * 100) + : 0 + dashboardData.fileRatio = dashboardData.totalFiles + ? clampRatio((dashboardData.fileCount / dashboardData.totalFiles) * 100) + : 0 + dashboardData.healthyRatio = dashboardData.totalFiles + ? clampRatio((dashboardData.healthyCount / dashboardData.totalFiles) * 100) + : 0 + dashboardData.healthAttentionRatio = dashboardData.totalFiles + ? clampRatio((dashboardData.healthAttentionCount / dashboardData.totalFiles) * 100) + : 0 + dashboardData.todaySizeRatio = dashboardData.uploadSizeLimit + ? clampRatio((dashboardData.todaySize / dashboardData.uploadSizeLimit) * 100) + : 0 + lastUpdatedAt.value = new Date() + } catch (error) { + errorMessage.value = getErrorMessage( + error, + options.loadFailedMessage || 'Failed to load dashboard data' + ) + } finally { + isLoading.value = false + } + } + + return { + dashboardData, + errorMessage, + fetchDashboardData, + isLoading, + lastUpdatedText + } +} diff --git a/src/composables/useInjectedDarkMode 2.ts b/src/composables/useInjectedDarkMode 2.ts new file mode 100644 index 0000000..c6497b8 --- /dev/null +++ b/src/composables/useInjectedDarkMode 2.ts @@ -0,0 +1,7 @@ +import { computed, inject, unref } from 'vue' +import type { Ref } from 'vue' + +export function useInjectedDarkMode() { + const injectedDarkMode = inject | boolean>('isDarkMode', false) + return computed(() => Boolean(unref(injectedDarkMode))) +} diff --git a/src/composables/usePresignedUpload 2.ts b/src/composables/usePresignedUpload 2.ts new file mode 100644 index 0000000..10b6c90 --- /dev/null +++ b/src/composables/usePresignedUpload 2.ts @@ -0,0 +1,355 @@ +import { ref, computed, readonly } from 'vue' +import { PresignUploadService } from '@/services' +import type { + PresignUploadStatus, + PresignUploadMode, + PresignInitResponse, + PresignUploadOptions, + PresignStatusResponse, + UploadProgress, + ExpireStyle, + AlertType +} from '@/types' +import { getErrorMessage } from '@/utils/common' + +// 预签名上传状态常量 +export const PRESIGN_UPLOAD_STATUS = { + IDLE: 'idle', + INITIALIZING: 'initializing', + UPLOADING: 'uploading', + CONFIRMING: 'confirming', + SUCCESS: 'success', + ERROR: 'error' +} as const + +// 默认过期配置 +const DEFAULT_EXPIRE_VALUE = 1 +const DEFAULT_EXPIRE_STYLE: ExpireStyle = 'day' + +type ErrorWithResponse = { + response?: { + status?: number + } +} + +type PresignedUploadNotifier = (message: string, type: AlertType) => void + +type UsePresignedUploadOptions = { + getMaxFileSize?: () => number + notify?: PresignedUploadNotifier + onStatus?: (status: PresignUploadStatus) => void +} + +/** + * 预签名上传 Composable + * 支持 S3 直传模式和服务器代理模式 + */ +export function usePresignedUpload(options: UsePresignedUploadOptions = {}) { + // 状态管理 + const presignStatus = ref(PRESIGN_UPLOAD_STATUS.IDLE) + const uploadSession = ref(null) + const uploadProgress = ref({ + loaded: 0, + total: 0, + percentage: 0 + }) + const uploadedCode = ref('') + const errorMessage = ref('') + + // 计算属性 + const isInitializing = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.INITIALIZING) + const isUploading = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.UPLOADING) + const isConfirming = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.CONFIRMING) + const isSuccess = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.SUCCESS) + const isError = computed(() => presignStatus.value === PRESIGN_UPLOAD_STATUS.ERROR) + const currentMode = computed(() => uploadSession.value?.mode ?? null) + + const notify: PresignedUploadNotifier = (message, type) => { + options.notify?.(message, type) + } + const onStatus = options.onStatus + + /** + * 文件大小验证 + */ + const validateFileSize = (file: File): boolean => { + const maxFileSize = options.getMaxFileSize?.() + if (!maxFileSize) { + return true + } + + if (file.size > maxFileSize) { + const maxSizeMB = Math.round(maxFileSize / 1024 / 1024) + errorMessage.value = `文件大小不能超过 ${maxSizeMB}MB` + notify(errorMessage.value, 'error') + return false + } + return true + } + + /** + * 进度追踪回调 + */ + const createProgressHandler = ( + externalHandler?: (progress: UploadProgress) => void + ): ((progress: UploadProgress) => void) => { + return (progress: UploadProgress) => { + // 确保进度值在有效范围内 + uploadProgress.value = { + loaded: Math.max(0, progress.loaded), + total: Math.max(0, progress.total), + percentage: Math.min(100, Math.max(0, progress.percentage)) + } + // 调用外部进度回调 + if (externalHandler) { + externalHandler(uploadProgress.value) + } + } + } + + /** + * 错误处理 + */ + const handleUploadError = (error: unknown): void => { + presignStatus.value = PRESIGN_UPLOAD_STATUS.ERROR + onStatus?.(PRESIGN_UPLOAD_STATUS.ERROR) + const status = (error as ErrorWithResponse)?.response?.status + const fallback = + status === 404 + ? '上传会话不存在或已过期' + : status === 500 + ? '服务器错误,请稍后重试' + : '上传失败,请重试' + + errorMessage.value = getErrorMessage(error, fallback) + notify(errorMessage.value, 'error') + } + + /** + * 初始化上传会话 + */ + const initUploadSession = async ( + file: File, + options?: PresignUploadOptions + ): Promise => { + try { + presignStatus.value = PRESIGN_UPLOAD_STATUS.INITIALIZING + onStatus?.(PRESIGN_UPLOAD_STATUS.INITIALIZING) + + const response = await PresignUploadService.initUpload({ + file_name: file.name, + file_size: file.size, + expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE, + expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE + }) + + if (response.code === 200 && response.detail) { + uploadSession.value = response.detail + return response.detail + } else { + throw new Error(response.message || '初始化上传失败') + } + } catch (error) { + handleUploadError(error) + return null + } + } + + /** + * 直传模式上传到 S3 + */ + const uploadDirect = async ( + file: File, + session: PresignInitResponse, + options?: PresignUploadOptions + ): Promise => { + try { + presignStatus.value = PRESIGN_UPLOAD_STATUS.UPLOADING + onStatus?.(PRESIGN_UPLOAD_STATUS.UPLOADING) + + // 上传到 S3 + const progressHandler = createProgressHandler(options?.onProgress) + const uploadSuccess = await PresignUploadService.directUploadToS3( + session.upload_url, + file, + progressHandler + ) + + if (!uploadSuccess) { + throw new Error('S3 上传失败') + } + + // 确认上传 + presignStatus.value = PRESIGN_UPLOAD_STATUS.CONFIRMING + onStatus?.(PRESIGN_UPLOAD_STATUS.CONFIRMING) + const confirmResponse = await PresignUploadService.confirmUpload(session.upload_id, { + expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE, + expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE + }) + + if (confirmResponse.code === 200 && confirmResponse.detail?.code) { + presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS + onStatus?.(PRESIGN_UPLOAD_STATUS.SUCCESS) + uploadedCode.value = String(confirmResponse.detail.code) + // 确保进度为 100% + uploadProgress.value = { + loaded: file.size, + total: file.size, + percentage: 100 + } + notify('文件上传成功!', 'success') + return uploadedCode.value + } else { + throw new Error(confirmResponse.message || '确认上传失败') + } + } catch (error) { + handleUploadError(error) + return null + } + } + + /** + * 代理模式上传 + */ + const uploadProxy = async ( + file: File, + session: PresignInitResponse, + options?: PresignUploadOptions + ): Promise => { + try { + presignStatus.value = PRESIGN_UPLOAD_STATUS.UPLOADING + onStatus?.(PRESIGN_UPLOAD_STATUS.UPLOADING) + + const progressHandler = createProgressHandler(options?.onProgress) + const uploadUrl = + session.proxy_upload_url || session.upload_url || session.legacy_proxy_upload_url + const response = await PresignUploadService.proxyUpload( + session.upload_id, + file, + progressHandler, + uploadUrl + ) + + if (response.code === 200 && response.detail?.code) { + presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS + onStatus?.(PRESIGN_UPLOAD_STATUS.SUCCESS) + uploadedCode.value = String(response.detail.code) + // 确保进度为 100% + uploadProgress.value = { + loaded: file.size, + total: file.size, + percentage: 100 + } + notify('文件上传成功!', 'success') + return uploadedCode.value + } else { + throw new Error(response.message || '代理上传失败') + } + } catch (error) { + handleUploadError(error) + return null + } + } + + const uploadFile = async (file: File, options?: PresignUploadOptions): Promise => { + reset() + + if (!validateFileSize(file)) { + presignStatus.value = PRESIGN_UPLOAD_STATUS.ERROR + return null + } + + const session = await initUploadSession(file, options) + if (!session) { + return null + } + + if (session.mode === 'direct') { + return await uploadDirect(file, session, options) + } else { + return await uploadProxy(file, session, options) + } + } + + /** + * 取消上传 + */ + const cancelUpload = async (): Promise => { + if (!uploadSession.value?.upload_id) { + return + } + + try { + await PresignUploadService.cancelUpload(uploadSession.value.upload_id) + notify('上传已取消', 'info') + } catch (error) { + // 取消失败时静默处理,因为会话可能已过期 + console.warn('取消上传失败:', error) + } finally { + reset() + } + } + + /** + * 获取上传状态 + */ + const getStatus = async (): Promise => { + if (!uploadSession.value?.upload_id) { + return null + } + + try { + const response = await PresignUploadService.getUploadStatus(uploadSession.value.upload_id) + if (response.code === 200 && response.detail) { + // 检查会话是否过期 + if (response.detail.is_expired) { + errorMessage.value = '上传会话已过期' + notify(errorMessage.value, 'warning') + } + return response.detail + } + return null + } catch (error) { + handleUploadError(error) + return null + } + } + + /** + * 重置状态 + */ + const reset = (): void => { + presignStatus.value = PRESIGN_UPLOAD_STATUS.IDLE + uploadSession.value = null + uploadProgress.value = { + loaded: 0, + total: 0, + percentage: 0 + } + uploadedCode.value = '' + errorMessage.value = '' + } + + return { + // 状态 (只读) + presignStatus: readonly(presignStatus), + uploadSession: readonly(uploadSession), + uploadProgress: readonly(uploadProgress), + uploadedCode: readonly(uploadedCode), + errorMessage: readonly(errorMessage), + + // 计算属性 + isInitializing, + isUploading, + isConfirming, + isSuccess, + isError, + currentMode, + + // 方法 + uploadFile, + cancelUpload, + getStatus, + reset + } +} diff --git a/src/composables/usePublicConfigBootstrap 2.ts b/src/composables/usePublicConfigBootstrap 2.ts new file mode 100644 index 0000000..d32c536 --- /dev/null +++ b/src/composables/usePublicConfigBootstrap 2.ts @@ -0,0 +1,26 @@ +import { ConfigService } from '@/services' +import { useAlertStore } from '@/stores/alertStore' +import { useConfigStore } from '@/stores/configStore' + +export function usePublicConfigBootstrap() { + const alertStore = useAlertStore() + const configStore = useConfigStore() + + const syncPublicConfig = async () => { + const res = await ConfigService.getUserConfig() + + if (res.code !== 200 || !res.detail) { + return + } + + configStore.applyPublicMeta(res.detail.meta) + const notifyMessage = configStore.applyRemoteConfig(res.detail.config) + if (notifyMessage) { + alertStore.showAlert(notifyMessage, 'success') + } + } + + return { + syncPublicConfig + } +} diff --git a/src/composables/useRetrieveFlow 2.ts b/src/composables/useRetrieveFlow 2.ts new file mode 100644 index 0000000..6407bf0 --- /dev/null +++ b/src/composables/useRetrieveFlow 2.ts @@ -0,0 +1,249 @@ +import { computed, ref, watch } from 'vue' +import { useI18n } from 'vue-i18n' +import { storeToRefs } from 'pinia' +import { FileService } from '@/services' +import { useAlertStore } from '@/stores/alertStore' +import { useFileDataStore } from '@/stores/fileData' +import type { ReceivedFileRecord, ShareMetadataResponse, ShareSelectResponse } from '@/types' +import { copyToClipboard } from '@/utils/clipboard' +import { getErrorMessage } from '@/utils/common' +import { renderMarkdownPreview } from '@/utils/content-preview' +import { downloadReceivedRecord } from '@/utils/download-action' +import { isValidRetrievalCode } from '@/utils/retrieval-code' + +type InputStatus = { + readonly: boolean + loading: boolean +} + +export function useRetrieveFlow() { + const { t } = useI18n() + const alertStore = useAlertStore() + const fileStore = useFileDataStore() + const { receiveData: records } = storeToRefs(fileStore) + + const code = ref('') + const inspectedFile = ref(null) + const isInspecting = ref(false) + const isRetrieving = ref(false) + const inputStatus = ref({ + readonly: false, + loading: false + }) + const error = ref('') + const selectedRecord = ref(null) + const showDrawer = ref(false) + const showPreview = ref(false) + const renderedContent = ref('') + const normalizedCode = computed(() => code.value.trim()) + const isWorking = computed(() => isInspecting.value || isRetrieving.value) + const hasValidCode = computed(() => isValidRetrievalCode(normalizedCode.value)) + + const formatFileSize = (bytes: number) => { + if (bytes === 0) return '0 ' + t('fileSize.bytes') + const k = 1024 + const sizes = [ + t('fileSize.bytes'), + t('fileSize.kb'), + t('fileSize.mb'), + t('fileSize.gb'), + t('fileSize.tb') + ] + const i = Math.floor(Math.log(bytes) / Math.log(k)) + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i] + } + + const createRecord = (detail: ShareSelectResponse): ReceivedFileRecord => { + const isText = + typeof detail.is_text === 'boolean' + ? detail.is_text + : detail.type + ? detail.type === 'text' + : detail.name === 'Text' && !detail.text.startsWith('/share/download') + const content = isText ? (detail.content ?? detail.text) : null + const downloadUrl = isText ? null : (detail.download_url ?? detail.text) + + return { + id: Date.now(), + code: detail.code, + filename: detail.name, + size: formatFileSize(detail.size), + downloadUrl, + content, + date: new Date().toLocaleString(), + type: isText ? 'text' : 'file', + remainingDownloads: detail.remaining_downloads + } + } + + const resetInspection = () => { + inspectedFile.value = null + error.value = '' + } + + const inspectCode = async () => { + if (!hasValidCode.value) { + alertStore.showAlert(t('retrieve.messages.invalidCode'), 'error') + return + } + + isInspecting.value = true + inputStatus.value.readonly = true + inputStatus.value.loading = true + error.value = '' + + try { + const res = await FileService.inspectFile(normalizedCode.value) + if (res.code === 200 && res.detail) { + inspectedFile.value = res.detail + } else { + inspectedFile.value = null + error.value = String(res.detail || res.message || '') + alertStore.showAlert(t('retrieve.messages.retrieveFailure') + error.value, 'error') + } + } catch { + inspectedFile.value = null + error.value = t('retrieve.messages.previewUnavailable') + alertStore.showAlert(error.value, 'warning') + } finally { + isInspecting.value = false + inputStatus.value.readonly = false + inputStatus.value.loading = false + } + } + + const handleSubmit = async () => { + if (!hasValidCode.value) { + alertStore.showAlert(t('retrieve.messages.invalidCode'), 'error') + return + } + + isRetrieving.value = true + inputStatus.value.readonly = true + inputStatus.value.loading = true + error.value = '' + + try { + const res = await FileService.selectFile(normalizedCode.value) + if (res.code === 200 && res.detail) { + const newFileData = createRecord(res.detail) + const existingIndex = fileStore.receiveData.findIndex( + (file) => file.code === newFileData.code + ) + if (existingIndex !== -1) { + fileStore.deleteReceiveData(existingIndex) + } + fileStore.addReceiveData(newFileData) + selectedRecord.value = newFileData + if (newFileData.content) { + showPreview.value = true + } + inspectedFile.value = null + alertStore.showAlert(t('retrieve.messages.retrieveSuccess'), 'success') + } else { + error.value = String(res.detail || '') + alertStore.showAlert(t('retrieve.messages.retrieveFailure') + error.value, 'error') + } + } catch (err: unknown) { + const errorMessage = getErrorMessage(err, t('retrieve.messages.unknownError')) + error.value = errorMessage + alertStore.showAlert(t('retrieve.messages.networkError') + errorMessage, 'error') + } finally { + isRetrieving.value = false + inputStatus.value.readonly = false + inputStatus.value.loading = false + code.value = '' + } + } + + const copyContent = async () => { + if (selectedRecord.value?.content) { + await copyToClipboard(selectedRecord.value.content, { + successMsg: t('fileRecord.contentCopied'), + errorMsg: t('fileRecord.copyFailed'), + notify: (message, type) => alertStore.showAlert(message, type) + }) + } + } + + const viewDetails = (record: ReceivedFileRecord) => { + selectedRecord.value = record + } + + const closeDetails = () => { + selectedRecord.value = null + } + + const deleteRecord = (id: number) => { + if (!window.confirm(t('fileRecord.deleteRecordConfirm'))) return + const index = records.value.findIndex((record) => record.id === id) + if (index !== -1) { + fileStore.deleteReceiveData(index) + } + } + + const toggleDrawer = () => { + showDrawer.value = !showDrawer.value + } + + const downloadRecord = (record: ReceivedFileRecord) => { + downloadReceivedRecord(record) + } + + const showContentPreview = () => { + showPreview.value = true + } + + const closeContentPreview = () => { + showPreview.value = false + } + + watch( + () => selectedRecord.value?.content, + async (content) => { + if (content) { + renderedContent.value = await renderMarkdownPreview(content) + } else { + renderedContent.value = '' + } + }, + { immediate: true } + ) + + watch(normalizedCode, (nextCode) => { + if (inspectedFile.value && inspectedFile.value.code !== nextCode) { + resetInspection() + } + + if (!isValidRetrievalCode(nextCode) && error.value) { + error.value = '' + } + }) + + return { + code, + inspectedFile, + isInspecting, + isRetrieving, + isWorking, + hasValidCode, + inputStatus, + error, + records, + selectedRecord, + showDrawer, + showPreview, + renderedContent, + closeContentPreview, + closeDetails, + copyContent, + deleteRecord, + downloadRecord, + handleSubmit, + inspectCode, + resetInspection, + showContentPreview, + toggleDrawer, + viewDetails + } +} diff --git a/src/composables/useRouteLoading 2.ts b/src/composables/useRouteLoading 2.ts new file mode 100644 index 0000000..6c3592f --- /dev/null +++ b/src/composables/useRouteLoading 2.ts @@ -0,0 +1,44 @@ +import { onUnmounted, ref } from 'vue' +import type { Router } from 'vue-router' + +const ROUTE_LOADING_DELAY = 200 + +export function useRouteLoading(router: Router) { + const isLoading = ref(false) + let loadingTimer: number | null = null + let cleanupBeforeGuard: (() => void) | null = null + let cleanupAfterHook: (() => void) | null = null + + const clearLoadingTimer = () => { + if (loadingTimer !== null) { + window.clearTimeout(loadingTimer) + loadingTimer = null + } + } + + const setupRouteLoading = () => { + cleanupBeforeGuard = router.beforeEach((to) => { + clearLoadingTimer() + isLoading.value = to.meta.showRouteLoading !== false + }) + + cleanupAfterHook = router.afterEach(() => { + clearLoadingTimer() + loadingTimer = window.setTimeout(() => { + isLoading.value = false + loadingTimer = null + }, ROUTE_LOADING_DELAY) + }) + } + + onUnmounted(() => { + clearLoadingTimer() + cleanupBeforeGuard?.() + cleanupAfterHook?.() + }) + + return { + isLoading, + setupRouteLoading + } +} diff --git a/src/composables/useSendFlow 2.ts b/src/composables/useSendFlow 2.ts new file mode 100644 index 0000000..32a1d4f --- /dev/null +++ b/src/composables/useSendFlow 2.ts @@ -0,0 +1,361 @@ +import { computed, ref, watch } from 'vue' +import { useI18n } from 'vue-i18n' +import { useAlertStore } from '@/stores/alertStore' +import { useAdminStore } from '@/stores/adminStore' +import { useConfigStore } from '@/stores/configStore' +import { useFileDataStore } from '@/stores/fileData' +import type { SendType, SentFileRecord } from '@/types' +import { getClipboardFile, insertTextAtSelection } from '@/utils/clipboard-paste' +import { getErrorMessage } from '@/utils/common' +import { getStorageUnit } from '@/utils/convert' +import { calculateFileHash } from '@/utils/file-processing' +import { buildSentRecord, isExpirationWithinLimit } from '@/utils/send-record' +import { createSentRecordActions } from '@/utils/sent-record-actions' +import { useSendSubmit } from './useSendSubmit' + +export function useSendFlow() { + const { t } = useI18n() + const alertStore = useAlertStore() + const adminStore = useAdminStore() + const configStore = useConfigStore() + const fileDataStore = useFileDataStore() + const config = computed(() => configStore.config) + const sendType = ref('file') + const selectedFile = ref(null) + const selectedFiles = ref([]) + const textContent = ref('') + const expirationMethod = ref(config.value.expireStyle[0] || 'day') + const expirationValue = ref('1') + const uploadProgress = ref(0) + const showDrawer = ref(false) + const selectedRecord = ref(null) + const isSubmitting = ref(false) + const fileHash = ref('') + const uploadStatus = ref<'idle' | 'initializing' | 'uploading' | 'confirming' | 'success' | 'error'>('idle') + const uploadedBytes = ref(0) + const totalBytes = ref(0) + const uploadError = ref('') + const sendRecords = computed(() => fileDataStore.shareData) + const uploadDescription = computed(() => + t('send.uploadArea.descriptionWithLimit', { + size: getStorageUnit(config.value.uploadSize) + }) + ) + const expirationOptions = computed(() => + config.value.expireStyle.map((value) => ({ + value, + label: getUnit(value) + })) + ) + watch( + () => config.value.expireStyle, + (expireStyle) => { + if (expireStyle.length > 0 && !expireStyle.includes(expirationMethod.value)) { + expirationMethod.value = expireStyle[0] + } + }, + { immediate: true } + ) + const notifyCopyResult = (message: string, type: 'success' | 'error') => { + alertStore.showAlert(message, type) + } + const sentRecordActions = createSentRecordActions(notifyCopyResult) + const { resetPresignUpload, submitFile, submitText } = useSendSubmit({ + getMaxFileSize: () => configStore.uploadSizeLimit, + notify: (message, type) => alertStore.showAlert(message, type), + translate: t, + onProgress: (progress) => { + uploadProgress.value = progress.percentage + totalBytes.value = progress.total + uploadedBytes.value = progress.loaded + }, + onStatus: (status) => { uploadStatus.value = status }, + onHashCalculated: (hash) => { + fileHash.value = hash + } + }) + + const checkOpenUpload = () => { + if (config.value.openUpload === 0 && !adminStore.hasToken) { + alertStore.showAlert(t('send.messages.guestUploadDisabled'), 'error') + return false + } + return true + } + + const checkFileSize = (file: File) => { + if (file.size > config.value.uploadSize) { + alertStore.showAlert( + t('send.messages.fileSizeExceeded', { size: getStorageUnit(config.value.uploadSize) }), + 'error' + ) + selectedFile.value = null + return false + } + return true + } + + const checkExpirationTime = (method: string, value: string): boolean => + isExpirationWithinLimit(method, value, config.value.max_save_seconds || 0) + + const checkUpload = () => { + if (!selectedFile.value) return false + if (!checkOpenUpload()) return false + if (!checkFileSize(selectedFile.value)) return false + if (!checkExpirationTime(expirationMethod.value, expirationValue.value)) return false + return true + } + + const handleFileSelected = async (file: File) => { + selectedFile.value = file + selectedFiles.value = [] + if (!checkOpenUpload()) return + if (!checkFileSize(file)) return + fileHash.value = await calculateFileHash(file) + } + + const handleFilesSelected = async (files: File[]) => { + if (!checkOpenUpload()) return + selectedFiles.value = files + selectedFile.value = null + fileHash.value = '' + } + + const handleFileDrop = async (event: DragEvent) => { + if (!event.dataTransfer?.files || event.dataTransfer.files.length === 0) return + const files = Array.from(event.dataTransfer.files) + if (files.length === 1) { + const file = files[0] + selectedFile.value = file + selectedFiles.value = [] + if (!checkUpload()) return + fileHash.value = await calculateFileHash(file) + } else { + if (!checkOpenUpload()) return + selectedFiles.value = files + selectedFile.value = null + fileHash.value = '' + } + } + + const handlePaste = async (event: ClipboardEvent) => { + const items = event.clipboardData?.items + if (!items) return + + const file = getClipboardFile(items) + if (file) { + if (file.size === 0) { + alertStore.showAlert(t('send.messages.emptyFileError'), 'error') + return + } + + selectedFile.value = file + if (!checkUpload()) return + + try { + fileHash.value = await calculateFileHash(file) + alertStore.showAlert( + t('send.messages.fileAddedFromClipboard', { filename: file.name }), + 'success' + ) + } catch (err) { + alertStore.showAlert(t('send.messages.fileProcessingFailed'), 'error') + console.error('File hash calculation failed:', err) + } + return + } + + const textItem = items[0] + if (!textItem) return + + sendType.value = 'text' + textItem.getAsString((str: string) => { + const trimmedStr = str.trim() + if (!trimmedStr) return + + const textareaElement = document.getElementById('text-content') as HTMLTextAreaElement + if (!textareaElement) { + textContent.value += trimmedStr + return + } + + const insertion = insertTextAtSelection({ + text: textContent.value, + insertText: trimmedStr, + selectionStart: textareaElement.selectionStart, + selectionEnd: textareaElement.selectionEnd + }) + textContent.value = insertion.value + + setTimeout(() => { + textareaElement.setSelectionRange(insertion.cursor, insertion.cursor) + textareaElement.focus() + }, 0) + }) + } + + const getUnit = (value: string = expirationMethod.value) => { + switch (value) { + case 'day': + return t('send.expiration.units.days') + case 'hour': + return t('send.expiration.units.hours') + case 'minute': + return t('send.expiration.units.minutes') + case 'count': + return t('send.expiration.units.times') + case 'forever': + return t('send.expiration.units.forever') + default: + return '' + } + } + + const handleSubmit = async () => { + if (isSubmitting.value) return + isSubmitting.value = true + uploadError.value = '' + + try { + if (sendType.value === 'file' && !selectedFile.value && selectedFiles.value.length === 0) { + alertStore.showAlert(t('send.messages.selectFile'), 'error') + return + } + if (sendType.value === 'text' && !textContent.value.trim()) { + alertStore.showAlert(t('send.messages.enterText'), 'error') + return + } + if (!checkOpenUpload()) { + return + } + if (expirationMethod.value !== 'forever' && !expirationValue.value) { + alertStore.showAlert(t('send.messages.enterExpirationValue'), 'error') + return + } + + if (!checkExpirationTime(expirationMethod.value, expirationValue.value)) { + const maxDays = Math.floor(config.value.max_save_seconds / 86400) + alertStore.showAlert(t('send.messages.expirationTooLong', { days: maxDays }), 'error') + return + } + + const expireValue = expirationValue.value ? parseInt(expirationValue.value) : 1 + let response + if (sendType.value === 'file') { + response = await submitFile({ + selectedFile: selectedFile.value, + selectedFiles: selectedFiles.value, + expireValue, + expireStyle: expirationMethod.value, + enableChunk: Boolean(config.value.enableChunk), + validateFileSize: checkFileSize + }) + } else { + response = await submitText({ + text: textContent.value, + expireValue, + expireStyle: expirationMethod.value + }) + } + + if (!response) return + + if (response?.code === 200) { + const newRecord = buildSentRecord({ + response, + sendType: sendType.value, + textContent: textContent.value, + selectedFile: selectedFile.value, + selectedFiles: selectedFiles.value, + expirationMethod: expirationMethod.value, + expirationValue: expirationValue.value, + translate: t, + getUnit + }) + fileDataStore.addShareDataRecord(newRecord) + alertStore.showAlert( + t('send.messages.sendSuccess', { code: newRecord.retrieveCode }), + 'success' + ) + selectedFile.value = null + selectedFiles.value = [] + textContent.value = '' + uploadProgress.value = 0 + uploadedBytes.value = 0 + totalBytes.value = 0 + uploadStatus.value = 'idle' + resetPresignUpload() + selectedRecord.value = newRecord + await sentRecordActions.copyLink(newRecord) + } else { + throw new Error(t('send.messages.serverError')) + } + } catch (error: unknown) { + uploadStatus.value = 'error' + uploadError.value = getErrorMessage(error, t('send.messages.sendFailed')) + alertStore.showAlert(getErrorMessage(error, t('send.messages.sendFailed')), 'error') + } finally { + uploadProgress.value = 0 + if (uploadStatus.value !== 'success' && uploadStatus.value !== 'error') { + uploadStatus.value = 'idle' + } + if (uploadStatus.value === 'success') uploadStatus.value = 'idle' + isSubmitting.value = false + } + } + + const toggleDrawer = () => { + showDrawer.value = !showDrawer.value + } + + const viewDetails = (record: SentFileRecord) => { + selectedRecord.value = record + } + + const closeDetails = () => { + selectedRecord.value = null + } + + const deleteRecord = (id: number) => { + if (!window.confirm(t('fileRecord.deleteRecordConfirm'))) return + const index = fileDataStore.shareData.findIndex((record) => record.id === id) + if (index !== -1) { + fileDataStore.deleteShareData(index) + } + } + + return { + config, + sendType, + selectedFile, + selectedFiles, + textContent, + expirationMethod, + expirationValue, + uploadProgress, + showDrawer, + selectedRecord, + isSubmitting, + uploadStatus, + uploadedBytes, + totalBytes, + uploadError, + sendRecords, + uploadDescription, + expirationOptions, + closeDetails, + deleteRecord, + copySentRecordCode: sentRecordActions.copyCode, + copySentRecordLink: sentRecordActions.copyLink, + copySentRecordWgetCommand: sentRecordActions.copyWgetCommand, + getQRCodeValue: sentRecordActions.getQRCodeValue, + getUnit, + handleFileDrop, + handleFileSelected, + handleFilesSelected, + handlePaste, + handleSubmit, + toggleDrawer, + viewDetails + } +} diff --git a/src/composables/useSendSubmit 2.ts b/src/composables/useSendSubmit 2.ts new file mode 100644 index 0000000..e370651 --- /dev/null +++ b/src/composables/useSendSubmit 2.ts @@ -0,0 +1,131 @@ +import { FileService, uploadChunkedFile } from '@/services' +import type { AlertType, ApiResponse, ExpireStyle, UploadProgress } from '@/types' +import { calculateFileHash, packFilesAsZip } from '@/utils/file-processing' +import { usePresignedUpload } from './usePresignedUpload' + +type Translate = ( + key: string, + params?: Record +) => string + +type UseSendSubmitOptions = { + getMaxFileSize: () => number + notify: (message: string, type: AlertType) => void + translate: Translate + onProgress: (progress: UploadProgress) => void + onHashCalculated: (hash: string) => void + onStatus?: (status: 'idle' | 'initializing' | 'uploading' | 'confirming' | 'success' | 'error') => void +} + +type SubmitFileOptions = { + selectedFile: File | null + selectedFiles: File[] + expireValue: number + expireStyle: string + enableChunk: boolean + validateFileSize: (file: File) => boolean +} + +type SubmitTextOptions = { + text: string + expireValue: number + expireStyle: string +} + +export function useSendSubmit(options: UseSendSubmitOptions) { + const { uploadFile: presignUploadFile, reset: resetPresignUpload } = usePresignedUpload({ + getMaxFileSize: options.getMaxFileSize, + notify: options.notify, + onStatus: options.onStatus + }) + + const handleChunkUpload = async ( + file: File, + expireValue: number, + expireStyle: string + ): Promise => { + return uploadChunkedFile(file, { + expireValue, + expireStyle, + onHashCalculated: options.onHashCalculated, + onProgress: options.onProgress, + onStatus: options.onStatus, + messages: { + initFailed: options.translate('send.messages.initChunkUploadFailed'), + chunkFailed: (index) => options.translate('send.messages.chunkUploadFailed', { index }), + completeFailed: options.translate('send.messages.completeUploadFailed') + } + }) + } + + const handlePresignedUpload = async ( + file: File, + expireValue: number, + expireStyle: string + ): Promise> => { + const code = await presignUploadFile(file, { + expireValue, + expireStyle: expireStyle as ExpireStyle, + onProgress: (progress) => { + options.onProgress(progress) + } + }) + + if (!code) { + throw new Error(options.translate('send.messages.uploadFailed')) + } + + return { + code: 200, + detail: { + code, + name: file.name + } + } + } + + const submitFile = async ({ + selectedFile, + selectedFiles, + expireValue, + expireStyle, + enableChunk, + validateFileSize + }: SubmitFileOptions): Promise => { + let fileToUpload = selectedFile + + if (selectedFiles.length > 0) { + options.notify('正在打包文件...', 'success') + fileToUpload = await packFilesAsZip(selectedFiles) + if (!validateFileSize(fileToUpload)) { + return null + } + options.onHashCalculated(await calculateFileHash(fileToUpload)) + } + + if (!fileToUpload) { + throw new Error(options.translate('send.messages.selectFile')) + } + + + try { + const response = enableChunk + ? await handleChunkUpload(fileToUpload, expireValue, expireStyle) + : await handlePresignedUpload(fileToUpload, expireValue, expireStyle) + if (response?.code === 200) options.onStatus?.('success') + return response + } catch (error) { + options.onStatus?.('error') + throw error + } + } + + const submitText = ({ text, expireValue, expireStyle }: SubmitTextOptions) => + FileService.uploadText(text, expireValue, expireStyle) + + return { + resetPresignUpload, + submitFile, + submitText + } +} diff --git a/src/composables/useSystemConfig 2.ts b/src/composables/useSystemConfig 2.ts new file mode 100644 index 0000000..1d27030 --- /dev/null +++ b/src/composables/useSystemConfig 2.ts @@ -0,0 +1,216 @@ +import { ref, computed } from 'vue' +import { ConfigService } from '@/services' +import { useAlertStore } from '@/stores/alertStore' +import { useConfigStore } from '@/stores/configStore' +import type { ConfigState } from '@/types' +import { DEFAULT_CONFIG_STATE, readStoredConfig } from '@/utils/config-storage' +import { getErrorMessage } from '@/utils/common' +import { + buildConfigSubmitPayload, + bytesToFileSizeForm, + secondsToSaveTimeForm, + type FileSizeUnit, + type SaveTimeUnit +} from '@/utils/config-form' + +type ConfigFlagKey = 'enableChunk' | 's3_proxy' | 'openUpload' + +export function useSystemConfig() { + const alertStore = useAlertStore() + const configStore = useConfigStore() + + // 状态管理 + const config = ref({ ...DEFAULT_CONFIG_STATE }) + const isRefreshing = ref(false) + const isSaving = ref(false) + const savedPayloadSnapshot = ref('') + const fileSize = ref(1) + const sizeUnit = ref('MB') + const saveTime = ref(1) + const saveTimeUnit = ref('天') + + const isLoading = computed(() => isRefreshing.value || isSaving.value) + + const buildSubmitPayload = (): Partial => { + const payload: Partial = buildConfigSubmitPayload( + config.value, + { value: fileSize.value, unit: sizeUnit.value }, + { value: saveTime.value, unit: saveTimeUnit.value } + ) + + if (!payload.admin_token) { + delete payload.admin_token + } + + return payload + } + + const snapshotPayload = (payload: Partial) => JSON.stringify(payload) + + const normalizeEditableConfig = (nextConfig: Partial): ConfigState => ({ + ...DEFAULT_CONFIG_STATE, + ...nextConfig, + admin_token: '' + }) + + const markConfigSaved = () => { + savedPayloadSnapshot.value = snapshotPayload(buildSubmitPayload()) + } + + const isDirty = computed(() => { + if (!savedPayloadSnapshot.value) { + return false + } + + return snapshotPayload(buildSubmitPayload()) !== savedPayloadSnapshot.value + }) + + // 从本地存储获取配置 + const getStoredConfig = (): ConfigState | null => { + const storedConfig = readStoredConfig>() + return storedConfig ? normalizeEditableConfig(storedConfig) : null + } + + // 保存配置到本地存储 + const saveConfigToStorage = (configData: ConfigState) => { + configStore.updateConfig(configData) + } + + // 获取系统配置 + const fetchConfig = async (): Promise => { + try { + isRefreshing.value = true + + const response = await ConfigService.getConfig() + + if (response.code === 200 && response.detail) { + config.value = normalizeEditableConfig(response.detail) + const notifyMessage = configStore.applyRemoteConfig(config.value) + if (notifyMessage) { + alertStore.showAlert(notifyMessage, 'success') + } + + return config.value + } else { + throw new Error(response.message || '获取配置失败') + } + } catch (error) { + // 如果网络请求失败,尝试使用本地存储的配置 + const storedConfig = getStoredConfig() + if (storedConfig) { + config.value = storedConfig + return config.value + } + + alertStore.showAlert(getErrorMessage(error, '获取配置失败'), 'error') + return null + } finally { + isRefreshing.value = false + } + } + + // 更新系统配置 + const updateConfig = async (newConfig: Partial): Promise => { + try { + isSaving.value = true + + const response = await ConfigService.updateConfig(newConfig) + + if (response.code === 200) { + config.value = normalizeEditableConfig({ ...config.value, ...newConfig }) + syncConfigForm(config.value) + markConfigSaved() + saveConfigToStorage(config.value) + alertStore.showAlert('配置更新成功!', 'success') + return true + } else { + throw new Error(response.message || '更新配置失败') + } + } catch (error) { + alertStore.showAlert(getErrorMessage(error, '更新配置失败'), 'error') + return false + } finally { + isSaving.value = false + } + } + + const toggleConfigFlag = (key: ConfigFlagKey) => { + config.value[key] = config.value[key] === 1 ? 0 : 1 + } + + const syncConfigForm = (nextConfig: ConfigState) => { + const sizeForm = bytesToFileSizeForm(nextConfig.uploadSize) + fileSize.value = sizeForm.value + sizeUnit.value = sizeForm.unit + + const saveTimeForm = secondsToSaveTimeForm(nextConfig.max_save_seconds) + saveTime.value = saveTimeForm.value + saveTimeUnit.value = saveTimeForm.unit + } + + const refreshConfig = async () => { + const latestConfig = await fetchConfig() + if (latestConfig) { + syncConfigForm(latestConfig) + markConfigSaved() + } + } + + const submitConfig = () => { + if (!isDirty.value || isSaving.value) { + return Promise.resolve(false) + } + + return updateConfig(buildSubmitPayload()) + } + + // 初始化配置 + const initConfig = async () => { + // 先尝试从本地存储加载 + const storedConfig = getStoredConfig() + if (storedConfig) { + config.value = storedConfig + syncConfigForm(storedConfig) + markConfigSaved() + } + + // 然后从服务器获取最新配置 + await refreshConfig() + } + + // 计算属性 + const maxFileSizeMB = computed(() => { + return Math.round(config.value.uploadSize / 1024 / 1024) + }) + + const isConfigLoaded = computed(() => { + return config.value.name !== DEFAULT_CONFIG_STATE.name || !isLoading.value + }) + + return { + // 状态 + config, + isLoading, + isRefreshing, + isSaving, + isDirty, + fileSize, + sizeUnit, + saveTime, + saveTimeUnit, + + // 计算属性 + maxFileSizeMB, + isConfigLoaded, + + // 方法 + fetchConfig, + updateConfig, + refreshConfig, + submitConfig, + toggleConfigFlag, + initConfig, + getStoredConfig, + saveConfigToStorage + } +} diff --git a/src/composables/useTheme 2.ts b/src/composables/useTheme 2.ts new file mode 100644 index 0000000..63fe823 --- /dev/null +++ b/src/composables/useTheme 2.ts @@ -0,0 +1,139 @@ +import { ref, computed } from 'vue' +import { THEME_MODES } from '@/constants' +import type { ThemeMode } from '@/types' +import { readStoredThemeMode, writeStoredThemeMode } from '@/utils/preference-storage' + +export function useTheme() { + // 状态管理 + const isDarkMode = ref(false) + const themeMode = ref(THEME_MODES.SYSTEM) + + // 检查系统颜色模式 + const checkSystemColorScheme = (): boolean => { + return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches + } + + // 从本地存储获取用户之前的选择 + const getUserPreference = (): ThemeMode | null => { + const storedPreference = readStoredThemeMode() + if (storedPreference && Object.values(THEME_MODES).includes(storedPreference as ThemeMode)) { + return storedPreference as ThemeMode + } + return null + } + + // 设置颜色模式 + const setThemeMode = (mode: ThemeMode) => { + themeMode.value = mode + writeStoredThemeMode(mode) + + // 根据模式设置实际的暗色模式状态 + if (mode === THEME_MODES.SYSTEM) { + isDarkMode.value = checkSystemColorScheme() + } else { + isDarkMode.value = mode === THEME_MODES.DARK + } + + // 更新 HTML 类名 + updateHtmlClass() + } + + // 更新 HTML 元素的类名 + const updateHtmlClass = () => { + const html = document.documentElement + if (isDarkMode.value) { + html.classList.add('dark') + } else { + html.classList.remove('dark') + } + } + + // 切换主题 + const toggleTheme = () => { + if (themeMode.value === THEME_MODES.LIGHT) { + setThemeMode(THEME_MODES.DARK) + } else if (themeMode.value === THEME_MODES.DARK) { + setThemeMode(THEME_MODES.SYSTEM) + } else { + setThemeMode(THEME_MODES.LIGHT) + } + } + + // 监听系统主题变化 + const setupSystemThemeListener = () => { + if (window.matchMedia) { + const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)') + + const handleChange = (e: MediaQueryListEvent) => { + if (themeMode.value === THEME_MODES.SYSTEM) { + isDarkMode.value = e.matches + updateHtmlClass() + } + } + + mediaQuery.addEventListener('change', handleChange) + + // 返回清理函数 + return () => { + mediaQuery.removeEventListener('change', handleChange) + } + } + return () => {} + } + + // 初始化主题 + const initTheme = () => { + const userPreference = getUserPreference() + if (userPreference) { + setThemeMode(userPreference) + } else { + setThemeMode(THEME_MODES.SYSTEM) + } + + // 设置系统主题监听 + return setupSystemThemeListener() + } + + // 计算属性 + const themeIcon = computed(() => { + switch (themeMode.value) { + case THEME_MODES.LIGHT: + return 'sun' + case THEME_MODES.DARK: + return 'moon' + case THEME_MODES.SYSTEM: + return 'monitor' + default: + return 'monitor' + } + }) + + const themeLabel = computed(() => { + switch (themeMode.value) { + case THEME_MODES.LIGHT: + return '浅色模式' + case THEME_MODES.DARK: + return '深色模式' + case THEME_MODES.SYSTEM: + return '跟随系统' + default: + return '跟随系统' + } + }) + + return { + // 状态 + isDarkMode, + themeMode, + + // 计算属性 + themeIcon, + themeLabel, + + // 方法 + setThemeMode, + toggleTheme, + initTheme, + checkSystemColorScheme + } +} diff --git a/src/composables/useTransferAnalytics 2.ts b/src/composables/useTransferAnalytics 2.ts new file mode 100644 index 0000000..a357883 --- /dev/null +++ b/src/composables/useTransferAnalytics 2.ts @@ -0,0 +1,13 @@ +import { StatsService } from '@/services' +import type { AnalyticsData } from '@/types' + +export function useTransferAnalytics() { + const fetchAnalytics = async (start?: string, end?: string): Promise => { + const response = await StatsService.getAnalytics(start, end) + return response.detail || null + } + + return { + fetchAnalytics + } +} diff --git a/src/constants/index 2.ts b/src/constants/index 2.ts new file mode 100644 index 0000000..959df51 --- /dev/null +++ b/src/constants/index 2.ts @@ -0,0 +1,102 @@ +// 应用常量配置 + +// 存储键名 +export const STORAGE_KEYS = { + COLOR_MODE: 'colorMode', + ADMIN_PASSWORD: 'adminPassword', + TOKEN: 'token', + CONFIG: 'config', + NOTIFY: 'notify' +} as const + +// 主题模式 +export const THEME_MODES = { + LIGHT: 'light', + DARK: 'dark', + SYSTEM: 'system' +} as const + +// 发送类型 +export const SEND_TYPES = { + FILE: 'file', + TEXT: 'text' +} as const + +// 警告类型 +export const ALERT_TYPES = { + SUCCESS: 'success', + ERROR: 'error', + WARNING: 'warning', + INFO: 'info' +} as const + +// 上传状态 +export const UPLOAD_STATUS = { + IDLE: 'idle', + UPLOADING: 'uploading', + SUCCESS: 'success', + ERROR: 'error' +} as const + +// API 响应状态码 +export const API_STATUS_CODES = { + SUCCESS: 200, + UNAUTHORIZED: 401, + FORBIDDEN: 403, + NOT_FOUND: 404, + SERVER_ERROR: 500 +} as const + +// 文件大小限制 (字节) +export const FILE_SIZE_LIMITS = { + MAX_FILE_SIZE: 100 * 1024 * 1024, // 100MB + CHUNK_SIZE: 1024 * 1024 // 1MB +} as const + +// 时间相关常量 +export const TIME_CONSTANTS = { + ALERT_DURATION: 5000, // 5秒 + REQUEST_TIMEOUT: 300000000, + PROGRESS_UPDATE_INTERVAL: 100 // 100毫秒 +} as const + +// 路由路径 +export const ROUTES = { + HOME: '/', + SEND: '/send', + ADMIN: '/admin', + LOGIN: '/login', + DASHBOARD: '/admin/dashboard', + FILE_MANAGE: '/admin/files', + TRASH: '/admin/trash', + ACTIVITY_LOG: '/admin/activities', + SETTINGS: '/admin/settings' +} as const + +export const ROUTE_NAMES = { + RETRIEVE: 'Retrieve', + SEND: 'Send', + ADMIN: 'Manage', + LOGIN: 'Login', + DASHBOARD: 'Dashboard', + FILE_MANAGE: 'FileManage', + TRASH: 'Trash', + ACTIVITY_LOG: 'ActivityLog', + SETTINGS: 'Settings' +} as const + +// 正则表达式 +export const REGEX_PATTERNS = { + EMAIL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, + PHONE: /^1[3-9]\d{9}$/, + CODE: /^[A-Za-z0-9]{4,16}$/ // 兼容旧码并支持当前 8 位及未来扩容 +} as const + +// 默认配置 +export const DEFAULT_CONFIG = { + name: 'FileCodeBox', + description: '文件传输工具', + maxFileSize: FILE_SIZE_LIMITS.MAX_FILE_SIZE, + allowedFileTypes: ['*'] as string[], + expireDays: 7 +} diff --git a/src/hooks/index 2.ts b/src/hooks/index 2.ts new file mode 100644 index 0000000..0207fdd --- /dev/null +++ b/src/hooks/index 2.ts @@ -0,0 +1,14 @@ +// 自定义 Vue hooks 导出文件 +// 这里可以导出所有自定义的 Vue hooks + +// 示例:导出常用的自定义 hooks +// export { useLocalStorage } from './useLocalStorage' +// export { useDebounce } from './useDebounce' +// export { useThrottle } from './useThrottle' +// export { useEventListener } from './useEventListener' +// export { useClickOutside } from './useClickOutside' + +// 目前项目中的业务逻辑已经通过 composables 进行了封装 +// hooks 文件夹主要用于存放更通用的、可复用的 Vue hooks + +export {} \ No newline at end of file diff --git a/src/i18n/index 2.ts b/src/i18n/index 2.ts new file mode 100644 index 0000000..61c2821 --- /dev/null +++ b/src/i18n/index 2.ts @@ -0,0 +1,51 @@ +import { createI18n } from 'vue-i18n' +import zhCN from './locales/zh-CN' +import enUS from './locales/en-US' +import { readStoredLocale, writeStoredLocale } from '@/utils/preference-storage' + +// 获取浏览器语言设置 +const getDefaultLocale = (): string => { + const savedLocale = readStoredLocale() + if (savedLocale) { + return savedLocale + } + + const browserLocale = navigator.language.toLowerCase() + if (browserLocale.startsWith('zh')) { + return 'zh-CN' + } + return 'en-US' +} + +const messages = { + 'zh-CN': zhCN, + 'en-US': enUS +} + +const i18n = createI18n({ + legacy: false, // 使用 Composition API 模式 + locale: getDefaultLocale(), + fallbackLocale: 'zh-CN', + messages, + globalInjection: true // 全局注入 $t 函数 +}) + +export default i18n + +// 导出切换语言的函数 +export const setLocale = (locale: string) => { + i18n.global.locale.value = locale as 'zh-CN' | 'en-US' + writeStoredLocale(locale) + document.documentElement.lang = locale +} + +// 导出获取当前语言的函数 +export const getCurrentLocale = () => { + return i18n.global.locale.value +} + +// 导出可用语言列表 +export const availableLocales = [ + { code: 'zh-CN', name: '中文' }, + { code: 'en-US', name: 'English' } +] diff --git a/src/i18n/locales/en-US 2.ts b/src/i18n/locales/en-US 2.ts new file mode 100644 index 0000000..6e40257 --- /dev/null +++ b/src/i18n/locales/en-US 2.ts @@ -0,0 +1,1037 @@ +export default { + // Common + common: { + confirm: 'Confirm', + cancel: 'Cancel', + close: 'Close', + delete: 'Delete', + edit: 'Edit', + save: 'Save', + add: 'Add', + back: 'Back', + next: 'Next', + language: 'Select language', + switchToLight: 'Switch to light mode', + switchToDark: 'Switch to dark mode', + showPassword: 'Show password', + hidePassword: 'Hide password', + openMenu: 'Open navigation menu', + closeMenu: 'Close navigation menu', + dialog: 'Dialog', + previous: 'Previous', + loading: 'Loading...', + noData: 'No Data', + success: 'Success', + error: 'Error', + warning: 'Warning', + info: 'Information', + search: 'Search', + copy: 'Copy', + more: 'More', + uploadSuccess: 'Upload successful', + uploadFailed: 'Upload failed', + copySuccess: 'Copy successful', + copyFailed: 'Copy failed', + deleteSuccess: 'Delete successful', + deleteFailed: 'Delete failed', + downloadSuccess: 'Download successful', + downloadFailed: 'Download failed', + shareSuccess: 'Share successful', + shareFailed: 'Share failed', + expiredFile: 'File has expired', + fileNotFound: 'File not found', + networkError: 'Network error', + unknownError: 'Unknown error', + invalidFileType: 'Invalid file type', + fileTooLarge: 'File too large', + uploadCanceled: 'Upload canceled', + processing: 'Processing', + pleaseWait: 'Please wait', + fileDetails: 'File Details', + enabled: 'Enabled', + disabled: 'Disabled', + minute: 'minute', + files: 'files', + second: 'second', + hour: 'hour', + day: 'day', + dayShort: 'd', + hourShort: 'h', + times: 'times', + appName: 'FileCodeBox - File Transfer', + appDescription: 'Ready-to-use file transfer system' + }, + + // Admin module + admin: { + logout: 'Logout', + dashboard: { + adminLabel: 'FileCodeBox Admin', + title: 'Dashboard', + totalFiles: 'Total Files', + storageSpace: 'Storage Space', + todayShares: 'Today Shares', + totalRetrievals: 'Total Retrievals', + activeFiles: 'Active files: {count}', + todayIncrease: 'Today added: {count}', + yesterdayShares: 'Yesterday: {count}', + serverUptime: 'Uptime', + refresh: 'Refresh', + refreshing: 'Refreshing', + lastUpdated: 'Last updated: {time}', + loadFailed: 'Failed to load dashboard data', + footerProduct: 'FileCodeBox Admin Console', + runtimeVersion: 'Runtime Version', + versionPending: 'Pending sync', + fileHealth: 'File Health', + fileHealthDesc: 'Status insights for available, risky, and pending file queues.', + activeFileRatio: 'Active Ratio', + fileShareRatio: 'File Ratio', + textShareRatio: 'Text Ratio', + binaryFiles: '{count} file shares', + textShares: '{count} text shares', + expiredFiles: 'Expired Files', + needCleanup: 'Clean up in file management', + chunkedFiles: 'Chunked Files', + storagePolicy: 'Storage & Upload Policy', + storagePolicyDesc: 'Current settings that affect upload behavior.', + storageBackend: 'Storage Backend', + singleFileLimit: 'Single File Limit', + guestUpload: 'Guest Upload', + maxSaveTime: 'Max Retention', + noSaveLimit: 'Unlimited', + todayCapacityReference: 'Today Size / Single File Limit', + healthActions: { + attention: { + title: 'Needs Attention', + description: 'Handle issue and warning files together' + }, + storageIssue: { + title: 'Storage Issues', + description: 'Review files missing download metadata' + }, + expiringSoon: { + title: 'Expiring Soon', + description: 'Extend shares that should stay available' + }, + neverRetrieved: { + title: 'Never Retrieved', + description: 'Find shares that have not been retrieved yet' + }, + permanent: { + title: 'Permanent', + description: 'View long-retention share records' + } + }, + topDownloads: { + title: 'Top 5 Downloads', + description: 'Downloads and traffic in the selected date range', + file: 'File', + downloads: 'Downloads', + traffic: 'Traffic', + status: 'Status', + empty: 'No download records', + current: 'Current', + history: 'Historical' + }, + trend: { + title: 'Download / Upload Trend', + mobileHint: 'Tap or slide to inspect; drag the bottom date axis to pan', + startDate: 'Start date', + endDate: 'End date', + zoomIn: 'Zoom in', + zoomOut: 'Zoom out', + reset: 'Reset', + noData: 'No data', + loadFailed: 'Failed to load analytics', + summary: '{window}: {downloads} downloads / {downloadTraffic}, {uploads} uploads / {uploadTraffic}' + } + }, + fileManage: { + title: 'File Management' + }, + settings: { + title: 'System Settings', + basicSettings: 'General', + websiteInfo: 'Site Information', + websiteName: 'Site Name', + websiteDescription: 'Site Description', + siteName: 'Site Name', + adminPassword: 'Admin Password', + passwordPlaceholder: 'Enter new password to change', + passwordNote: 'Leave empty to keep current', + keywords: 'SEO Keywords', + themeSelection: 'Theme', + robotsFile: 'Robots.txt Configuration', + notificationSettings: 'Notifications', + notificationTitle: 'Announcement Title', + notificationContent: 'Announcement Content', + storageSettings: 'Storage', + storagePath: 'Storage Path', + storagePathPlaceholder: 'Leave empty for default path', + storageMethod: 'Storage Type', + localStorage: 'Local Storage', + s3Storage: 'S3 Object Storage', + webdavStorage: 'WebDAV Storage', + chunkUploadNote: 'Chunked Upload (experimental, better for large files)', + s3AccessKeyId: 'Access Key ID', + s3SecretAccessKey: 'Secret Access Key', + s3BucketName: 'Bucket Name', + s3EndpointUrl: 'Endpoint URL', + s3RegionName: 'Region Name', + s3SignatureVersion: 'Signature Version', + s3Hostname: 'Custom Domain', + s3v2: 'S3v2', + s3v4: 'S3v4', + autoPlaceholder: 'Auto-detect', + enabled: 'Enabled', + disabled: 'Disabled', + webdavUrl: 'Enter WebDAV server URL', + webdavUsername: 'Enter WebDAV username', + webdavPassword: 'Enter WebDAV password', + webdavUrlPlaceholder: 'Enter WebDAV server URL', + webdavUsernamePlaceholder: 'Enter WebDAV username', + webdavPasswordPlaceholder: 'Enter WebDAV password', + enableProxy: 'Enable Download Proxy', + uploadLimits: 'Upload Settings', + uploadRateLimit: 'Time Window (limit uploads within this period)', + uploadPerMinute: 'Time Window (limit uploads within this period)', + minute: 'min', + uploadCountLimit: 'Max Files Allowed (within the time window)', + files: 'files', + fileSizeLimit: 'Max File Size', + expirationMethod: 'Expiration Options', + expirationType: 'Expiration Options', + expiration: { + day: 'Days', + hour: 'Hours', + minute: 'Minutes', + forever: 'Never Expire', + count: 'Download Count' + }, + maxSaveTime: 'Max Retention Period', + trashRetentionDays: 'Recycle Bin Default Retention', + trashRetentionDaysNote: 'Changing this recalculates cleanup time for dated items currently in the recycle bin. Permanent and already purged items are not affected.', + timeUnits: { + second: 'sec', + minute: 'min', + hour: 'hr', + day: 'day' + }, + guestUpload: 'Allow Guest Uploads', + errorLimits: 'Access Protection', + errorRateLimit: 'Detection Window (count errors within this period)', + errorPerMinute: 'Detection Window (count errors within this period)', + errorCountLimit: 'Max Errors Allowed (block after exceeding)', + times: 'times', + saveChanges: 'Save Settings', + fileSizeUnits: { + kb: 'KB', + mb: 'MB', + gb: 'GB' + } + } + }, + + // Navigation + nav: { + sendFile: 'Send File', + retrieveFile: 'Retrieve', + fileRecords: 'File Records' + }, + + // Retrieve page + retrieve: { + title: 'File Retrieval', + codeInput: { + placeholder: 'Enter 5- or 8-character retrieval code', + label: 'Retrieval Code' + }, + submit: 'Retrieve', + needSendFile: 'Need to send a file? Click here', + recordsDrawer: 'Retrieval Records', + messages: { + invalidCode: 'Please enter a 5- or 8-character retrieval code', + retrieveSuccess: 'File retrieved successfully', + invalidCodeError: 'Invalid retrieval code', + retrieveFailure: 'Failed to retrieve file: ', + networkError: 'Retrieval failed, please try again later: ', + unknownError: 'Unknown error', + previewUnavailable: 'Preview is unavailable, you can still retrieve directly' + }, + workspace: { + sendFile: 'Send File', + inspect: 'Preview', + inspecting: 'Previewing', + retrieving: 'Retrieving', + ready: 'Ready', + noPreview: 'Waiting for a code', + noPreviewDesc: + 'Enter a 5- or 8-character retrieval code to preview file details before consuming a retrieval.', + latestRecord: 'Latest Retrieval', + noRecord: 'No retrieval records yet', + currentCode: 'Code', + fileSize: 'File Size', + viewDetail: 'View Detail', + historyCount: '{count} records', + openRecords: 'Open retrieval records', + security: 'Safe Retrieval', + securityState: + 'Previewing does not consume retrieval count. Access is recorded only after confirmation.', + noExpiry: 'No limit', + unlimited: 'Unlimited', + remainingCount: '{count} left', + textType: 'Text Content', + fileType: 'File Download', + expiresAt: 'Expires At', + remainingDownloads: 'Remaining', + usedCount: 'Retrieved', + emptyCode: 'Empty', + previewState: 'Preview State', + waiting: 'Waiting' + } + }, + + // Send page + send: { + title: 'File Send', + sendText: 'Send Text', + uploadArea: { + dragText: 'Drag files here or', + clickText: 'click to select files', + textInput: 'Enter text to send here...', + placeholder: 'Click or drag files here to upload', + description: 'Supports various common formats', + descriptionWithLimit: 'Supports common formats, up to {size}', + retry: 'Retry', + selectedFiles: '{count} files selected', + status: { + initializing: 'Preparing upload...', + uploading: 'Uploading files...', + confirming: 'Confirming upload...', + success: 'Upload complete!' + } + }, + submit: 'Secure Send', + submitting: 'Sending...', + needRetrieveFile: 'Retrieve a file', + sendRecords: 'Send Records', + secureEncryption: 'Secure Encryption', + workspace: { + uploadLimit: 'Single File Limit', + uploadMode: 'Upload Mode', + standardMode: 'Standard', + chunkMode: 'Chunked', + guestPolicy: 'Guest Upload', + guestOpen: 'Allowed', + guestClosed: 'Disabled', + currentTask: 'Current Task', + awaitingFile: 'Waiting for files', + fileReady: '{count} files ready', + textDraft: 'Text draft, {count} chars', + payload: 'Payload', + expirationPreview: 'Expiration', + security: 'Security', + latestRecord: 'Latest Send', + noRecord: 'No records yet', + copyLink: 'Copy Link', + viewDetail: 'View Detail', + historyTitle: 'Send History', + historyCount: '{count} records', + openRecords: 'Open send records' + }, + fileDetails: 'File Details', + expirationMethod: 'Expiration Method', + expiration: { + day: 'By Day', + hour: 'By Hour', + minute: 'By Minute', + forever: 'Forever', + count: 'By Count', + label: 'Expiration Time', + method: 'Expiration method', + increment: 'Increase expiration value', + decrement: 'Decrease expiration value', + placeholders: { + days: 'Enter days', + hours: 'Enter hours', + minutes: 'Enter minutes', + count: 'Enter view count', + forever: 'Forever', + default: 'Enter value' + }, + units: { + days: 'days', + hours: 'hours', + minutes: 'minutes', + times: 'times', + forever: 'Forever' + } + }, + time: { + day: 'By Day', + hour: 'By Hour', + minute: 'By Minute', + forever: 'Forever', + count: 'By Count' + }, + messages: { + selectFile: 'Please select a file to upload', + enterText: 'Please enter text to send', + enterExpirationValue: 'Please enter expiration value', + expirationTooLong: 'Expiration time cannot exceed {days} days', + sendSuccess: 'File sent successfully! Retrieve code: {code}', + initChunkUploadFailed: 'Failed to initialize chunk upload', + chunkUploadFailed: 'Chunk {index} upload failed', + completeUploadFailed: 'Failed to complete upload', + uploadFailed: 'Upload failed, please try again later', + guestUploadDisabled: 'Guest upload feature is disabled', + fileSizeExceeded: 'File size exceeds limit ({size})', + serverError: 'Server response error', + sendFailed: 'Send failed, please try again later', + expiresAfterCount: 'Expires after {count} times', + expiresAt: 'Expires at {date}', + emptyFileError: 'Cannot read empty file', + fileAddedFromClipboard: 'File added from clipboard: {filename}', + fileProcessingFailed: 'File processing failed', + expiresAfter: 'Expires after {value} {unit}' + } + }, + + // File records + fileRecord: { + filename: 'Filename', + size: 'Size', + date: 'Date', + code: 'Code', + actions: 'Actions', + download: 'Download', + viewDetails: 'View Details', + deleteRecord: 'Delete Record', + deleteRecordConfirm: 'Delete this local record? The file on the server will not be deleted.', + preview: 'Preview', + copyContent: 'Copy Content', + contentCopied: 'Content copied to clipboard', + copyFailed: 'Copy failed, please try again' + }, + + // File Detail Modal + fileDetail: { + title: 'File Details', + content: 'File Content', + previewContent: 'Preview Content', + download: 'Click to Download', + qrCode: 'Retrieve QR Code', + scanQrCode: 'Scan QR code for quick retrieval' + }, + + // Content Preview Modal + contentPreview: { + title: 'Content Preview' + }, + + // File Management + fileManage: { + title: 'File Management', + subtitle: '{count} share records. Filter by status, type, and usage.', + searchPlaceholder: 'Search code, name, or text...', + allFiles: 'All Files', + detail: 'Details', + detailTitle: 'File Details', + detailLoading: 'Loading details...', + detailFailed: 'Failed to load details', + editFileInfo: 'Edit File Information', + saveChanges: 'Save Changes', + refresh: 'Refresh List', + resetFilters: 'Reset Filters', + totalFiles: 'All Records', + activeFiles: 'Available', + expiredFiles: 'Expired', + storageUsed: 'Storage Used', + statusLabel: 'Status', + typeLabel: 'Type', + healthLabel: 'Health', + viewPreset: 'View', + viewPresetCustom: 'Custom Filters', + viewPresetAll: 'All Files', + viewPresetAttention: 'Needs Attention', + viewPresetExpiringSoon: 'Expiring Soon', + viewPresetStorageIssue: 'Storage Issues', + viewPresetNeverRetrieved: 'Never Retrieved', + viewPresetPermanent: 'Permanent', + saveViewPreset: 'Save View', + updateViewPreset: 'Update View', + deleteViewPreset: 'Delete View', + viewPresetNamePrompt: 'Enter a view name', + viewPresetSaveSuccess: 'View saved', + viewPresetSaveFailed: 'Failed to save view', + viewPresetDeleteConfirm: 'Delete view "{name}"?', + viewPresetDeleteSuccess: 'View deleted', + viewPresetDeleteFailed: 'Failed to delete view', + viewPresetLoadFailed: 'Failed to load saved views; using built-in views', + all: 'All', + active: 'Available', + expired: 'Expired', + fileType: 'File', + textType: 'Text', + chunkedType: 'Chunked', + healthFilters: { + all: 'All', + attention: 'Needs Attention', + danger: 'Issues', + warning: 'Warnings', + expiringSoon: 'Expiring Soon', + storageIssue: 'Storage Issues', + neverRetrieved: 'Never Retrieved', + healthy: 'Healthy', + permanent: 'Permanent' + }, + sortBy: 'Sort', + sortOrder: 'Direction', + unlimited: 'Unlimited', + remaining: '{count} left', + loadError: 'Failed to load file list', + noMatches: 'No matching files', + viewText: 'View', + textPreview: 'Text Preview', + copyText: 'Copy Text', + copyCode: 'Copy Code', + copyLink: 'Copy Link', + copySuccess: 'Text copied to clipboard', + copyCodeSuccess: 'Retrieve code copied to clipboard', + copyLinkSuccess: 'Retrieve link copied to clipboard', + copyFailed: 'Copy failed, please try again', + charCount: '{count} characters', + downloadFile: 'Download File', + exportText: 'Export Text', + downloadSuccess: 'Downloaded: {name}', + exportSuccess: 'Exported: {name}', + downloadFailed: 'Download failed', + previewFailed: 'Failed to load preview', + loadingPreview: 'Loading preview...', + previewComplete: 'Loaded full content, {count} characters', + previewTruncated: 'Showing {shown} / {total} characters', + previewFallback: 'Preview endpoint unavailable; using text from the list', + selectCurrentPage: 'Select current page', + selectedCount: '{count} selected', + mobileBatchActions: 'Mobile batch actions', + policyActionsLabel: 'Policy', + selectFile: 'Select {name}', + clearSelection: 'Clear Selection', + batchDelete: 'Batch Delete', + batchDeleteConfirm: 'Delete the selected {count} files? This action cannot be undone.', + batchDeleteSuccess: 'Deleted {count} files', + batchDeletePartialSuccess: 'Deleted {count} files, {failed} failed', + batchDeleteFailed: 'Batch delete failed', + batchEdit: 'Batch Edit', + batchEditTitle: 'Batch Edit File Policy', + batchEditSelected: 'Update the selected {count} files', + batchEditMode: 'Update Mode', + batchEditExpiresAt: 'Set Expiration Time', + batchEditRelativeExpire: 'Expire After Duration', + batchEditRelativeExpireValue: 'Expiration Duration', + batchEditRelativeExpirePlaceholder: 'Enter amount', + batchEditRelativeExpireUnit: 'Unit', + batchEditRelativeExpireHours: 'Hours', + batchEditRelativeExpireDays: 'Days', + batchEditDownloadLimit: 'Set Retrieval Limit', + batchEditForever: 'Make Permanent', + batchEditForeverHint: 'Clear the expiration time and make retrievals unlimited.', + batchUpdateConfirm: 'Update the selected {count} files?', + batchUpdateSuccess: 'Updated {count} files', + batchUpdatePartialSuccess: 'Updated {count} files, {failed} failed', + batchUpdateFailed: 'Batch update failed', + batchUpdateNoFields: 'Choose a policy to update', + batchPolicyActionConfirm: 'Apply "{action}" to the selected {count} files?', + batchPolicyActionSuccess: 'Processed {count} files', + batchPolicyActionPartialSuccess: 'Processed {count} files, {failed} failed', + batchPolicyActionFailed: 'Batch policy action failed', + policyActionSuccess: 'File policy updated', + policyActionFailed: 'Failed to apply policy action', + metadataInfo: 'Operations Notes', + metadataHint: + 'Visible to admins only. Use it for handling notes, archive tags, and follow-up actions.', + metadataNote: 'Note', + metadataNotePlaceholder: 'Record context, handling history, or ownership...', + metadataTags: 'Tags', + metadataTagsPlaceholder: 'Comma-separated, e.g. Client A, Renew, Important', + metadataUpdatedAt: 'Last saved: {time}', + metadataNeverUpdated: 'No notes saved yet', + saveMetadata: 'Save Notes', + metadataSaveSuccess: 'Notes and tags saved', + metadataSaveFailed: 'Failed to save notes', + policyActions: { + extend24h: 'Extend 24h', + extend7d: 'Extend 7d', + makePermanent: 'Make Permanent', + resetDownloadLimit: 'Reset to {count}' + }, + policyActionDescriptions: { + extend24h: 'Add one day from the active expiration', + extend7d: 'Good for a one-week temporary extension', + makePermanent: 'Clear expiration time and retrieval limits', + resetDownloadLimit: 'Restore retrievals to {count}' + }, + applyBatchEdit: 'Apply Changes', + overview: 'Overview', + policyInfo: 'Policy', + storageInfo: 'Storage', + statusInsight: 'Status Insight', + nextAction: 'Next Action', + lifecycle: 'Lifecycle', + expandLifecycle: 'Show all lifecycle records ({count})', + collapseLifecycle: 'Collapse lifecycle records', + expandRetrievalHistory: 'Show all retrieval records ({count})', + collapseRetrievalHistory: 'Collapse retrieval records', + permanent: 'Permanent', + createdAt: 'Created Time', + remainingDownloads: 'Remaining Downloads', + textLength: 'Text Length', + hasDownloadLimit: 'Has Retrieval Limit', + hasExpirationTime: 'Has Expiration', + canPreviewText: 'Can Preview Text', + canDownload: 'Can Download', + storageBackend: 'Storage Backend', + fileHash: 'File Hash', + isChunked: 'Chunked Upload', + filePath: 'Storage Path', + uuidFileName: 'Stored File Name', + uploadId: 'Upload Session', + yes: 'Yes', + no: 'No', + insightSeverity: { + success: 'Healthy', + warning: 'Needs Attention', + danger: 'Issue', + info: 'Info', + neutral: 'Watch' + }, + insightStates: { + available: 'Available for retrieval', + expired: 'Unavailable for retrieval', + storage_incomplete: 'Storage metadata incomplete', + expiring_soon: 'Expiring soon', + permanent: 'Permanent' + }, + insightActions: { + monitor: 'No action needed', + extend_or_delete: 'Extend or clean up', + inspect_storage: 'Check storage info', + extend_expiration: 'Extend validity' + }, + insightReasons: { + expired: 'Past expiration time', + download_limit_exhausted: 'Retrieval limit exhausted', + expires_soon: 'Expires within 24 hours', + never_retrieved: 'Never retrieved', + storage_metadata_incomplete: 'Missing downloadable storage metadata', + chunked_upload: 'Created by chunked upload' + }, + timeline: { + status: { + done: 'Done', + pending: 'Pending', + active: 'Active', + expired: 'Expired', + exhausted: 'Exhausted', + unlimited: 'Unlimited' + }, + created: { + title: 'Record Created', + description: 'The share record has been created and is currently {status}.' + }, + content_ready: { + title: 'Content Ready', + description: 'Content type is {detail}; current status is {status}.' + }, + upload_session: { + title: 'Upload Session', + description: 'Upload session recorded: {detail}.' + }, + expiration_policy: { + title: 'Expiration Policy', + description: 'Expiration policy is currently {status}.', + remaining: '{time} left', + overdue: '{time} overdue' + }, + download_limit: { + title: 'Retrieval Limit', + description: 'Retrieval limit is currently {status}; {value}.' + }, + retrieved: { + title: 'Retrieval History', + description: 'Retrieved {value}; current status is {status}.' + }, + retrieved_event: { + title: 'Retrieval #{value}', + description: 'This retrieval is complete; current status is {status}.' + }, + retrieved_event_unknown: { + title: 'Retrieval History', + description: 'This retrieval is complete; current status is {status}.' + } + }, + headers: { + select: 'Select', + code: 'Retrieve Code', + name: 'Name', + type: 'Type', + size: 'Size', + usage: 'Retrievals', + status: 'Status', + description: 'Description', + expiration: 'Expiration', + actions: 'Actions' + }, + sort: { + createdAt: 'Created Time', + expiredAt: 'Expiration', + name: 'Name', + size: 'Size', + usedCount: 'Retrievals', + code: 'Retrieve Code', + desc: 'Descending', + asc: 'Ascending' + }, + form: { + code: 'Retrieve Code', + codePlaceholder: 'Enter retrieve code', + filename: 'File Name', + filenamePlaceholder: 'Enter file name', + suffix: 'File Extension', + suffixPlaceholder: 'Enter file extension', + downloadLimit: 'Download Limit', + downloadLimitPlaceholder: 'Enter download limit' + } + }, + + // Side drawer + drawer: { + noRecords: 'No records' + }, + + // Admin pages + manage: { + settings: { + title: 'System Settings', + basicSettings: 'General', + websiteInfo: 'Site Information', + websiteName: 'Site Name', + websiteDescription: 'Site Description', + siteName: 'Site Name', + adminPassword: 'Admin Password', + passwordPlaceholder: 'Enter new password to change', + passwordNote: 'Leave empty to keep current', + keywords: 'SEO Keywords', + themeSelection: 'Theme', + notificationSettings: 'Notifications', + notificationTitle: 'Announcement Title', + notificationContent: 'Announcement Content', + storageSettings: 'Storage', + storagePath: 'Storage Path', + storagePathPlaceholder: 'Leave empty for default path', + storageMethod: 'Storage Type', + localStorage: 'Local Storage', + s3Storage: 'S3 Object Storage', + webdavStorage: 'WebDAV Storage', + chunkUploadNote: 'Chunked Upload (experimental, better for large files)', + enabled: 'Enabled', + disabled: 'Disabled', + webdavUrl: 'Enter WebDAV server URL', + webdavUsername: 'Enter WebDAV username', + webdavPassword: 'Enter WebDAV password', + webdavUrlPlaceholder: 'Enter WebDAV server URL', + webdavUsernamePlaceholder: 'Enter WebDAV username', + webdavPasswordPlaceholder: 'Enter WebDAV password', + enableProxy: 'Enable Download Proxy', + uploadLimits: 'Upload Settings', + uploadRateLimit: 'Time Window (limit uploads within this period)', + uploadPerMinute: 'Time Window (limit uploads within this period)', + minute: 'min', + uploadCountLimit: 'Max Files Allowed (within the time window)', + files: 'files', + fileSizeLimit: 'Max File Size', + expirationMethod: 'Expiration Options', + expirationType: 'Expiration Options', + expiration: { + day: 'Days', + hour: 'Hours', + minute: 'Minutes', + forever: 'Never Expire', + count: 'Download Count' + }, + maxSaveTime: 'Max Retention Period', + trashRetentionDays: 'Recycle Bin Default Retention', + trashRetentionDaysNote: 'Changing this recalculates cleanup time for dated items currently in the recycle bin. Permanent and already purged items are not affected.', + timeUnits: { + second: 'sec', + minute: 'min', + hour: 'hr', + day: 'day' + }, + guestUpload: 'Allow Guest Uploads', + errorLimits: 'Access Protection', + errorRateLimit: 'Detection Window (count errors within this period)', + errorPerMinute: 'Detection Window (count errors within this period)', + errorCountLimit: 'Max Errors Allowed (block after exceeding)', + times: 'times', + fileSizeUnits: { + kb: 'KB', + mb: 'MB', + gb: 'GB' + }, + saveChanges: 'Save Settings', + refreshConfig: 'Refresh Config', + refreshing: 'Refreshing', + saving: 'Saving', + unsavedChanges: 'Unsaved changes', + allChangesSaved: 'Saved', + refreshBlocked: 'Save current changes before refreshing' + ,sectionNavigation: 'Settings section navigation' + ,reloadSaved: 'Reload saved settings' + ,discardChanges: 'Discard changes' + ,discardChangesConfirm: 'Discard unsaved changes and reload the saved settings?' + ,robotsWarning: 'A Disallow: / rule blocks search engines from crawling the entire site.' + ,fileSizeUnit: 'File size unit' + ,timeUnit: 'Time unit' + }, + systemSettings: { + title: 'System Settings', + basicSettings: 'General', + websiteInfo: 'Site Information', + websiteName: 'Site Name', + websiteDescription: 'Site Description', + adminPassword: 'Admin Password', + passwordPlaceholder: 'Enter new password to change', + passwordNote: 'Leave empty to keep current', + keywords: 'SEO Keywords', + themeSelection: 'Theme', + notificationSettings: 'Notifications', + notificationTitle: 'Announcement Title', + notificationContent: 'Announcement Content', + storageSettings: 'Storage', + storagePath: 'Storage Path', + storagePathPlaceholder: 'Leave empty for default path', + storageMethod: 'Storage Type', + localStorage: 'Local Storage', + s3Storage: 'S3 Object Storage', + webdavStorage: 'WebDAV Storage', + chunkUploadNote: 'Chunked Upload (experimental, better for large files)', + enabled: 'Enabled', + disabled: 'Disabled', + webdavUrl: 'Enter WebDAV server URL', + webdavUsername: 'Enter WebDAV username', + webdavPassword: 'Enter WebDAV password', + enableProxy: 'Enable Download Proxy', + uploadLimits: 'Upload Settings', + uploadRateLimit: 'Time Window (limit uploads within this period)', + minute: 'min', + uploadCountLimit: 'Max Files Allowed (within the time window)', + files: 'files', + fileSizeLimit: 'Max File Size', + expirationMethod: 'Expiration Options', + expirationMethods: { + day: 'Days', + hour: 'Hours', + minute: 'Minutes', + forever: 'Never Expire', + count: 'Download Count' + }, + expiration: { + day: 'Days', + hour: 'Hours', + minute: 'Minutes', + forever: 'Never Expire', + count: 'Download Count' + }, + maxSaveTime: 'Max Retention Period', + trashRetentionDays: 'Recycle Bin Default Retention', + trashRetentionDaysNote: 'Changing this recalculates cleanup time for dated items currently in the recycle bin. Permanent and already purged items are not affected.', + timeUnits: { + second: 'sec', + minute: 'min', + hour: 'hr', + day: 'day' + }, + guestUpload: 'Allow Guest Uploads', + errorLimits: 'Access Protection', + errorRateLimit: 'Detection Window (count errors within this period)', + errorCountLimit: 'Max Errors Allowed (block after exceeding)', + times: 'times', + saveSettings: 'Save Settings', + saveSuccess: 'Settings saved successfully', + saveFailed: 'Failed to save, please try again', + getConfigFailed: 'Failed to load settings, please refresh' + }, + dashboard: { + title: 'Dashboard', + totalFiles: 'Total Files', + storageSpace: 'Storage Space', + todayShares: 'Today Shares', + totalRetrievals: 'Total Retrievals', + activeFiles: 'Active files: {count}', + todayIncrease: 'Today added: {count}', + yesterdayShares: 'Yesterday: {count}', + serverUptime: 'Uptime', + refresh: 'Refresh', + fileHealth: 'File Health', + fileHealthDesc: 'Status insights for available, risky, and pending file queues.', + activeFileRatio: 'Active Ratio', + fileShareRatio: 'File Ratio', + textShareRatio: 'Text Ratio', + binaryFiles: '{count} file shares', + textShares: '{count} text shares', + expiredFiles: 'Expired Files', + needCleanup: 'Clean up in file management', + chunkedFiles: 'Chunked Files', + storagePolicy: 'Storage & Upload Policy', + storagePolicyDesc: 'Current settings that affect upload behavior.', + storageBackend: 'Storage Backend', + singleFileLimit: 'Single File Limit', + guestUpload: 'Guest Upload', + maxSaveTime: 'Max Retention', + noSaveLimit: 'Unlimited', + todayCapacityReference: 'Today Size / Single File Limit' + }, + fileManage: { + title: 'File Management', + searchPlaceholder: 'Search file name, description...', + allFiles: 'All Files', + editFileInfo: 'Edit File Info', + saveChanges: 'Save Changes', + headers: { + code: 'Code', + name: 'Name', + size: 'Size', + description: 'Description', + expiration: 'Expiration', + actions: 'Actions' + }, + form: { + code: 'Code', + codePlaceholder: 'Enter code', + filename: 'File Name', + filenamePlaceholder: 'Enter file name', + suffix: 'File Suffix', + suffixPlaceholder: 'Enter file suffix', + downloadLimit: 'Download Limit', + downloadLimitPlaceholder: 'Enter download limit' + }, + updateFailed: 'Update failed', + deleteFailed: 'Delete failed', + deleteConfirm: 'Delete this file? This action cannot be undone.', + loadFileListFailed: 'Failed to load file list' + }, + login: { + title: 'Login', + password: 'Password', + passwordPlaceholder: 'Password', + loginButton: 'Login', + loggingIn: 'Logging in...', + invalidPassword: 'Invalid password', + passwordTooShort: 'Password must be at least 6 characters', + loginFailed: 'Login failed', + noValidToken: 'Login failed: No valid token received' + } + }, + + // File size units + fileSize: { + bytes: 'Bytes', + kb: 'KB', + mb: 'MB', + gb: 'GB', + tb: 'TB' + }, + + // Utility functions + utils: { + // Time formatting + formatTime: 'Format timestamp to readable format', + formatFileSize: 'Format file size', + formatDuration: 'Format duration', + time: { + forever: 'Forever', + day: 'day', + hour: 'hour', + minute: 'minute', + second: 'second' + }, + copyToClipboard: 'Copy text to clipboard', + copyFailed: 'Copy failed:', + debounce: 'Debounce function', + throttle: 'Throttle function', + validateEmail: 'Validate email format', + validateUrl: 'Validate URL format', + generateRandomString: 'Generate random string', + deepClone: 'Deep clone object', + getFileExtension: 'Get file extension', + isMobileDevice: 'Check if mobile device', + formatNumber: 'Format number with thousand separators', + clipboard: { + title: 'Clipboard utility functions', + copyText: 'Copy text to clipboard', + copySuccess: 'Copy successful', + copyFailed: 'Copy failed, please copy manually' + } + }, + + // Components + components: { + pagination: { + navigation: 'Pagination', + range: 'Showing {start} to {end} of {total}', + pageSize: 'Items per page', + perPage: '{size}/page', + goToPage: 'Go to page {page}', + showing: 'Showing', + to: 'to', + of: 'of', + total: 'total', + previous: 'Previous', + next: 'Next' + }, + languageSwitcher: { + clickOutsideToClose: 'Click outside to close dropdown menu' + }, + borderProgressBar: { + borderWidth: 'Border width', + cornerRadius: 'Corner radius', + createGradient: 'Create gradient', + drawBackground: 'Draw background', + calculateProgress: 'Calculate progress', + drawProgress: 'Draw progress' + } + }, + + // Miscellaneous + misc: { + emptyFileError: 'Cannot read empty file', + fileAddedFromClipboard: 'File added from clipboard: ', + fileProcessFailed: 'File processing failed', + chunkSize: 'Keep 2MB chunk size for hash calculation', + secureContext: 'If not in secure context (HTTP), return an alternative hash based on file info', + cryptoFallback: 'If crypto.subtle.digest fails, use fallback method', + generateAlternativeHash: 'Function to generate alternative hash', + fileInfoHash: 'Generate simple hash using filename, size and last modified time', + convertToHex: 'Convert to hex string and pad to 64 bits', + defaultChunkSize: 'Default chunk size is 5MB', + initChunkUpload: '1. Initialize chunk upload', + uploadChunk: '2. Upload chunk', + completeUpload: '3. Complete upload', + chunkUploadFailed: 'Chunk upload failed: ', + uploadProgressListener: 'Add upload progress listener', + noLimitCheck: 'If no limit, return true directly', + expirationValidation: 'Add expiration time validation', + chunkUploadReplacement: 'Use chunk upload to replace direct upload', + textUploadUnchanged: 'Text upload remains unchanged', + addSendRecord: 'Add new send record', + permanent: 'Permanent', + sendSuccessMessage: 'Show send success message', + resetForm: 'Reset form - only reset file and text content, keep expiration info', + showDetails: 'Show details', + autoCopyLink: 'Auto copy retrieve code link', + delayedLoading: 'Use onMounted hook to delay load non-critical resources or initialization', + nonCriticalInit: 'Place non-immediately needed initialization code here' + } +} diff --git a/src/i18n/locales/zh-CN 2.ts b/src/i18n/locales/zh-CN 2.ts new file mode 100644 index 0000000..20bcbc8 --- /dev/null +++ b/src/i18n/locales/zh-CN 2.ts @@ -0,0 +1,1057 @@ +export default { + // 通用 + common: { + confirm: '确认', + cancel: '取消', + close: '关闭', + delete: '删除', + edit: '编辑', + save: '保存', + add: '添加', + back: '返回', + next: '下一页', + language: '选择语言', + switchToLight: '切换到浅色模式', + switchToDark: '切换到深色模式', + showPassword: '显示密码', + hidePassword: '隐藏密码', + openMenu: '打开导航菜单', + closeMenu: '关闭导航菜单', + dialog: '对话框', + previous: '上一页', + loading: '加载中...', + noData: '暂无数据', + success: '成功', + error: '错误', + warning: '警告', + info: '信息', + search: '搜索', + copy: '复制', + more: '更多', + uploadSuccess: '上传成功', + uploadFailed: '上传失败', + copySuccess: '复制成功', + copyFailed: '复制失败', + deleteSuccess: '删除成功', + deleteFailed: '删除失败', + downloadSuccess: '下载成功', + downloadFailed: '下载失败', + shareSuccess: '分享成功', + shareFailed: '分享失败', + expiredFile: '文件已过期', + fileNotFound: '文件不存在', + networkError: '网络错误', + unknownError: '未知错误', + invalidFileType: '不支持的文件类型', + fileTooLarge: '文件过大', + uploadCanceled: '上传已取消', + processing: '处理中...', + pleaseWait: '请稍候...', + fileDetails: '文件详情', + enabled: '已开启', + disabled: '已关闭', + minute: '分钟', + files: '个文件', + second: '秒', + hour: '小时', + day: '天', + dayShort: '天', + hourShort: '小时', + times: '次', + appName: '文件快递柜 - FileCodeBox', + appDescription: '开箱即用的文件快传系统' + }, + + // 管理员模块 + admin: { + logout: '退出登录', + dashboard: { + adminLabel: 'FileCodeBox 管理后台', + title: '仪表盘', + totalFiles: '总文件数', + storageSpace: '存储空间', + todayShares: '今日分享', + totalRetrievals: '累计取件', + activeFiles: '有效文件:{count}', + todayIncrease: '今日新增容量:{count}', + yesterdayShares: '昨日分享:{count}', + serverUptime: '运行时间', + refresh: '刷新数据', + refreshing: '刷新中', + lastUpdated: '最近更新:{time}', + loadFailed: '仪表盘数据加载失败', + footerProduct: 'FileCodeBox 管理后台', + runtimeVersion: '运行版本', + versionPending: '待同步', + fileHealth: '文件健康', + fileHealthDesc: '基于状态洞察统计可取件、风险与待处理队列。', + activeFileRatio: '有效占比', + fileShareRatio: '文件占比', + textShareRatio: '文本占比', + binaryFiles: '文件分享 {count} 个', + textShares: '文本分享 {count} 条', + expiredFiles: '已过期文件', + needCleanup: '可在文件管理中清理', + chunkedFiles: '分片上传文件', + storagePolicy: '存储与上传策略', + storagePolicyDesc: '当前后台配置对上传链路的影响。', + storageBackend: '存储后端', + singleFileLimit: '单文件上限', + guestUpload: '游客上传', + maxSaveTime: '最长保存', + noSaveLimit: '不限制', + todayCapacityReference: '今日容量 / 单文件上限', + healthActions: { + attention: { + title: '需关注', + description: '集中处理异常和预警文件' + }, + storageIssue: { + title: '存储异常', + description: '检查缺少下载信息的文件' + }, + expiringSoon: { + title: '即将过期', + description: '优先续期仍需保留的分享' + }, + neverRetrieved: { + title: '未取件', + description: '识别创建后尚未被取件的记录' + }, + permanent: { + title: '永久有效', + description: '查看长期保留的分享记录' + } + }, + topDownloads: { + title: '热门下载 Top 5', + description: '统计当前日期范围内的下载次数和流量', + file: '文件', + downloads: '下载', + traffic: '流量', + status: '状态', + empty: '暂无下载记录', + current: '现存', + history: '历史' + }, + trend: { + title: '下载/上传趋势', + mobileHint: '轻触或滑动查看数据;拖动底部日期轴平移图表', + startDate: '开始日期', + endDate: '结束日期', + zoomIn: '放大', + zoomOut: '缩小', + reset: '重置', + noData: '无数据', + loadFailed: '统计加载失败', + summary: '{window},下载 {downloads} 次 / {downloadTraffic},上传 {uploads} 次 / {uploadTraffic}' + } + }, + fileManage: { + title: '文件管理' + }, + settings: { + title: '系统设置', + basicSettings: '基本设置', + websiteInfo: '网站基本信息', + websiteName: '网站名称', + websiteDescription: '网站描述', + siteName: '网站名称', + adminPassword: '管理员密码', + passwordPlaceholder: '如需修改请输入新密码', + passwordNote: '不修改请留空', + keywords: 'SEO 关键词', + themeSelection: '界面主题', + robotsFile: 'Robots.txt 配置', + notificationSettings: '通知设置', + notificationTitle: '公告标题', + notificationContent: '公告内容', + storageSettings: '存储配置', + storagePath: '文件存储路径', + storagePathPlaceholder: '使用默认路径可留空', + storageMethod: '存储方式', + localStorage: '本地存储', + s3Storage: 'S3 对象存储', + webdavStorage: 'WebDAV 存储', + chunkUploadNote: '分片上传(实验性功能,大文件上传更稳定)', + s3AccessKeyId: 'Access Key ID', + s3SecretAccessKey: 'Secret Access Key', + s3BucketName: '存储桶名称', + s3EndpointUrl: '服务端点 URL', + s3RegionName: '区域名称', + s3SignatureVersion: '签名版本', + s3Hostname: '自定义域名', + s3v2: 'S3v2', + s3v4: 'S3v4', + autoPlaceholder: '自动识别', + enabled: '已启用', + disabled: '已禁用', + webdavUrl: '输入 WebDAV 服务地址', + webdavUsername: '输入 WebDAV 用户名', + webdavPassword: '输入 WebDAV 密码', + webdavUrlPlaceholder: '输入 WebDAV 服务地址', + webdavUsernamePlaceholder: '输入 WebDAV 用户名', + webdavPasswordPlaceholder: '输入 WebDAV 密码', + enableProxy: '启用下载代理', + uploadLimits: '上传设置', + uploadRateLimit: '限流时间窗口(在此时间内限制上传次数)', + uploadPerMinute: '限流时间窗口(在此时间内限制上传次数)', + minute: '分钟', + uploadCountLimit: '允许上传文件数(限流窗口内最多上传几个文件)', + files: '个文件', + fileSizeLimit: '单文件大小上限', + expirationMethod: '过期方式', + expirationType: '过期方式', + expiration: { + day: '按天数', + hour: '按小时', + minute: '按分钟', + forever: '永久有效', + count: '按下载次数' + }, + maxSaveTime: '文件最长保存时间', + trashRetentionDays: '回收站默认保留期', + trashRetentionDaysNote: '修改后会重新计算当前回收站中有期限文件的清理时间;已设为永久或已清理的文件不受影响。', + timeUnits: { + second: '秒', + minute: '分钟', + hour: '小时', + day: '天' + }, + guestUpload: '允许游客上传', + errorLimits: '访问保护', + errorRateLimit: '检测时间窗口(在此时间内统计错误次数)', + errorPerMinute: '检测时间窗口(在此时间内统计错误次数)', + errorCountLimit: '允许错误次数(超过后临时封禁)', + times: '次', + saveChanges: '保存设置', + fileSizeUnits: { + kb: 'KB', + mb: 'MB', + gb: 'GB' + } + } + }, + + // 页面标题和导航 + nav: { + sendFile: '发送文件', + retrieveFile: '取件', + fileRecords: '取件记录' + }, + + // 取件页面 + retrieve: { + title: '文件取件', + codeInput: { + placeholder: '输入 5 位或 8 位取件码', + label: '取件码', + }, + submit: '取件', + needSendFile: '需要发送文件?点击这里', + recordsDrawer: '取件记录', + messages: { + invalidCode: '请输入 5 位或 8 位取件码', + retrieveSuccess: '文件获取成功', + invalidCodeError: '无效的取件码', + retrieveFailure: '获取文件失败:', + networkError: '取件失败,请稍后重试:', + unknownError: '未知错误', + previewUnavailable: '暂时无法预览文件信息,可直接取件' + }, + workspace: { + sendFile: '发送文件', + inspect: '预览', + inspecting: '预览中', + retrieving: '取件中', + ready: '可取件', + noPreview: '等待取件码', + noPreviewDesc: '输入 5 位或 8 位取件码后会先读取文件信息,确认后再消耗取件次数。', + latestRecord: '最近取件', + noRecord: '暂无取件记录', + currentCode: '取件码', + fileSize: '文件大小', + viewDetail: '查看详情', + historyCount: '{count} 条记录', + openRecords: '打开取件记录', + security: '安全取件', + securityState: '预览不会消耗取件次数,确认取件后才会记录访问。', + noExpiry: '不限制', + unlimited: '不限次数', + remainingCount: '剩余 {count} 次', + textType: '文本内容', + fileType: '文件下载', + expiresAt: '过期时间', + remainingDownloads: '剩余次数', + usedCount: '已取件', + emptyCode: '未输入', + previewState: '预览状态', + waiting: '等待输入' + } + }, + + // 发送页面 + send: { + title: '文件发送', + sendText: '发送文本', + fileDetails: '文件详情', + expirationMethod: '过期方式', + uploadArea: { + dragText: '拖拽文件到此处或', + clickText: '点击选择文件', + textInput: '在此输入要发送的文本...', + placeholder: '点击或拖放文件到此处上传', + description: '支持各种常见格式', + descriptionWithLimit: '支持各种常见格式,最大{size}', + retry: '重试', + selectedFiles: '已选择 {count} 个文件', + status: { + initializing: '正在初始化上传...', + uploading: '正在上传文件...', + confirming: '正在确认上传...', + success: '上传成功!' + } + }, + submit: '安全寄送', + submitting: '发送中...', + needRetrieveFile: '前往取件', + sendRecords: '发件记录', + secureEncryption: '安全加密', + workspace: { + uploadLimit: '单文件上限', + uploadMode: '上传模式', + standardMode: '标准上传', + chunkMode: '分片上传', + guestPolicy: '游客上传', + guestOpen: '允许', + guestClosed: '已关闭', + currentTask: '当前任务', + awaitingFile: '等待选择文件', + fileReady: '已选择 {count} 个文件', + textDraft: '文本草稿 {count} 字', + payload: '发送内容', + expirationPreview: '有效期', + security: '安全状态', + latestRecord: '最近一次发送', + noRecord: '暂无记录', + copyLink: '复制链接', + viewDetail: '查看详情', + historyTitle: '发送历史', + historyCount: '{count} 条记录', + openRecords: '打开发送记录' + }, + fileDetail: { + title: '文件详情', + content: '文件内容', + previewContent: '预览内容', + download: '点击下载', + qrCode: '取件二维码', + scanQrCode: '扫描二维码快速取件' + }, + contentPreview: { + title: '内容预览' + }, + fileManage: { + title: '文件管理', + searchPlaceholder: '搜索文件名称、描述...', + allFiles: '所有文件', + editFileInfo: '编辑文件信息', + saveChanges: '保存更改', + headers: { + code: '取件码', + name: '名称', + size: '大小', + description: '描述', + expiration: '过期时间', + actions: '操作' + }, + form: { + code: '取件码', + codePlaceholder: '输入取件码', + filename: '文件名称', + filenamePlaceholder: '输入文件名称', + suffix: '文件后缀', + suffixPlaceholder: '输入文件后缀', + downloadLimit: '下载次数限制', + downloadLimitPlaceholder: '输入下载次数限制' + } + }, + expiration: { + label: '过期时间', + method: '过期方式', + increment: '增加过期值', + decrement: '减少过期值', + placeholders: { + days: '输入天数', + hours: '输入小时数', + minutes: '输入分钟数', + count: '输入查看次数', + forever: '永久', + default: '输入值' + }, + units: { + days: '天', + hours: '小时', + minutes: '分钟', + times: '次', + forever: '永久' + } + }, + time: { + day: '按天', + hour: '按小时', + minute: '按分钟', + forever: '永久', + count: '按次数' + }, + messages: { + selectFile: '请选择要上传的文件', + enterText: '请输入要发送的文本', + enterExpirationValue: '请输入过期值', + expirationTooLong: '过期时间不能超过{days}天', + sendSuccess: '文件发送成功!取件码:{code}', + initChunkUploadFailed: '初始化切片上传失败', + chunkUploadFailed: '切片 {index} 上传失败', + completeUploadFailed: '完成上传失败', + uploadFailed: '上传失败,请稍后重试', + guestUploadDisabled: '游客上传功能已关闭', + fileSizeExceeded: '文件大小超过限制 ({size})', + serverError: '服务器响应异常', + sendFailed: '发送失败,请稍后重试', + expiresAfterCount: '{count}次后过期', + expiresAt: '{date}过期', + emptyFileError: '无法读取空文件', + fileAddedFromClipboard: '已从剪贴板添加文件:{filename}', + fileProcessingFailed: '文件处理失败', + expiresAfter: '{value}{unit}后过期' + } + }, + + // 文件管理 + fileManage: { + title: '文件管理', + subtitle: '共 {count} 条分享记录,可按状态、类型和使用情况快速筛选。', + searchPlaceholder: '搜索取件码、名称或文本...', + allFiles: '所有文件', + detail: '详情', + detailTitle: '文件详情', + detailLoading: '正在加载详情...', + detailFailed: '详情加载失败', + editFileInfo: '编辑文件信息', + saveChanges: '保存更改', + refresh: '刷新列表', + resetFilters: '重置筛选', + totalFiles: '全部记录', + activeFiles: '可取件', + expiredFiles: '已过期', + storageUsed: '占用空间', + statusLabel: '状态', + typeLabel: '类型', + healthLabel: '健康', + viewPreset: '视图', + viewPresetCustom: '自定义筛选', + viewPresetAll: '全部文件', + viewPresetAttention: '需关注', + viewPresetExpiringSoon: '即将过期', + viewPresetStorageIssue: '存储异常', + viewPresetNeverRetrieved: '未取件', + viewPresetPermanent: '永久有效', + saveViewPreset: '保存视图', + updateViewPreset: '覆盖视图', + deleteViewPreset: '删除视图', + viewPresetNamePrompt: '输入视图名称', + viewPresetSaveSuccess: '视图已保存', + viewPresetSaveFailed: '视图保存失败', + viewPresetDeleteConfirm: '确认删除视图“{name}”?', + viewPresetDeleteSuccess: '视图已删除', + viewPresetDeleteFailed: '视图删除失败', + viewPresetLoadFailed: '视图预设加载失败,已使用内置视图', + all: '全部', + active: '可取件', + expired: '已过期', + fileType: '文件', + textType: '文本', + chunkedType: '分片', + healthFilters: { + all: '全部', + attention: '需关注', + danger: '异常', + warning: '预警', + expiringSoon: '即将过期', + storageIssue: '存储异常', + neverRetrieved: '未取件', + healthy: '健康', + permanent: '永久有效' + }, + sortBy: '排序', + sortOrder: '方向', + unlimited: '不限次数', + remaining: '剩余 {count} 次', + loadError: '文件列表加载失败', + noMatches: '没有匹配的文件', + viewText: '查看', + textPreview: '文本预览', + copyText: '复制文本', + copyCode: '复制取件码', + copyLink: '复制取件链接', + copySuccess: '文本已复制到剪贴板', + copyCodeSuccess: '取件码已复制到剪贴板', + copyLinkSuccess: '取件链接已复制到剪贴板', + copyFailed: '复制失败,请重试', + charCount: '共 {count} 个字符', + downloadFile: '下载文件', + exportText: '导出文本', + downloadSuccess: '已下载:{name}', + exportSuccess: '已导出:{name}', + downloadFailed: '下载失败', + previewFailed: '预览加载失败', + loadingPreview: '正在加载预览...', + previewComplete: '已加载完整内容,共 {count} 个字符', + previewTruncated: '已显示 {shown} / {total} 个字符', + previewFallback: '预览接口不可用,已使用列表中的文本内容', + selectCurrentPage: '选择当前页', + selectedCount: '已选择 {count} 项', + mobileBatchActions: '移动端批量操作', + policyActionsLabel: '策略', + selectFile: '选择 {name}', + clearSelection: '清空选择', + batchDelete: '批量删除', + batchDeleteConfirm: '确认删除选中的 {count} 个文件?此操作不可撤销。', + batchDeleteSuccess: '已删除 {count} 个文件', + batchDeletePartialSuccess: '已删除 {count} 个文件,{failed} 个失败', + batchDeleteFailed: '批量删除失败', + batchEdit: '批量编辑', + batchEditTitle: '批量编辑文件策略', + batchEditSelected: '将更新选中的 {count} 个文件', + batchEditMode: '更新方式', + batchEditExpiresAt: '设置过期时间', + batchEditRelativeExpire: '设为一段时间后消失', + batchEditRelativeExpireValue: '消失时间', + batchEditRelativeExpirePlaceholder: '输入数量', + batchEditRelativeExpireUnit: '单位', + batchEditRelativeExpireHours: '小时', + batchEditRelativeExpireDays: '天', + batchEditDownloadLimit: '设置取件次数', + batchEditForever: '设为永久有效', + batchEditForeverHint: '清空过期时间,并将取件次数设为不限。', + batchUpdateConfirm: '确认更新选中的 {count} 个文件?', + batchUpdateSuccess: '已更新 {count} 个文件', + batchUpdatePartialSuccess: '已更新 {count} 个文件,{failed} 个失败', + batchUpdateFailed: '批量更新失败', + batchUpdateNoFields: '请选择要更新的策略', + batchPolicyActionConfirm: '确认对选中的 {count} 个文件执行“{action}”?', + batchPolicyActionSuccess: '已处理 {count} 个文件', + batchPolicyActionPartialSuccess: '已处理 {count} 个文件,{failed} 个失败', + batchPolicyActionFailed: '批量策略动作执行失败', + policyActionSuccess: '文件策略已更新', + policyActionFailed: '策略动作执行失败', + metadataInfo: '运营备注', + metadataHint: '仅管理员可见,用于记录处理线索、归档标签和后续动作。', + metadataNote: '备注', + metadataNotePlaceholder: '记录这个分享的背景、处理记录或负责人...', + metadataTags: '标签', + metadataTagsPlaceholder: '逗号分隔,例如:客户A, 待续期, 重要', + metadataUpdatedAt: '最近保存:{time}', + metadataNeverUpdated: '尚未保存备注', + saveMetadata: '保存备注', + metadataSaveSuccess: '备注和标签已保存', + metadataSaveFailed: '备注保存失败', + policyActions: { + extend24h: '延长 24 小时', + extend7d: '延长 7 天', + makePermanent: '设为永久', + resetDownloadLimit: '重置为 {count} 次' + }, + policyActionDescriptions: { + extend24h: '从当前有效期继续追加一天', + extend7d: '适合临时续期一周', + makePermanent: '清空过期时间和次数限制', + resetDownloadLimit: '恢复可取件次数到 {count} 次' + }, + applyBatchEdit: '应用更改', + overview: '概览', + policyInfo: '策略信息', + storageInfo: '存储信息', + statusInsight: '状态洞察', + nextAction: '建议动作', + lifecycle: '生命周期', + expandLifecycle: '展开全部生命周期记录(共 {count} 条)', + collapseLifecycle: '收起生命周期记录', + expandRetrievalHistory: '展开全部取件记录(共 {count} 次)', + collapseRetrievalHistory: '收起取件记录', + permanent: '永久有效', + createdAt: '创建时间', + remainingDownloads: '剩余次数', + textLength: '文本长度', + hasDownloadLimit: '限制取件次数', + hasExpirationTime: '限制过期时间', + canPreviewText: '可预览文本', + canDownload: '可下载', + storageBackend: '存储后端', + fileHash: '文件哈希', + isChunked: '分片上传', + filePath: '存储路径', + uuidFileName: '存储文件名', + uploadId: '上传会话', + yes: '是', + no: '否', + insightSeverity: { + success: '正常', + warning: '需关注', + danger: '异常', + info: '提示', + neutral: '待观察' + }, + insightStates: { + available: '当前可正常取件', + expired: '当前已不可取件', + storage_incomplete: '存储信息不完整', + expiring_soon: '即将过期', + permanent: '永久有效' + }, + insightActions: { + monitor: '无需处理', + extend_or_delete: '建议延长或清理', + inspect_storage: '检查存储信息', + extend_expiration: '建议延长有效期' + }, + insightReasons: { + expired: '已超过过期时间', + download_limit_exhausted: '取件次数已用尽', + expires_soon: '24 小时内过期', + never_retrieved: '尚未被取件', + storage_metadata_incomplete: '缺少可下载存储信息', + chunked_upload: '由分片上传生成' + }, + timeline: { + status: { + done: '已完成', + pending: '等待中', + active: '生效中', + expired: '已过期', + exhausted: '已用尽', + unlimited: '不限' + }, + created: { + title: '记录创建', + description: '分享记录已创建,当前状态为 {status}。' + }, + content_ready: { + title: '内容就绪', + description: '内容类型为 {detail},当前状态为 {status}。' + }, + upload_session: { + title: '上传会话', + description: '上传会话已记录:{detail}。' + }, + expiration_policy: { + title: '过期策略', + description: '过期策略当前为 {status}。', + remaining: '还剩 {time}', + overdue: '已超时 {time}' + }, + download_limit: { + title: '取件次数', + description: '取件次数策略当前为 {status},{value}。' + }, + retrieved: { + title: '取件记录', + description: '累计取件 {value},当前状态为 {status}。' + }, + retrieved_event: { + title: '第 {value} 次取件', + description: '本次取件已完成,当前状态为 {status}。' + }, + retrieved_event_unknown: { + title: '取件记录', + description: '本次取件已完成,当前状态为 {status}。' + } + }, + headers: { + select: '选择', + code: '取件码', + name: '名称', + type: '类型', + size: '大小', + usage: '取件', + status: '状态', + description: '描述', + expiration: '过期时间', + actions: '操作' + }, + sort: { + createdAt: '创建时间', + expiredAt: '过期时间', + name: '名称', + size: '大小', + usedCount: '取件次数', + code: '取件码', + desc: '降序', + asc: '升序' + }, + form: { + code: '取件码', + codePlaceholder: '输入取件码', + filename: '文件名称', + filenamePlaceholder: '输入文件名称', + suffix: '文件后缀', + suffixPlaceholder: '输入文件后缀', + downloadLimit: '下载次数限制', + downloadLimitPlaceholder: '输入下载次数限制' + } + }, + + // 文件记录 + fileRecord: { + filename: '文件名', + size: '文件大小', + date: '取件日期', + code: '取件码', + actions: '操作', + download: '下载', + viewDetails: '查看详情', + deleteRecord: '删除记录', + deleteRecordConfirm: '确认删除这条本地记录?此操作不会删除服务器上的文件。', + preview: '预览', + copyContent: '复制内容', + contentCopied: '内容已复制到剪贴板', + copyFailed: '复制失败,请重试' + }, + + // 文件详情模态框 + fileDetail: { + title: '文件详情', + content: '文件内容', + previewContent: '预览内容', + download: '点击下载', + qrCode: '取件二维码', + scanQrCode: '扫描二维码快速取件' + }, + + // 内容预览 + contentPreview: { + title: '内容预览' + }, + + // 侧边抽屉 + drawer: { + noRecords: '暂无记录' + }, + + // 文件大小单位 + fileSize: { + bytes: 'Bytes', + kb: 'KB', + mb: 'MB', + gb: 'GB', + tb: 'TB' + }, + + // 管理页面 + manage: { + settings: { + title: '系统设置', + basicSettings: '基本设置', + siteName: '网站名称', + adminPassword: '管理员密码', + passwordPlaceholder: '如需修改请输入新密码', + passwordNote: '不修改请留空', + keywords: 'SEO 关键词', + themeSelection: '界面主题', + robotsFile: 'Robots.txt 配置', + notificationSettings: '通知设置', + notificationTitle: '公告标题', + notificationContent: '公告内容', + storageSettings: '存储配置', + storagePath: '文件存储路径', + storagePathPlaceholder: '使用默认路径可留空', + storageMethod: '存储方式', + localStorage: '本地存储', + s3Storage: 'S3 对象存储', + webdavStorage: 'WebDAV 存储', + chunkUploadNote: '分片上传(实验性功能,大文件上传更稳定)', + uploadLimits: '上传设置', + uploadPerMinute: '限流时间窗口(在此时间内限制上传次数)', + uploadCountLimit: '允许上传文件数(限流窗口内最多上传几个文件)', + fileSizeLimit: '单文件大小上限', + expiration: { + day: '按天数', + hour: '按小时', + minute: '按分钟', + forever: '永久有效', + count: '按下载次数' + }, + maxSaveTime: '文件最长保存时间', + trashRetentionDays: '回收站默认保留期', + trashRetentionDaysNote: '修改后会重新计算当前回收站中有期限文件的清理时间;已设为永久或已清理的文件不受影响。', + s3AccessKeyId: 'Access Key ID', + s3SecretAccessKey: 'Secret Access Key', + s3BucketName: '存储桶名称', + s3EndpointUrl: '服务端点 URL', + s3RegionName: '区域名称', + s3SignatureVersion: '签名版本', + s3Hostname: '自定义域名', + s3v2: 'S3v2', + s3v4: 'S3v4', + autoPlaceholder: '自动识别', + enableProxy: '启用下载代理', + webdavUrlPlaceholder: '输入 WebDAV 服务地址', + webdavUsernamePlaceholder: '输入 WebDAV 用户名', + webdavPasswordPlaceholder: '输入 WebDAV 密码', + fileSizeUnits: { + kb: 'KB', + mb: 'MB', + gb: 'GB' + }, + expirationType: '过期方式', + guestUpload: '允许游客上传', + errorLimits: '访问保护', + errorPerMinute: '检测时间窗口(在此时间内统计错误次数)', + errorCountLimit: '允许错误次数(超过后临时封禁)', + saveChanges: '保存设置', + refreshConfig: '刷新配置', + refreshing: '刷新中', + saving: '保存中', + unsavedChanges: '有未保存修改', + allChangesSaved: '已保存', + refreshBlocked: '请先保存当前变更再刷新' + ,sectionNavigation: '设置分区导航' + ,reloadSaved: '重新加载已保存配置' + ,discardChanges: '放弃修改' + ,discardChangesConfirm: '确认放弃当前未保存的修改并重新加载已保存配置?' + ,robotsWarning: '如果包含 Disallow: /,搜索引擎将无法抓取整个站点。' + ,fileSizeUnit: '文件大小单位' + ,timeUnit: '时间单位' + }, + dashboard: { + title: '仪表盘', + totalFiles: '总文件数', + storageSpace: '存储空间', + todayShares: '今日分享', + totalRetrievals: '累计取件', + activeFiles: '有效文件:{count}', + todayIncrease: '今日新增容量:{count}', + yesterdayShares: '昨日分享:{count}', + serverUptime: '运行时间', + refresh: '刷新数据', + fileHealth: '文件健康', + fileHealthDesc: '基于状态洞察统计可取件、风险与待处理队列。', + activeFileRatio: '有效占比', + fileShareRatio: '文件占比', + textShareRatio: '文本占比', + binaryFiles: '文件分享 {count} 个', + textShares: '文本分享 {count} 条', + expiredFiles: '已过期文件', + needCleanup: '可在文件管理中清理', + chunkedFiles: '分片上传文件', + storagePolicy: '存储与上传策略', + storagePolicyDesc: '当前后台配置对上传链路的影响。', + storageBackend: '存储后端', + singleFileLimit: '单文件上限', + guestUpload: '游客上传', + maxSaveTime: '最长保存', + noSaveLimit: '不限制', + todayCapacityReference: '今日容量 / 单文件上限' + }, + fileManage: { + title: '文件管理', + searchPlaceholder: '搜索文件名称、描述...', + allFiles: '所有文件', + editFileInfo: '编辑文件信息', + saveChanges: '保存更改', + headers: { + code: '取件码', + name: '名称', + size: '大小', + description: '描述', + expiration: '过期时间', + actions: '操作' + }, + form: { + code: '取件码', + codePlaceholder: '输入取件码', + filename: '文件名称', + filenamePlaceholder: '输入文件名称', + suffix: '文件后缀', + suffixPlaceholder: '输入文件后缀', + downloadLimit: '下载次数限制', + downloadLimitPlaceholder: '输入下载次数限制' + }, + updateFailed: '更新失败', + deleteFailed: '删除失败', + deleteConfirm: '确认删除这个文件?此操作不可撤销。', + loadFileListFailed: '加载文件列表失败' + }, + systemSettings: { + title: '系统设置', + basicSettings: '基本设置', + websiteInfo: '网站基本信息', + websiteName: '网站名称', + websiteDescription: '网站描述', + adminPassword: '管理员密码', + passwordPlaceholder: '如需修改请输入新密码', + passwordNote: '不修改请留空', + keywords: 'SEO 关键词', + themeSelection: '界面主题', + notificationSettings: '通知设置', + notificationTitle: '公告标题', + notificationContent: '公告内容', + storageSettings: '存储配置', + storagePath: '文件存储路径', + storagePathPlaceholder: '使用默认路径可留空', + storageMethod: '存储方式', + localStorage: '本地存储', + s3Storage: 'S3 对象存储', + webdavStorage: 'WebDAV 存储', + chunkUploadNote: '分片上传(实验性功能,大文件上传更稳定)', + enabled: '已启用', + disabled: '已禁用', + webdavUrl: '输入 WebDAV 服务地址', + webdavUsername: '输入 WebDAV 用户名', + webdavPassword: '输入 WebDAV 密码', + enableProxy: '启用下载代理', + uploadLimits: '上传设置', + uploadRateLimit: '限流时间窗口(在此时间内限制上传次数)', + minute: '分钟', + uploadCountLimit: '允许上传文件数(限流窗口内最多上传几个文件)', + files: '个文件', + fileSizeLimit: '单文件大小上限', + expirationMethod: '过期方式', + expirationMethods: { + day: '按天数', + hour: '按小时', + minute: '按分钟', + forever: '永久有效', + count: '按下载次数' + }, + expiration: { + day: '按天数', + hour: '按小时', + minute: '按分钟', + forever: '永久有效', + count: '按下载次数' + }, + maxSaveTime: '文件最长保存时间', + trashRetentionDays: '回收站默认保留期', + trashRetentionDaysNote: '修改后会重新计算当前回收站中有期限文件的清理时间;已设为永久或已清理的文件不受影响。', + timeUnits: { + second: '秒', + minute: '分钟', + hour: '小时', + day: '天' + }, + guestUpload: '允许游客上传', + errorLimits: '访问保护', + errorRateLimit: '检测时间窗口(在此时间内统计错误次数)', + errorCountLimit: '允许错误次数(超过后临时封禁)', + times: '次', + saveSettings: '保存设置', + saveSuccess: '设置已保存', + saveFailed: '保存失败,请重试', + getConfigFailed: '获取配置失败,请刷新页面' + }, + login: { + title: '登录', + password: '密码', + passwordPlaceholder: '密码', + loginButton: '登录', + loggingIn: '登录中...', + invalidPassword: '无效的密码', + passwordTooShort: '密码长度至少为6位', + loginFailed: '登录失败', + noValidToken: '登录失败:未获取到有效令牌' + } + }, + + // 工具函数相关 + utils: { + common: { + formatTime: '格式化时间戳为可读格式', + formatFileSize: '格式化文件大小', + formatDuration: '格式化持续时间', + time: { + forever: '永久', + day: '天', + hour: '小时', + minute: '分钟', + second: '秒' + }, + copyToClipboard: '复制文本到剪贴板', + copyFailed: '复制失败:', + debounce: '防抖函数', + throttle: '节流函数', + validateEmail: '验证邮箱格式', + validateUrl: '验证URL格式', + generateRandomString: '生成随机字符串', + deepClone: '深度克隆对象', + getFileExtension: '获取文件扩展名', + isMobileDevice: '检查是否为移动设备', + formatNumber: '格式化数字,添加千分位分隔符' + }, + clipboard: { + title: '剪贴板工具函数', + copyText: '复制文本到剪贴板', + copySuccess: '复制成功', + copyFailed: '复制失败,请手动复制' + } + }, + + // 组件相关 + components: { + pagination: { + navigation: '分页导航', + range: '显示第 {start} 到 {end} 条,共 {total} 条', + pageSize: '每页显示数量', + perPage: '{size}/页', + goToPage: '前往第 {page} 页', + showing: '显示第', + to: '到', + of: '条,共', + total: '条', + previous: '上一页', + next: '下一页' + }, + languageSwitcher: { + clickOutsideToClose: '点击外部关闭下拉菜单' + }, + borderProgressBar: { + borderWidth: '边框宽度', + cornerRadius: '拐角半径', + createGradient: '创建渐变', + drawBackground: '绘制背景', + calculateProgress: '计算进度', + drawProgress: '绘制进度' + } + }, + + // 其他通用文本 + misc: { + emptyFileError: '无法读取空文件', + fileAddedFromClipboard: '已从剪贴板添加文件:', + fileProcessFailed: '文件处理失败', + chunkSize: '保持 2MB 的切片大小用于计算哈希', + secureContext: '如果不是安全上下文(HTTP),则返回一个基于文件信息的替代哈希', + cryptoFallback: '如果 crypto.subtle.digest 失败,使用替代方案', + generateAlternativeHash: '生成替代哈希的函数', + fileInfoHash: '使用文件名、大小和最后修改时间生成一个简单的哈希', + convertToHex: '转换为16进制字符串并填充到64位', + defaultChunkSize: '默认切片大小为5MB', + initChunkUpload: '1. 初始化切片上传', + uploadChunk: '2. 上传切片', + completeUpload: '3. 完成上传', + chunkUploadFailed: '切片上传失败:', + uploadProgressListener: '添加上传进度监听', + noLimitCheck: '如果没有限制,直接返回true', + expirationValidation: '添加过期时间验证', + chunkUploadReplacement: '使用切片上传替代原来的直接上传', + textUploadUnchanged: '文本上传保持不变', + addSendRecord: '添加新的发送记录', + permanent: '永久', + sendSuccessMessage: '显示发送成功消息', + resetForm: '重置表单 - 只重置文件和文本内容,保留过期信息', + showDetails: '显示详情', + autoCopyLink: '自动复制取件码链接', + delayedLoading: '使用 onMounted 钩子延迟加载一些非关键资源或初始化', + nonCriticalInit: '这里可以放置一些非立即需要的初始化代码' + } +} diff --git a/src/layout/AdminLayout/AdminLayout 2.vue b/src/layout/AdminLayout/AdminLayout 2.vue new file mode 100644 index 0000000..fbef430 --- /dev/null +++ b/src/layout/AdminLayout/AdminLayout 2.vue @@ -0,0 +1,353 @@ + + + + + diff --git a/src/main 2.ts b/src/main 2.ts new file mode 100644 index 0000000..ad9dbcd --- /dev/null +++ b/src/main 2.ts @@ -0,0 +1,18 @@ +import './assets/style/main.css' + +import { createApp } from 'vue' +import { createPinia } from 'pinia' + +import App from './App.vue' +import router from './router' +import i18n from './i18n' + +document.documentElement.lang = i18n.global.locale.value + +const app = createApp(App) + +app.use(createPinia()) +app.use(router) +app.use(i18n) + +app.mount('#app') diff --git a/src/router/index 2.ts b/src/router/index 2.ts new file mode 100644 index 0000000..d40215a --- /dev/null +++ b/src/router/index 2.ts @@ -0,0 +1,123 @@ +import { createRouter, createWebHashHistory } from 'vue-router' +import type { RouteRecordRaw } from 'vue-router' +import { ROUTE_NAMES, ROUTES } from '@/constants' +import { readStoredToken } from '@/utils/auth-storage' + +const publicPageMeta = { + showGlobalControls: true, + showRouteLoading: false, + routeTransition: 'transfer-fade' +} + +const adminPageMeta = { + requiresAuth: true, + showGlobalControls: false, + showRouteLoading: false +} + +const routes: RouteRecordRaw[] = [ + { + path: '/', + name: ROUTE_NAMES.RETRIEVE, + component: () => import('@/views/RetrievewFileView.vue'), + meta: { + ...publicPageMeta, + title: 'retrieve' + } + }, + { + path: ROUTES.SEND, + name: ROUTE_NAMES.SEND, + component: () => import('@/views/SendFileView.vue'), + meta: { + ...publicPageMeta, + title: 'send' + } + }, + { + path: ROUTES.ADMIN, + name: ROUTE_NAMES.ADMIN, + component: () => import('@/layout/AdminLayout/AdminLayout.vue'), + redirect: ROUTES.DASHBOARD, + meta: adminPageMeta, + children: [ + { + path: 'dashboard', + name: ROUTE_NAMES.DASHBOARD, + component: () => import('@/views/manage/DashboardView.vue'), + meta: { + ...adminPageMeta, + title: 'dashboard' + } + }, + { + path: 'files', + name: ROUTE_NAMES.FILE_MANAGE, + component: () => import('@/views/manage/FileManageView.vue'), + meta: { + ...adminPageMeta, + title: 'files' + } + }, + { + path: 'trash', + name: ROUTE_NAMES.TRASH, + component: () => import('@/views/manage/TrashView.vue'), + meta: { + ...adminPageMeta, + title: 'trash' + } + }, + { + path: 'activities', + name: ROUTE_NAMES.ACTIVITY_LOG, + component: () => import('@/views/manage/ActivityLogView.vue'), + meta: { + ...adminPageMeta, + title: 'activities' + } + }, + { + path: 'settings', + name: ROUTE_NAMES.SETTINGS, + component: () => import('@/views/manage/SystemSettingsView.vue'), + meta: { + ...adminPageMeta, + title: 'settings' + } + } + ] + }, + { + path: ROUTES.LOGIN, + name: ROUTE_NAMES.LOGIN, + component: () => import('@/views/manage/LoginView.vue'), + meta: { + showGlobalControls: true, + showRouteLoading: true, + title: 'login' + } + }, + { + path: '/:pathMatch(.*)*', + redirect: ROUTES.HOME + } +] + +const router = createRouter({ + history: createWebHashHistory(import.meta.env.BASE_URL), + routes +}) + +router.beforeEach((to) => { + if (to.meta.requiresAuth && !readStoredToken()) { + return { + path: ROUTES.LOGIN, + query: { + redirect: to.fullPath + } + } + } +}) + +export default router diff --git a/src/services/activity 2.ts b/src/services/activity 2.ts new file mode 100644 index 0000000..652e251 --- /dev/null +++ b/src/services/activity 2.ts @@ -0,0 +1,10 @@ +import api from './client' +import type { AdminActivityListParams, AdminActivityListResponse, ApiResponse } from '@/types' + +export class ActivityService { + static async getAdminActivities( + params: AdminActivityListParams + ): Promise> { + return api.get('/admin/activities', { params }) + } +} diff --git a/src/services/auth 2.ts b/src/services/auth 2.ts new file mode 100644 index 0000000..47fb448 --- /dev/null +++ b/src/services/auth 2.ts @@ -0,0 +1,16 @@ +import api from './client' +import type { AdminUser, ApiResponse } from '@/types' + +export class AuthService { + static async login(password: string): Promise> { + return api.post('/admin/login', { password }) + } + + static async logout(): Promise { + return api.post('/admin/logout') + } + + static async verifyToken(): Promise> { + return api.get('/admin/verify') + } +} diff --git a/src/services/client 2.ts b/src/services/client 2.ts new file mode 100644 index 0000000..4a39bfa --- /dev/null +++ b/src/services/client 2.ts @@ -0,0 +1,61 @@ +import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios' +import { API_STATUS_CODES, TIME_CONSTANTS } from '@/constants' +import type { ApiErrorPayload } from '@/types' +import { clearStoredToken, readStoredToken } from '@/utils/auth-storage' + +export const AUTH_EVENTS = { + UNAUTHORIZED: 'filecodebox:auth:unauthorized' +} as const + +const rawBaseURL = + import.meta.env.MODE === 'production' + ? import.meta.env.VITE_API_BASE_URL_PROD + : import.meta.env.VITE_API_BASE_URL_DEV + +export const apiBaseURL = typeof rawBaseURL === 'string' ? rawBaseURL.replace(/\/+$/, '') : '' + +const clientOptions = { + baseURL: apiBaseURL, + timeout: TIME_CONSTANTS.REQUEST_TIMEOUT, + headers: { + 'Content-Type': 'application/json' + } +} + +const apiClient = axios.create(clientOptions) +export const rawApiClient = axios.create(clientOptions) + +const attachAuthToken = (config: InternalAxiosRequestConfig) => { + const token = readStoredToken() + if (token) { + config.headers.Authorization = `Bearer ${token}` + } + return config +} + +const handleAuthError = (error: AxiosError) => { + if (error.response?.status === API_STATUS_CODES.UNAUTHORIZED) { + clearStoredToken() + window.dispatchEvent(new CustomEvent(AUTH_EVENTS.UNAUTHORIZED)) + } + return Promise.reject(error) +} + +apiClient.interceptors.request.use( + attachAuthToken, + (error) => Promise.reject(error) +) + +rawApiClient.interceptors.request.use( + attachAuthToken, + (error) => Promise.reject(error) +) + +apiClient.interceptors.response.use( + (response) => response.data, + handleAuthError +) + +rawApiClient.interceptors.response.use((response) => response, handleAuthError) + +export default apiClient diff --git a/src/services/config 2.ts b/src/services/config 2.ts new file mode 100644 index 0000000..4a48b6a --- /dev/null +++ b/src/services/config 2.ts @@ -0,0 +1,52 @@ +import api from './client' +import type { ApiResponse, ConfigState, PublicConfigPayload } from '@/types' + +const isPublicConfigEnvelope = ( + detail: ConfigState | PublicConfigPayload | null | undefined +): detail is PublicConfigPayload => { + return !!detail && typeof detail === 'object' && 'config' in detail +} + +const normalizeUserConfigResponse = ( + response: ApiResponse +): ApiResponse => { + if (isPublicConfigEnvelope(response.detail)) { + return { + ...response, + detail: { + config: response.detail.config, + meta: response.detail.meta + } + } + } + + return { + ...response, + detail: { + config: response.detail ?? {} + } + } +} + +export class ConfigService { + static async getConfig(): Promise> { + return api.get('/admin/config/get') + } + + static async getUserConfig(): Promise> { + try { + const response = (await api.get('/api/v1/config')) as ApiResponse< + ConfigState | PublicConfigPayload + > + + return normalizeUserConfigResponse(response) + } catch { + const response = (await api.post('/')) as ApiResponse + return normalizeUserConfigResponse(response) + } + } + + static async updateConfig(config: Partial): Promise { + return api.patch('/admin/config/update', config) + } +} diff --git a/src/services/file 2.ts b/src/services/file 2.ts new file mode 100644 index 0000000..b1eef53 --- /dev/null +++ b/src/services/file 2.ts @@ -0,0 +1,272 @@ +import api, { rawApiClient } from './client' +import { multipartUploadConfig } from './shared' +import type { + AdminBatchDeleteFilesResponse, + AdminBatchPolicyActionRequest, + AdminBatchPolicyActionResponse, + AdminBatchUpdateFilesRequest, + AdminBatchUpdateFilesResponse, + AdminFilePatchPayload, + AdminFileDetailResponse, + AdminFileListParams, + AdminFileMetadataRequest, + AdminFilePolicyActionRequest, + AdminFilePreviewResponse, + AdminFileViewPreset, + AdminFileViewPresetRequest, + AdminFileViewPresetsResponse, + ApiResponse, + ChunkUploadCompleteRequest, + ChunkUploadInitRequest, + ChunkUploadInitResponse, + ChunkUploadResponse, + FileEditForm, + FileInfo, + FileListResponse, + FileUploadResponse, + ShareMetadataResponse, + ShareSelectResponse, + TextSendResponse, + UploadProgress +} from '@/types' + +const urlEncodedConfig = { + headers: { + 'Content-Type': 'application/x-www-form-urlencoded' + } +} + +const toUrlEncodedForm = (data: Record) => { + const form = new URLSearchParams() + Object.entries(data).forEach(([key, value]) => { + form.append(key, String(value)) + }) + return form +} + +const isMethodFallbackError = (error: unknown) => { + const status = (error as { response?: { status?: number } })?.response?.status + return status === 404 || status === 405 +} + +export class FileService { + static async uploadFile( + file: File, + onProgress?: (progress: UploadProgress) => void + ): Promise> { + const formData = new FormData() + formData.append('file', file) + + return api.post('/share/file/', formData, multipartUploadConfig(onProgress)) + } + + static async uploadText( + text: string, + expireValue = 1, + expireStyle = 'day' + ): Promise> { + const formData = new FormData() + formData.append('text', text) + formData.append('expire_value', String(expireValue)) + formData.append('expire_style', expireStyle) + return api.post('/share/text/', formData, multipartUploadConfig()) + } + + static async initChunkUpload( + request: ChunkUploadInitRequest + ): Promise> { + return api.post( + '/chunk/upload/init/', + toUrlEncodedForm({ + file_name: request.file_name, + file_size: request.file_size, + chunk_size: request.chunk_size, + file_hash: request.file_hash + }), + urlEncodedConfig + ) + } + + static async uploadChunk( + uploadId: string, + chunkIndex: number, + chunk: Blob, + onProgress?: (progress: UploadProgress) => void + ): Promise> { + const formData = new FormData() + formData.append('chunk', chunk) + return api.post( + `/chunk/upload/chunk/${uploadId}/${chunkIndex}`, + formData, + multipartUploadConfig(onProgress) + ) + } + + static async completeChunkUpload( + uploadId: string, + request: ChunkUploadCompleteRequest + ): Promise> { + return api.post( + `/chunk/upload/complete/${uploadId}`, + toUrlEncodedForm({ + expire_value: request.expire_value, + expire_style: request.expire_style + }), + urlEncodedConfig + ) + } + + static async selectFile(code: string): Promise> { + return api.post('/share/select/', { code }) + } + + static async inspectFile(code: string): Promise> { + return api.post('/share/metadata/', { code }) + } + + static async getFile(code: string): Promise> { + return api.get(`/file/${code}`) + } + + static async downloadFile(code: string): Promise { + const response = await rawApiClient.get(`/download/${code}`, { + responseType: 'blob' + }) + return response.data + } + + static async getAdminFileList( + params: AdminFileListParams + ): Promise> { + return api.get('/admin/file/list', { params }) + } + + static async getAdminFileDetail(id: number): Promise> { + return api.get('/admin/file/detail', { + params: { id } + }) + } + + static async updateFile(data: FileEditForm | AdminFilePatchPayload): Promise { + return api.patch('/admin/file/update', data) + } + + static async applyAdminFilePolicyAction( + data: AdminFilePolicyActionRequest + ): Promise> { + try { + return await api.patch('/admin/file/policy-action', data) + } catch (error: unknown) { + if (!isMethodFallbackError(error)) { + throw error + } + + return api.post('/admin/file/policy-action', data) + } + } + + static async applyAdminFilesPolicyAction( + data: AdminBatchPolicyActionRequest + ): Promise> { + try { + return await api.patch('/admin/file/batch-policy-action', data) + } catch (error: unknown) { + if (!isMethodFallbackError(error)) { + throw error + } + + return api.post('/admin/file/batch-policy-action', data) + } + } + + static async updateAdminFileMetadata( + data: AdminFileMetadataRequest + ): Promise> { + try { + return await api.patch('/admin/file/metadata', data) + } catch (error: unknown) { + if (!isMethodFallbackError(error)) { + throw error + } + + return api.post('/admin/file/metadata', data) + } + } + + static async getAdminFileViewPresets(): Promise> { + return api.get('/admin/file/view-presets') + } + + static async saveAdminFileViewPreset( + data: AdminFileViewPresetRequest + ): Promise> { + try { + return await api.patch('/admin/file/view-presets', data) + } catch (error: unknown) { + if (!isMethodFallbackError(error)) { + throw error + } + + return api.post('/admin/file/view-presets', data) + } + } + + static async updateAdminFiles( + data: AdminBatchUpdateFilesRequest + ): Promise> { + return api.patch('/admin/file/batch-update', data) + } + + static async deleteAdminFile(id: number): Promise { + return api.delete('/admin/file/delete', { + data: { id } + }) + } + + static async deleteAdminFiles( + ids: number[] + ): Promise> { + return api.delete('/admin/file/batch-delete', { + data: { ids } + }) + } + + static async deleteAdminFileViewPreset(id: string): Promise { + try { + return await api.delete('/admin/file/view-presets', { + data: { id } + }) + } catch (error: unknown) { + if (!isMethodFallbackError(error)) { + throw error + } + + return api.post('/admin/file/view-presets/delete', { id }) + } + } + + static async downloadAdminFile( + id: number + ): Promise<{ data: Blob; headers: Record }> { + const response = await rawApiClient.get('/admin/file/download', { + params: { id }, + responseType: 'blob' + }) + return { + data: response.data, + headers: response.headers as Record + } + } + + static async previewAdminFile( + id: number, + maxChars = 20000 + ): Promise> { + return api.get('/admin/file/preview', { + params: { + id, + maxChars + } + }) + } +} diff --git a/src/services/index 2.ts b/src/services/index 2.ts new file mode 100644 index 0000000..2d2dbdc --- /dev/null +++ b/src/services/index 2.ts @@ -0,0 +1,9 @@ +export { AUTH_EVENTS } from './client' +export { ActivityService } from './activity' +export { AuthService } from './auth' +export { ConfigService } from './config' +export { FileService } from './file' +export { PresignUploadService } from './presign-upload' +export { StatsService } from './stats' +export { TrashService } from './trash' +export { uploadChunkedFile } from './upload-strategy' diff --git a/src/services/presign-upload 2.ts b/src/services/presign-upload 2.ts new file mode 100644 index 0000000..47c6684 --- /dev/null +++ b/src/services/presign-upload 2.ts @@ -0,0 +1,58 @@ +import api from './client' +import { multipartUploadConfig } from './shared' +import { uploadToExternalUrl } from './upload-client' +import type { + ApiResponse, + PresignConfirmRequest, + PresignInitRequest, + PresignInitResponse, + PresignStatusResponse, + PresignUploadResult, + UploadProgress +} from '@/types' + +export class PresignUploadService { + static async initUpload(request: PresignInitRequest): Promise> { + return api.post('/presign/upload/init', request) + } + + static async proxyUpload( + uploadId: string, + file: File, + onProgress?: (progress: UploadProgress) => void, + uploadUrl?: string + ): Promise> { + const formData = new FormData() + formData.append('file', file) + + return api.put( + uploadUrl || `/presign/upload/proxy/${uploadId}`, + formData, + multipartUploadConfig(onProgress) + ) + } + + static async confirmUpload( + uploadId: string, + request?: PresignConfirmRequest + ): Promise> { + return api.post(`/presign/upload/confirm/${uploadId}`, request || {}) + } + + static async getUploadStatus(uploadId: string): Promise> { + return api.get(`/presign/upload/status/${uploadId}`) + } + + static async cancelUpload(uploadId: string): Promise> { + return api.delete(`/presign/upload/${uploadId}`) + } + + static async directUploadToS3( + uploadUrl: string, + file: File, + onProgress?: (progress: UploadProgress) => void + ): Promise { + await uploadToExternalUrl(uploadUrl, file, onProgress) + return true + } +} diff --git a/src/services/shared 2.ts b/src/services/shared 2.ts new file mode 100644 index 0000000..58c5535 --- /dev/null +++ b/src/services/shared 2.ts @@ -0,0 +1,20 @@ +import type { AxiosRequestConfig } from 'axios' +import type { UploadProgress } from '@/types' + +export const multipartUploadConfig = ( + onProgress?: (progress: UploadProgress) => void +): AxiosRequestConfig => ({ + headers: { + 'Content-Type': 'multipart/form-data' + }, + timeout: 0, + onUploadProgress: (progressEvent) => { + if (onProgress && progressEvent.total) { + onProgress({ + loaded: progressEvent.loaded, + total: progressEvent.total, + percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total) + }) + } + } +}) diff --git a/src/services/stats 2.ts b/src/services/stats 2.ts new file mode 100644 index 0000000..6d32cc2 --- /dev/null +++ b/src/services/stats 2.ts @@ -0,0 +1,17 @@ +import api from './client' +import type { AnalyticsData, ApiResponse, DashboardData } from '@/types' + +export class StatsService { + static async getDashboard(): Promise> { + return api.get('/admin/dashboard') + } + + static async getAnalytics(start?: string, end?: string): Promise> { + return api.get('/admin/analytics', { + params: { + start, + end + } + }) + } +} diff --git a/src/services/trash 2.ts b/src/services/trash 2.ts new file mode 100644 index 0000000..61ad133 --- /dev/null +++ b/src/services/trash 2.ts @@ -0,0 +1,20 @@ +import api from './client' +import type { ApiResponse, TrashListParams, TrashListResponse } from '@/types' + +export class TrashService { + static async list(params: TrashListParams): Promise> { + return api.get('/admin/trash/list', { params }) + } + + static async restore(id: number): Promise { + return api.post('/admin/trash/restore', { id }) + } + + static async purge(id: number): Promise { + return api.delete('/admin/trash/purge', { data: { id } }) + } + + static async updateRetention(id: number, retentionDays: number): Promise { + return api.post('/admin/trash/retention', { id, retentionDays }) + } +} diff --git a/src/services/upload-client 2.ts b/src/services/upload-client 2.ts new file mode 100644 index 0000000..062fe77 --- /dev/null +++ b/src/services/upload-client 2.ts @@ -0,0 +1,26 @@ +import axios from 'axios' +import type { UploadProgress } from '@/types' + +export async function uploadToExternalUrl( + uploadUrl: string, + file: File, + onProgress?: (progress: UploadProgress) => void +): Promise { + await axios.put(uploadUrl, file, { + headers: { + 'Content-Type': 'application/octet-stream' + }, + timeout: 0, + onUploadProgress: (progressEvent) => { + if (!onProgress || !progressEvent.total) { + return + } + + onProgress({ + loaded: progressEvent.loaded, + total: progressEvent.total, + percentage: Math.round((progressEvent.loaded * 100) / progressEvent.total) + }) + } + }) +} diff --git a/src/services/upload-strategy 2.ts b/src/services/upload-strategy 2.ts new file mode 100644 index 0000000..8221964 --- /dev/null +++ b/src/services/upload-strategy 2.ts @@ -0,0 +1,103 @@ +import { FileService } from './file' +import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types' +import { calculateFileHash } from '@/utils/file-processing' + +const CHUNK_SIZE = 5 * 1024 * 1024 + +type ChunkedUploadOptions = { + expireValue: number + expireStyle: string + onHashCalculated?: (hash: string) => void + onProgress?: (progress: UploadProgress) => void + messages?: { + initFailed?: string + chunkFailed?: (index: number) => string + completeFailed?: string + } + onStatus?: (status: 'initializing' | 'uploading' | 'confirming' | 'success' | 'error') => void +} + +type ChunkedUploadResult = ChunkUploadInitResponse | FileUploadResponse + +const calculateCompletedBytes = (uploadedChunks: Set, chunkSize: number, fileSize: number) => + Array.from(uploadedChunks).reduce((total, index) => { + const chunkStart = index * chunkSize + const chunkEnd = Math.min((index + 1) * chunkSize, fileSize) + return total + Math.max(0, chunkEnd - chunkStart) + }, 0) + +export const uploadChunkedFile = async ( + file: File, + options: ChunkedUploadOptions +): Promise> => { + options.onStatus?.('initializing') + const fileHash = await calculateFileHash(file) + options.onHashCalculated?.(fileHash) + + const chunks = Math.ceil(file.size / CHUNK_SIZE) + const initResponse = await FileService.initChunkUpload({ + file_name: file.name, + file_size: file.size, + chunk_size: CHUNK_SIZE, + file_hash: fileHash + }) + + if (initResponse.code !== 200) { + throw new Error(options.messages?.initFailed || 'Init chunk upload failed') + } + + if (initResponse.detail?.existed) { + return initResponse + } + + const initDetail = initResponse.detail + const uploadId = initDetail?.upload_id + if (!uploadId) { + throw new Error(options.messages?.initFailed || 'Init chunk upload failed') + } + + const uploadedChunks = new Set(initDetail.uploaded_chunks || []) + options.onStatus?.('uploading') + for (let index = 0; index < chunks; index++) { + if (uploadedChunks.has(index)) { + continue + } + + const start = index * CHUNK_SIZE + const end = Math.min(start + CHUNK_SIZE, file.size) + const chunk = file.slice(start, end) + const chunkResponse = await FileService.uploadChunk( + uploadId, + index, + new Blob([chunk], { type: file.type }), + (progress) => { + const completedBytes = calculateCompletedBytes(uploadedChunks, CHUNK_SIZE, file.size) + const percentage = Math.round(((completedBytes + progress.loaded) * 100) / file.size) + options.onProgress?.({ + loaded: completedBytes + progress.loaded, + total: file.size, + percentage: Math.min(percentage, 99) + }) + } + ) + + if (chunkResponse.code !== 200) { + throw new Error(options.messages?.chunkFailed?.(index) || `Chunk upload failed: ${index}`) + } + uploadedChunks.add(index) + } + + options.onStatus?.('confirming') + const completeResponse = await FileService.completeChunkUpload(uploadId, { + expire_value: options.expireValue, + expire_style: options.expireStyle + }) + + if (completeResponse.code !== 200) { + options.onStatus?.('error') + throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed') + } + + options.onStatus?.('success') + return completeResponse +} diff --git a/src/stores/adminStore 2.ts b/src/stores/adminStore 2.ts new file mode 100644 index 0000000..93d2bad --- /dev/null +++ b/src/stores/adminStore 2.ts @@ -0,0 +1,82 @@ +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' +import type { AdminUser } from '@/types' +import { + clearStoredAuth, + readStoredAdminPassword, + readStoredToken, + writeStoredAdminPassword, + writeStoredToken +} from '@/utils/auth-storage' + +export const useAdminStore = defineStore('admin', () => { + // 状态 + const adminPassword = ref(readStoredAdminPassword()) + const token = ref(readStoredToken()) + const isLoggedIn = ref(false) + const userInfo = ref(null) + + // 计算属性 + const isAuthenticated = computed(() => { + return isLoggedIn.value && !!token.value + }) + const hasToken = computed(() => !!token.value) + + // 方法 + const updateAdminPassword = (pwd: string) => { + adminPassword.value = pwd + writeStoredAdminPassword(pwd) + } + + const setToken = (newToken: string) => { + token.value = newToken + writeStoredToken(newToken) + } + + const setUserInfo = (user: AdminUser) => { + userInfo.value = user + isLoggedIn.value = true + setToken(user.token) + } + + const login = (user: AdminUser) => { + setUserInfo(user) + } + + const logout = () => { + adminPassword.value = '' + token.value = '' + isLoggedIn.value = false + userInfo.value = null + + clearStoredAuth() + } + + const initAuth = () => { + const storedToken = readStoredToken() + if (storedToken) { + token.value = storedToken + isLoggedIn.value = true + } + } + + return { + // 状态 + adminPassword, + token, + isLoggedIn, + userInfo, + + // 计算属性 + isAuthenticated, + hasToken, + + // 方法 + updateAdminPassword, + setToken, + setUserInfo, + login, + logout, + initAuth + } +}) diff --git a/src/stores/alertStore 2.ts b/src/stores/alertStore 2.ts new file mode 100644 index 0000000..f6d5e80 --- /dev/null +++ b/src/stores/alertStore 2.ts @@ -0,0 +1,61 @@ +import { defineStore } from 'pinia' +import type { Alert, AlertType } from '@/types' +import { TIME_CONSTANTS } from '@/constants' + +let progressTimer: ReturnType | null = null + +export const useAlertStore = defineStore('alert', { + state: () => ({ + alerts: [] as Alert[] + }), + actions: { + showAlert( + message: string, + type: AlertType = 'info', + duration = TIME_CONSTANTS.ALERT_DURATION + ) { + const id = Date.now() + const startTime = Date.now() + this.alerts.push({ id, message, type, progress: 100, duration, startTime }) + this.startProgressTimer() + setTimeout(() => this.removeAlert(id), duration) + }, + removeAlert(id: number) { + const index = this.alerts.findIndex((alert) => alert.id === id) + if (index > -1) { + this.alerts.splice(index, 1) + } + if (this.alerts.length === 0) this.stopProgressTimer() + }, + updateAlertProgress(id: number) { + const alert = this.alerts.find((a) => a.id === id) + if (alert) { + const elapsedTime = Date.now() - alert.startTime + const progress = 100 - (elapsedTime / alert.duration) * 100 + alert.progress = Math.max(0, progress) + if (alert.progress <= 0) { + this.removeAlert(id) + } + } + }, + startProgressTimer() { + if (progressTimer) { + return + } + + progressTimer = setInterval(() => { + this.alerts.forEach((alert) => { + this.updateAlertProgress(alert.id) + }) + }, TIME_CONSTANTS.PROGRESS_UPDATE_INTERVAL) + }, + stopProgressTimer() { + if (!progressTimer) { + return + } + + clearInterval(progressTimer) + progressTimer = null + } + } +}) diff --git a/src/stores/configStore 2.ts b/src/stores/configStore 2.ts new file mode 100644 index 0000000..6400f4b --- /dev/null +++ b/src/stores/configStore 2.ts @@ -0,0 +1,76 @@ +import { defineStore } from 'pinia' +import { computed, ref } from 'vue' +import type { ConfigState, PublicConfigMeta } from '@/types' +import { + DEFAULT_PUBLIC_CONFIG, + readNotifyKey, + readStoredConfig, + toPublicConfig, + writeNotifyKey, + writeStoredConfig, + type PublicConfig +} from '@/utils/config-storage' + +export const useConfigStore = defineStore('config', () => { + const config = ref({ + ...DEFAULT_PUBLIC_CONFIG, + ...toPublicConfig(readStoredConfig>()) + }) + const publicMeta = ref({}) + + const uploadSizeLimit = computed(() => config.value.uploadSize) + const appVersion = computed(() => publicMeta.value.version || '') + + const updateConfig = (nextConfig: Partial) => { + config.value = { + ...DEFAULT_PUBLIC_CONFIG, + ...config.value, + ...toPublicConfig(nextConfig) + } + writeStoredConfig(config.value) + } + + const applyRemoteConfig = (nextConfig: Partial): string | null => { + updateConfig(nextConfig) + + const { notify_title: notifyTitle, notify_content: notifyContent } = nextConfig + if (!notifyTitle || !notifyContent) { + return null + } + + const notifyKey = notifyTitle + notifyContent + if (readNotifyKey() === notifyKey) { + return null + } + + writeNotifyKey(notifyKey) + return `${notifyTitle}: ${notifyContent}` + } + + const applyPublicMeta = (nextMeta: PublicConfigMeta | undefined) => { + if (!nextMeta) return + + publicMeta.value = { + ...publicMeta.value, + ...nextMeta + } + } + + const reloadStoredConfig = () => { + config.value = { + ...DEFAULT_PUBLIC_CONFIG, + ...toPublicConfig(readStoredConfig>()) + } + } + + return { + appVersion, + config, + publicMeta, + uploadSizeLimit, + applyPublicMeta, + applyRemoteConfig, + updateConfig, + reloadStoredConfig + } +}) diff --git a/src/stores/fileData 2.ts b/src/stores/fileData 2.ts new file mode 100644 index 0000000..a4836fe --- /dev/null +++ b/src/stores/fileData 2.ts @@ -0,0 +1,55 @@ +import { defineStore } from 'pinia' +import { ref } from 'vue' +import type { ReceivedFileRecord, SentFileRecord } from '@/types' + +export const useFileDataStore = defineStore('fileData', () => { + const receiveData = ref([]) + const shareData = ref([]) + + const addReceiveData = (record: ReceivedFileRecord) => { + receiveData.value.push(record) + } + + const removeReceiveData = (id: number) => { + const index = receiveData.value.findIndex((record) => record.id === id) + if (index !== -1) { + receiveData.value.splice(index, 1) + } + } + + const deleteReceiveData = (index: number) => { + if (index >= 0 && index < receiveData.value.length) { + receiveData.value.splice(index, 1) + } + } + + const clearReceiveData = () => { + receiveData.value = [] + } + + const addShareDataRecord = (record: SentFileRecord) => { + shareData.value.push(record) + } + + const deleteShareData = (index: number) => { + if (index >= 0 && index < shareData.value.length) { + shareData.value.splice(index, 1) + } + } + + const clearShareData = () => { + shareData.value = [] + } + + return { + receiveData, + shareData, + addReceiveData, + removeReceiveData, + deleteReceiveData, + clearReceiveData, + addShareDataRecord, + deleteShareData, + clearShareData + } +}) diff --git a/src/types/activity 2.ts b/src/types/activity 2.ts new file mode 100644 index 0000000..ef0ca6a --- /dev/null +++ b/src/types/activity 2.ts @@ -0,0 +1,48 @@ +export interface AdminActivityEvent { + id: string + action: string + targetType: string + target_type?: string + targetId?: string | number | null + target_id?: string | number | null + targetName: string + target_name?: string + count: number + meta: Record + createdAt: string + created_at?: string +} + +export interface AdminActivityOption { + value: string + label: string + count: number +} + +export interface AdminActivityListResponse { + activities?: AdminActivityEvent[] + items?: AdminActivityEvent[] + page: number + size: number + total: number + storedTotal?: number + stored_total?: number + filters?: { + action?: string + targetType?: string + target_type?: string + keyword?: string + } + actionOptions?: AdminActivityOption[] + action_options?: AdminActivityOption[] + targetTypeOptions?: AdminActivityOption[] + target_type_options?: AdminActivityOption[] +} + +export interface AdminActivityListParams { + page: number + size: number + action?: string + targetType?: string + keyword?: string +} diff --git a/src/types/api 2.ts b/src/types/api 2.ts new file mode 100644 index 0000000..ebb6f43 --- /dev/null +++ b/src/types/api 2.ts @@ -0,0 +1,11 @@ +export interface ApiResponse { + code: number + message?: string + msg?: string + detail?: T +} + +export interface ApiErrorPayload { + detail?: string + message?: string +} diff --git a/src/types/auth 2.ts b/src/types/auth 2.ts new file mode 100644 index 0000000..800740b --- /dev/null +++ b/src/types/auth 2.ts @@ -0,0 +1,7 @@ +export interface AdminUser { + id: string + username: string + token: string + token_type?: string + expires_at?: number +} diff --git a/src/types/config 2.ts b/src/types/config 2.ts new file mode 100644 index 0000000..755edac --- /dev/null +++ b/src/types/config 2.ts @@ -0,0 +1,68 @@ +export interface SystemConfig { + name: string + description?: string + maxFileSize: number + allowedFileTypes: string[] + expireDays: number + notify_title?: string + notify_content?: string +} + +export interface ThemeChoice { + key: string + name: string + author: string + version: string +} + +export interface PublicConfigMeta { + version?: string + api?: Record + features?: Record + limits?: Record +} + +export interface PublicConfigPayload { + config: Partial + meta?: PublicConfigMeta +} + +export interface ConfigState { + name: string + description: string + file_storage: string + themesChoices: ThemeChoice[] + expireStyle: string[] + admin_token: string + robotsText: string + keywords: string + notify_title: string + notify_content: string + openUpload: number + uploadSize: number + storage_path: string + uploadMinute: number + max_save_seconds: number + trashRetentionDays: number + opacity: number + enableChunk: number + s3_access_key_id: string + background: string + showAdminAddr: number + page_explain: string + s3_secret_access_key: string + aws_session_token: string + s3_signature_version: string + s3_region_name: string + s3_bucket_name: string + s3_endpoint_url: string + s3_hostname: string + uploadCount: number + errorMinute: number + errorCount: number + s3_proxy: number + themesSelect: string + webdav_url: string + webdav_username: string + webdav_password: string +} diff --git a/src/types/dashboard 2.ts b/src/types/dashboard 2.ts new file mode 100644 index 0000000..5552a9a --- /dev/null +++ b/src/types/dashboard 2.ts @@ -0,0 +1,142 @@ +import type { AdminFileHealthFilter } from './file' + +export interface DashboardHealthSummary { + healthAttentionCount: number + healthDangerCount: number + healthWarningCount: number + expiringSoonCount: number + storageIssueCount: number + neverRetrievedCount: number + healthyCount: number + permanentCount: number +} + +export interface DashboardData { + totalFiles: number + storageUsed: number | string + yesterdayCount: number + todayCount: number + yesterdaySize: number | string + todaySize: number | string + sysUptime: number | null + activeCount?: number + expiredCount?: number + textCount?: number + fileCount?: number + chunkedCount?: number + usedCount?: number + storageBackend?: string + uploadSizeLimit?: number + openUpload?: number + enableChunk?: number + maxSaveSeconds?: number + healthAttentionCount?: number + healthDangerCount?: number + healthWarningCount?: number + expiringSoonCount?: number + storageIssueCount?: number + neverRetrievedCount?: number + healthyCount?: number + permanentCount?: number + healthSummary?: Partial +} + +export type DashboardViewData = Omit< + DashboardData, + | keyof DashboardHealthSummary + | 'activeCount' + | 'expiredCount' + | 'textCount' + | 'fileCount' + | 'chunkedCount' + | 'usedCount' + | 'storageBackend' + | 'uploadSizeLimit' + | 'openUpload' + | 'enableChunk' + | 'maxSaveSeconds' + | 'storageUsed' + | 'yesterdaySize' + | 'todaySize' +> & + DashboardHealthSummary & { + hasExtendedStats: boolean + activeCount: number + expiredCount: number + textCount: number + fileCount: number + chunkedCount: number + usedCount: number + storageBackend: string + uploadSizeLimit: number + openUpload: number + enableChunk: number + maxSaveSeconds: number + storageUsed: number + yesterdaySize: number + todaySize: number + storageUsedText: string + yesterdaySizeText: string + todaySizeText: string + uploadSizeLimitText: string + sysUptimeText: string + activeRatio: number + textRatio: number + fileRatio: number + healthyRatio: number + healthAttentionRatio: number + todaySizeRatio: number + } + +export interface DashboardHealthAction { + key: string + label: string + description: string + count: number + health: AdminFileHealthFilter + tone: 'danger' | 'warning' | 'success' | 'neutral' +} + +export interface AnalyticsDailyRow { + date: string + downloads: number + uploads: number + downloadTraffic: number | string + uploadTraffic: number | string +} + +export interface AnalyticsFileRow { + code: string + name: string + size: number | string + download_count: number + download_traffic: number | string + upload_count?: number + upload_traffic?: number | string + current: boolean + expired?: boolean + deleted?: boolean + created_at?: string + uploaded_at?: string + expired_at?: string + deleted_at?: string +} + +export interface AnalyticsData { + range: { + start: string + end: string + } + totals: { + totalDownloads: number + downloadedFiles: number + downloadTraffic: number | string + historicalFiles: number + currentFiles: number + totalUploads?: number + uploadTraffic?: number | string + } + daily: AnalyticsDailyRow[] + topFiles: AnalyticsFileRow[] + historyFiles: AnalyticsFileRow[] +} diff --git a/src/types/file 2.ts b/src/types/file 2.ts new file mode 100644 index 0000000..ddc4fd5 --- /dev/null +++ b/src/types/file 2.ts @@ -0,0 +1,496 @@ +export interface FileInfo { + id: string + name: string + size: number + type: string + uploadTime: string + downloadCount: number + expireTime?: string +} + +export interface FileListItem { + id: number + code: string + prefix: string + suffix: string + size: number + text?: string + description?: string + expired_at: string | null + expired_count: number | null + created_at: string + name?: string + type?: 'text' | 'file' + status?: 'active' | 'expired' + isText?: boolean + is_text?: boolean + isExpired?: boolean + is_expired?: boolean + isChunked?: boolean + is_chunked?: boolean + statusInsights?: AdminFileDetailStatusInsights + status_insights?: AdminFileDetailStatusInsights + remainingDownloads?: number | null + remaining_downloads?: number | null + usedCount?: number + used_count?: number + fileHash?: string | null + file_hash?: string | null +} + +export interface AdminFileViewItem extends FileListItem { + displayName: string + displaySize: string + displayExpiredAt: string + displayUsage: string + displayHealthState: string + displayHealthAction: string + isTextFile: boolean + isExpiredFile: boolean + isPermanentFile: boolean + isChunkedFile: boolean + remainingDownloadsValue: number | null + canPreviewText: boolean + statusInsightSeverity: AdminFileInsightSeverity + statusInsightState: string + statusInsightNextAction: string + statusInsightReasons: string[] +} + +export interface AdminFileSummary { + totalFiles: number + activeCount: number + expiredCount: number + textCount: number + fileCount: number + chunkedCount: number + healthAttentionCount: number + healthDangerCount: number + healthWarningCount: number + expiringSoonCount: number + storageIssueCount: number + neverRetrievedCount: number + healthyCount: number + permanentCount: number + storageUsed: number + usedCount: number +} + +export type AdminFileStatusFilter = 'all' | 'active' | 'expired' +export type AdminFileTypeFilter = 'all' | 'file' | 'text' | 'chunked' +export type AdminFileHealthFilter = + | 'all' + | 'attention' + | 'danger' + | 'warning' + | 'healthy' + | 'expired' + | 'expiring_soon' + | 'storage_issue' + | 'never_retrieved' + | 'permanent' +export type AdminFileSortBy = 'created_at' | 'expired_at' | 'name' | 'size' | 'used_count' | 'code' +export type AdminFileSortOrder = 'asc' | 'desc' + +export interface AdminFileListParams { + page: number + size: number + keyword?: string + status?: AdminFileStatusFilter + type?: AdminFileTypeFilter + health?: AdminFileHealthFilter + sortBy?: AdminFileSortBy + sortOrder?: AdminFileSortOrder +} + +export interface AdminFileViewPresetParams { + keyword: string + status: AdminFileStatusFilter + type: AdminFileTypeFilter + health: AdminFileHealthFilter + sortBy: AdminFileSortBy + sortOrder: AdminFileSortOrder + size: number +} + +export interface AdminFileViewPreset { + id: string + name: string + filters?: AdminFileViewPresetParams + params?: AdminFileViewPresetParams + isBuiltIn?: boolean + isDefault?: boolean + is_default?: boolean + createdAt?: string | null + created_at?: string | null + updatedAt?: string | null + updated_at?: string | null +} + +export interface AdminFileViewPresetRequest { + id?: string + name: string + filters: AdminFileViewPresetParams + params?: AdminFileViewPresetParams +} + +export interface AdminFileViewPresetsResponse { + presets?: AdminFileViewPreset[] + items?: AdminFileViewPreset[] + total?: number +} + +export interface FileEditForm { + id: number | null + code: string + prefix: string + suffix: string + expired_at: string + expired_count: number | null +} + +export interface AdminFilePatchPayload { + id: number + code?: string + prefix?: string + suffix?: string + expired_at?: string | null + expired_count?: number | null +} + +export type AdminFilePolicyAction = + | 'extend_24h' + | 'extend_7d' + | 'make_permanent' + | 'reset_download_limit' + +export interface AdminFilePolicyActionRequest { + id: number + action: AdminFilePolicyAction + downloadLimit?: number + download_limit?: number +} + +export interface AdminFileMetadata { + note: string + tags: string[] + updatedAt?: string | null + updated_at?: string | null +} + +export interface AdminFileMetadataRequest { + id: number + note?: string + tags?: string[] +} + +export interface FileListResponse { + data: FileListItem[] + total: number + page: number + size: number + summary?: AdminFileSummary +} + +export interface AdminFilePreviewResponse { + id: number + code: string + name: string + type: 'text' + content: string + length: number + previewLength?: number + preview_length?: number + truncated: boolean + maxChars?: number + max_chars?: number + createdAt?: string | null + created_at?: string | null + expiredAt?: string | null + expired_at?: string | null +} + +export interface AdminFileDetailPolicy { + expiredAt?: string | null + expired_at?: string | null + expiredCount?: number | null + expired_count?: number | null + remainingDownloads?: number | null + remaining_downloads?: number | null + isExpired?: boolean + is_expired?: boolean + isPermanent?: boolean + is_permanent?: boolean +} + +export interface AdminFileDetailStorage { + backend?: string + filePath?: string | null + file_path?: string | null + uuidFileName?: string | null + uuid_file_name?: string | null + fileHash?: string | null + file_hash?: string | null + isChunked?: boolean + is_chunked?: boolean + uploadId?: string | null + upload_id?: string | null +} + +export type AdminFileInsightSeverity = 'success' | 'warning' | 'danger' | 'info' | 'neutral' + +export interface AdminFileDetailInsightMetrics { + ageSeconds?: number + age_seconds?: number + secondsUntilExpiration?: number | null + seconds_until_expiration?: number | null + remainingDownloads?: number | null + remaining_downloads?: number | null + usedCount?: number + used_count?: number +} + +export interface AdminFileDetailStatusInsights { + severity?: AdminFileInsightSeverity + state?: string + nextAction?: string + next_action?: string + reasons?: string[] + metrics?: AdminFileDetailInsightMetrics +} + +export interface AdminFileDetailTimelineItem { + key: string + status?: string + severity?: AdminFileInsightSeverity + timestamp?: string | null + value?: number | string | null + detail?: string | null +} + +export interface AdminFileDetailTimelineViewItem extends AdminFileDetailTimelineItem { + severity: AdminFileInsightSeverity + displayTitle: string + displayDescription: string + displayMeta: string +} + +export interface AdminFileDetailResponse extends FileListItem { + filename?: string + displayName?: string + display_name?: string + isPermanent?: boolean + is_permanent?: boolean + hasDownloadLimit?: boolean + has_download_limit?: boolean + hasExpirationTime?: boolean + has_expiration_time?: boolean + textLength?: number + text_length?: number + canPreviewText?: boolean + can_preview_text?: boolean + canDownload?: boolean + can_download?: boolean + storageBackend?: string + storage_backend?: string + filePath?: string | null + file_path?: string | null + uuidFileName?: string | null + uuid_file_name?: string | null + uploadId?: string | null + upload_id?: string | null + policy?: AdminFileDetailPolicy + storage?: AdminFileDetailStorage + metadata?: AdminFileMetadata + meta?: AdminFileMetadata + note?: string + tags?: string[] + metadataUpdatedAt?: string | null + metadata_updated_at?: string | null + statusInsights?: AdminFileDetailStatusInsights + status_insights?: AdminFileDetailStatusInsights + timeline?: AdminFileDetailTimelineItem[] +} + +export interface AdminFileDetailViewItem extends AdminFileViewItem { + displayCreatedAt: string + displayRetrieveUrl: string + textLengthValue: number + canDownloadFile: boolean + isPermanentFile: boolean + hasDownloadLimitFile: boolean + hasExpirationTimeFile: boolean + isChunkedStorage: boolean + storageBackendValue: string + fileHashValue?: string | null + filePathValue?: string | null + uuidFileNameValue?: string | null + uploadIdValue?: string | null + metadataNote: string + metadataTags: string[] + metadataUpdatedAt: string | null + statusInsightMetrics?: AdminFileDetailInsightMetrics + detailTimeline: AdminFileDetailTimelineViewItem[] +} + +export interface AdminBatchDeleteFileFailure { + id: number + reason: string +} + +export interface AdminBatchDeleteFilesResponse { + requestedCount?: number + requested_count?: number + uniqueCount?: number + unique_count?: number + deletedCount?: number + deleted_count?: number + missingCount?: number + missing_count?: number + failedCount?: number + failed_count?: number + deleted?: number[] + missing?: number[] + failed?: AdminBatchDeleteFileFailure[] +} + +export interface AdminBatchUpdateFileFailure { + id: number + reason: string +} + +export interface AdminBatchUpdateFilesRequest { + ids: number[] + expired_at?: string | null + expired_count?: number | null + clearExpiredAt?: boolean + clear_expired_at?: boolean +} + +export interface AdminBatchUpdateFilesResponse { + requestedCount?: number + requested_count?: number + uniqueCount?: number + unique_count?: number + updatedCount?: number + updated_count?: number + missingCount?: number + missing_count?: number + failedCount?: number + failed_count?: number + updated?: number[] + missing?: number[] + failed?: AdminBatchUpdateFileFailure[] +} + +export interface AdminBatchPolicyActionRequest { + ids: number[] + action: AdminFilePolicyAction + downloadLimit?: number + download_limit?: number +} + +export interface AdminBatchPolicyActionResponse extends AdminBatchUpdateFilesResponse { + action?: AdminFilePolicyAction | string +} + +export type AdminBatchExpireUnit = 'hours' | 'days' + +export type AdminBatchEditMode = 'expiresAt' | 'relativeExpire' | 'downloadLimit' | 'forever' + +export interface AdminBatchEditForm { + mode: AdminBatchEditMode + expired_at: string + expired_count: number | null + relative_expire_value: number | null + relative_expire_unit: AdminBatchExpireUnit +} + +export interface FileUploadResponse { + code: string + name: string +} + +export interface TextSendResponse { + code: string +} + +export interface ShareSelectResponse { + code: string + name: string + text: string + size: number + type?: 'file' | 'text' + is_text?: boolean + content?: string | null + download_url?: string | null + created_at?: string | null + expired_at?: string | null + expires_at?: string | null + expired_count?: number | null + used_count?: number + remaining_downloads?: number | null +} + +export interface ShareMetadataResponse { + code: string + name: string + size: number + type: 'file' | 'text' + is_text: boolean + created_at?: string | null + expired_at?: string | null + expires_at?: string | null + expired_count?: number | null + used_count?: number + remaining_downloads?: number | null +} + +export interface ReceivedFileRecord { + id: number + code: string + filename: string + size: string + downloadUrl: string | null + content: string | null + date: string + type?: 'file' | 'text' + remainingDownloads?: number | null +} + +export interface SentFileRecord { + id: number + filename: string + date: string + size: string + expiration: string + retrieveCode: string +} + +export interface UploadProgress { + loaded: number + total: number + percentage: number +} + +export interface ChunkUploadInitRequest { + file_name: string + file_size: number + chunk_size: number + file_hash: string +} + +export interface ChunkUploadInitResponse { + code?: string + name?: string + upload_id?: string + existed?: boolean + uploaded_chunks?: number[] +} + +export interface ChunkUploadCompleteRequest { + expire_value: number + expire_style: string +} + +export type ChunkUploadResponse = null diff --git a/src/types/index 2.ts b/src/types/index 2.ts new file mode 100644 index 0000000..3dad71f --- /dev/null +++ b/src/types/index 2.ts @@ -0,0 +1,9 @@ +export * from './activity' +export * from './api' +export * from './auth' +export * from './config' +export * from './dashboard' +export * from './file' +export * from './presign-upload' +export * from './trash' +export * from './ui' diff --git a/src/types/presign-upload 2.ts b/src/types/presign-upload 2.ts new file mode 100644 index 0000000..abb09ea --- /dev/null +++ b/src/types/presign-upload 2.ts @@ -0,0 +1,55 @@ +import type { UploadProgress } from './file' + +export type PresignUploadMode = 'direct' | 'proxy' + +export type PresignUploadStatus = + | 'idle' + | 'initializing' + | 'uploading' + | 'confirming' + | 'success' + | 'error' + +export type ExpireStyle = 'day' | 'hour' | 'minute' | 'forever' | 'count' + +export interface PresignInitRequest { + file_name: string + file_size: number + expire_value?: number + expire_style?: ExpireStyle +} + +export interface PresignInitResponse { + upload_id: string + upload_url: string + proxy_upload_url?: string + legacy_proxy_upload_url?: string + mode: PresignUploadMode + expires_in: number +} + +export interface PresignConfirmRequest { + expire_value?: number + expire_style?: ExpireStyle +} + +export interface PresignUploadResult { + code: string + name: string +} + +export interface PresignStatusResponse { + upload_id: string + file_name: string + file_size: number + mode: PresignUploadMode + created_at: string + expires_at: string + is_expired: boolean +} + +export interface PresignUploadOptions { + expireValue?: number + expireStyle?: ExpireStyle + onProgress?: (progress: UploadProgress) => void +} diff --git a/src/types/trash 2.ts b/src/types/trash 2.ts new file mode 100644 index 0000000..2cd385d --- /dev/null +++ b/src/types/trash 2.ts @@ -0,0 +1,27 @@ +export interface TrashFileItem { + id: number + code: string + name?: string + prefix?: string + suffix?: string + size: number + text?: string | null + trashedAt?: string | null + trashExpiresAt?: string | null + trashReason?: string | null + trashPurgedAt?: string | null + isTrashPermanent?: boolean + isTrashPurged?: boolean +} + +export interface TrashListResponse { + page: number + size: number + total: number + data: TrashFileItem[] +} + +export interface TrashListParams { + page: number + size: number +} diff --git a/src/types/ui 2.ts b/src/types/ui 2.ts new file mode 100644 index 0000000..8a8e21f --- /dev/null +++ b/src/types/ui 2.ts @@ -0,0 +1,26 @@ +export type ThemeMode = 'light' | 'dark' | 'system' + +export type SendType = 'file' | 'text' + +export type AlertType = 'success' | 'error' | 'warning' | 'info' + +export interface Alert { + id: number + message: string + type: AlertType + progress: number + duration: number + startTime: number +} + +export type UploadStatus = 'idle' | 'uploading' | 'success' | 'error' + +export interface RouteConfig { + path: string + name: string + component: () => Promise<{ default: object }> + meta?: { + requiresAuth?: boolean + title?: string + } +} diff --git a/src/utils/api 2.ts b/src/utils/api 2.ts new file mode 100644 index 0000000..f4e76cb --- /dev/null +++ b/src/utils/api 2.ts @@ -0,0 +1,2 @@ +export { apiBaseURL, rawApiClient } from '@/services/client' +export { default } from '@/services/client' diff --git a/src/utils/auth-storage 2.ts b/src/utils/auth-storage 2.ts new file mode 100644 index 0000000..ff59afb --- /dev/null +++ b/src/utils/auth-storage 2.ts @@ -0,0 +1,26 @@ +import { STORAGE_KEYS } from '@/constants' + +export function readStoredAdminPassword(): string { + return localStorage.getItem(STORAGE_KEYS.ADMIN_PASSWORD) || '' +} + +export function writeStoredAdminPassword(password: string) { + localStorage.setItem(STORAGE_KEYS.ADMIN_PASSWORD, password) +} + +export function readStoredToken(): string { + return localStorage.getItem(STORAGE_KEYS.TOKEN) || '' +} + +export function writeStoredToken(token: string) { + localStorage.setItem(STORAGE_KEYS.TOKEN, token) +} + +export function clearStoredAuth() { + localStorage.removeItem(STORAGE_KEYS.ADMIN_PASSWORD) + localStorage.removeItem(STORAGE_KEYS.TOKEN) +} + +export function clearStoredToken() { + localStorage.removeItem(STORAGE_KEYS.TOKEN) +} diff --git a/src/utils/clipboard 2.ts b/src/utils/clipboard 2.ts new file mode 100644 index 0000000..8ef5f8e --- /dev/null +++ b/src/utils/clipboard 2.ts @@ -0,0 +1,129 @@ +/** + * 剪贴板工具函数 + */ + +import { buildRetrieveUrl, buildWgetCommand } from '@/utils/share-url' + +type CopyNotifyType = 'success' | 'error' + +interface CopyOptions { + successMsg?: string + errorMsg?: string + showMsg?: boolean + notify?: (message: string, type: CopyNotifyType) => void +} + +/** + * 复制文本到剪贴板 + * @param text 要复制的文本 + * @param options 配置选项 + * @returns Promise 是否复制成功 + */ +export const copyToClipboard = async ( + text: string, + options: CopyOptions = {} +): Promise => { + const { + successMsg = '复制成功', + errorMsg = '复制失败,请手动复制', + showMsg = true, + notify + } = options + + const showCopyMessage = (message: string, type: CopyNotifyType) => { + if (showMsg) { + notify?.(message, type) + } + } + + const showManualCopyDialog = () => { + window.prompt('复制下面内容', text) + } + + try { + if (navigator.clipboard && window.isSecureContext) { + try { + await navigator.clipboard.writeText(text) + showCopyMessage(successMsg, 'success') + return true + } catch { + // Continue to the DOM fallback. + } + } + + const textarea = document.createElement('textarea') + textarea.value = text + textarea.setAttribute('readonly', '') + textarea.style.cssText = + 'position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;z-index:-1;' + document.body.appendChild(textarea) + textarea.focus() + textarea.select() + textarea.setSelectionRange(0, textarea.value.length) + let success = false + try { + success = document.execCommand('copy') + } finally { + document.body.removeChild(textarea) + } + if (success) { + showCopyMessage(successMsg, 'success') + return true + } + + showManualCopyDialog() + showCopyMessage('已打开手动复制窗口', 'error') + return false + } catch (err) { + console.error('复制失败:', err) + showManualCopyDialog() + showCopyMessage(errorMsg, 'error') + return false + } +} + +/** + * 生成并复制取件链接 + * @param code 取件码 + * @returns Promise 是否复制成功 + */ +export const copyRetrieveLink = async ( + code: string, + options: Pick = {} +): Promise => { + const link = buildRetrieveUrl(code) + return copyToClipboard(link, { + successMsg: '取件链接已复制到剪贴板', + errorMsg: '复制失败,请手动复制取件链接', + ...options + }) +} + +/** + * 复制取件码 + * @param code 取件码 + * @returns Promise 是否复制成功 + */ +export const copyRetrieveCode = async ( + code: string, + options: Pick = {} +): Promise => { + return copyToClipboard(code, { + successMsg: '取件码已复制到剪贴板', + errorMsg: '复制失败,请手动复制取件码', + ...options + }) +} + +export const copyWgetCommand = ( + retrieveCode: string, + fileName: string, + options: Pick = {} +) => { + const command = buildWgetCommand(retrieveCode, fileName) + void copyToClipboard(command, { + successMsg: '命令已复制到剪贴板', + errorMsg: '复制失败,请手动复制命令', + ...options + }) +} diff --git a/src/utils/clipboard-paste 2.ts b/src/utils/clipboard-paste 2.ts new file mode 100644 index 0000000..4a44e0a --- /dev/null +++ b/src/utils/clipboard-paste 2.ts @@ -0,0 +1,40 @@ +export const getClipboardFile = (items: DataTransferItemList): File | null => { + for (let index = 0; index < items.length; index++) { + const item = items[index] + if (item.kind !== 'file') { + continue + } + + const file = item.getAsFile() + if (file) { + return file + } + } + return null +} + +export type TextInsertionInput = { + text: string + insertText: string + selectionStart: number + selectionEnd: number +} + +export type TextInsertionResult = { + value: string + cursor: number +} + +export const insertTextAtSelection = ({ + text, + insertText, + selectionStart, + selectionEnd +}: TextInsertionInput): TextInsertionResult => { + const beforeSelection = text.substring(0, selectionStart) + const afterSelection = text.substring(selectionEnd) + return { + value: beforeSelection + insertText + afterSelection, + cursor: selectionStart + insertText.length + } +} diff --git a/src/utils/common 2.ts b/src/utils/common 2.ts new file mode 100644 index 0000000..f818fe6 --- /dev/null +++ b/src/utils/common 2.ts @@ -0,0 +1,236 @@ +/** + * 通用工具函数 + */ +import type { ApiErrorPayload } from '@/types' + +/** + * 格式化时间戳为可读格式 + * @param timestamp 时间戳字符串 + * @param format 格式类型 + * @returns 格式化后的时间字符串 + */ +export function formatTimestamp(timestamp: string, format: 'datetime' | 'date' | 'time' = 'datetime'): string { + const date = new Date(timestamp) + const year = date.getFullYear() + const month = (date.getMonth() + 1).toString().padStart(2, '0') + const day = date.getDate().toString().padStart(2, '0') + const hours = date.getHours().toString().padStart(2, '0') + const minutes = date.getMinutes().toString().padStart(2, '0') + const seconds = date.getSeconds().toString().padStart(2, '0') + + switch (format) { + case 'date': + return `${year}-${month}-${day}` + case 'time': + return `${hours}:${minutes}:${seconds}` + case 'datetime': + default: + return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}` + } +} + +/** + * 格式化文件大小 + * @param bytes 字节数 + * @param decimals 小数位数 + * @returns 格式化后的文件大小字符串 + */ +export function formatFileSize(bytes: number, decimals: number = 2): string { + if (bytes === 0) return '0 Bytes' + + const k = 1024 + const dm = decimals < 0 ? 0 : decimals + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] + + const i = Math.floor(Math.log(bytes) / Math.log(k)) + + return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i] +} + +/** + * 格式化持续时间 + * @param seconds 秒数 + * @param t 翻译函数 + * @returns 格式化后的持续时间字符串 + */ +export function formatDuration(seconds: number, t?: (key: string) => string): string { + if (seconds === 0) return t ? t('utils.time.forever') : 'Forever' + + const units = [ + { key: 'utils.time.day', value: 86400 }, + { key: 'utils.time.hour', value: 3600 }, + { key: 'utils.time.minute', value: 60 }, + { key: 'utils.time.second', value: 1 } + ] + + for (const unit of units) { + if (seconds >= unit.value) { + const value = Math.floor(seconds / unit.value) + const unitName = t ? t(unit.key) : unit.key.split('.').pop() + return `${value}${unitName}` + } + } + + const secondName = t ? t('utils.time.second') : 'second' + return `${seconds}${secondName}` +} + +/** + * 防抖函数 + * @param func 要防抖的函数 + * @param wait 等待时间(毫秒) + * @returns 防抖后的函数 + */ +export function debounce unknown>( + func: T, + wait: number +): (...args: Parameters) => void { + let timeout: ReturnType | null = null + + return (...args: Parameters) => { + if (timeout) { + clearTimeout(timeout) + } + timeout = setTimeout(() => func(...args), wait) + } +} + +/** + * 节流函数 + * @param func 要节流的函数 + * @param limit 限制时间(毫秒) + * @returns 节流后的函数 + */ +export function throttle unknown>( + func: T, + limit: number +): (...args: Parameters) => void { + let inThrottle: boolean = false + + return (...args: Parameters) => { + if (!inThrottle) { + func(...args) + inThrottle = true + setTimeout(() => inThrottle = false, limit) + } + } +} + +/** + * 验证邮箱格式 + * @param email 邮箱地址 + * @returns 是否为有效邮箱 + */ +export function isValidEmail(email: string): boolean { + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ + return emailRegex.test(email) +} + +/** + * 验证URL格式 + * @param url URL地址 + * @returns 是否为有效URL + */ +export function isValidUrl(url: string): boolean { + try { + new URL(url) + return true + } catch { + return false + } +} + +/** + * 生成随机字符串 + * @param length 字符串长度 + * @param chars 可选字符集 + * @returns 随机字符串 + */ +export function generateRandomString( + length: number = 8, + chars: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789' +): string { + let result = '' + for (let i = 0; i < length; i++) { + result += chars.charAt(Math.floor(Math.random() * chars.length)) + } + return result +} + +/** + * 深度克隆对象 + * @param obj 要克隆的对象 + * @returns 克隆后的对象 + */ +export function deepClone(obj: T): T { + if (obj === null || typeof obj !== 'object') { + return obj + } + + if (obj instanceof Date) { + return new Date(obj.getTime()) as T + } + + if (obj instanceof Array) { + return obj.map(item => deepClone(item)) as T + } + + if (typeof obj === 'object') { + const clonedObj = {} as T + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + clonedObj[key] = deepClone(obj[key]) + } + } + return clonedObj + } + + return obj +} + +/** + * 获取文件扩展名 + * @param filename 文件名 + * @returns 文件扩展名(不包含点) + */ +export function getFileExtension(filename: string): string { + return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2) +} + +/** + * 检查是否为移动设备 + * @returns 是否为移动设备 + */ +export function isMobile(): boolean { + return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) +} + +/** + * 格式化数字,添加千分位分隔符 + * @param num 数字 + * @returns 格式化后的数字字符串 + */ +export function formatNumber(num: number): string { + return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',') +} + +type ErrorWithResponse = { + response?: { + data?: ApiErrorPayload + } + message?: string +} + +export function getErrorMessage(error: unknown, fallback: string): string { + if (!error || typeof error !== 'object') { + return fallback + } + + const errorWithResponse = error as ErrorWithResponse + return ( + errorWithResponse.response?.data?.detail || + errorWithResponse.response?.data?.message || + errorWithResponse.message || + fallback + ) +} diff --git a/src/utils/config-form 2.ts b/src/utils/config-form 2.ts new file mode 100644 index 0000000..4f14636 --- /dev/null +++ b/src/utils/config-form 2.ts @@ -0,0 +1,107 @@ +import type { ConfigState } from '@/types' + +export type FileSizeUnit = 'KB' | 'MB' | 'GB' +export type SaveTimeUnit = '秒' | '分' | '时' | '天' + +export type FileSizeForm = { + value: number + unit: FileSizeUnit +} + +export type SaveTimeForm = { + value: number + unit: SaveTimeUnit +} + +const FILE_SIZE_UNITS: Record = { + KB: 1024, + MB: 1024 * 1024, + GB: 1024 * 1024 * 1024 +} + +const SAVE_TIME_UNITS: Record = { + 秒: 1, + 分: 60, + 时: 3600, + 天: 86400 +} + +export function bytesToFileSizeForm(bytes: number): FileSizeForm { + if (bytes >= FILE_SIZE_UNITS.GB) { + return { + value: Math.round(bytes / FILE_SIZE_UNITS.GB), + unit: 'GB' + } + } + + if (bytes >= FILE_SIZE_UNITS.MB) { + return { + value: Math.round(bytes / FILE_SIZE_UNITS.MB), + unit: 'MB' + } + } + + return { + value: Math.round(bytes / FILE_SIZE_UNITS.KB), + unit: 'KB' + } +} + +export function fileSizeFormToBytes(value: number, unit: FileSizeUnit): number { + return value * FILE_SIZE_UNITS[unit] +} + +export function secondsToSaveTimeForm(seconds: number): SaveTimeForm { + if (seconds === 0) { + return { + value: 7, + unit: '天' + } + } + + if (seconds % SAVE_TIME_UNITS.天 === 0 && seconds >= SAVE_TIME_UNITS.天) { + return { + value: seconds / SAVE_TIME_UNITS.天, + unit: '天' + } + } + + if (seconds % SAVE_TIME_UNITS.时 === 0 && seconds >= SAVE_TIME_UNITS.时) { + return { + value: seconds / SAVE_TIME_UNITS.时, + unit: '时' + } + } + + if (seconds % SAVE_TIME_UNITS.分 === 0 && seconds >= SAVE_TIME_UNITS.分) { + return { + value: seconds / SAVE_TIME_UNITS.分, + unit: '分' + } + } + + return { + value: seconds, + unit: '秒' + } +} + +export function saveTimeFormToSeconds(value: number, unit: SaveTimeUnit): number { + if (value === 0) { + return 7 * SAVE_TIME_UNITS.天 + } + + return value * SAVE_TIME_UNITS[unit] +} + +export function buildConfigSubmitPayload( + config: ConfigState, + fileSize: FileSizeForm, + saveTime: SaveTimeForm +): ConfigState { + return { + ...config, + uploadSize: fileSizeFormToBytes(fileSize.value, fileSize.unit), + max_save_seconds: saveTimeFormToSeconds(saveTime.value, saveTime.unit) + } +} diff --git a/src/utils/config-storage 2.ts b/src/utils/config-storage 2.ts new file mode 100644 index 0000000..3bcc512 --- /dev/null +++ b/src/utils/config-storage 2.ts @@ -0,0 +1,108 @@ +import { DEFAULT_CONFIG, FILE_SIZE_LIMITS, STORAGE_KEYS } from '@/constants' +import type { ConfigState, SystemConfig } from '@/types' + +export type PublicConfig = SystemConfig & { + uploadSize: number + expireStyle: string[] + openUpload: number + max_save_seconds: number + enableChunk: number + notify_title?: string + notify_content?: string + page_explain?: string + showAdminAddr?: number + themesSelect?: string + background?: string + opacity?: number +} + +export const DEFAULT_PUBLIC_CONFIG: PublicConfig = { + ...DEFAULT_CONFIG, + uploadSize: FILE_SIZE_LIMITS.MAX_FILE_SIZE, + expireStyle: ['day'], + openUpload: 1, + max_save_seconds: 0, + enableChunk: 0 +} + +export const DEFAULT_CONFIG_STATE: ConfigState = { + name: DEFAULT_PUBLIC_CONFIG.name, + description: DEFAULT_PUBLIC_CONFIG.description || '', + file_storage: '', + themesChoices: [], + expireStyle: DEFAULT_PUBLIC_CONFIG.expireStyle, + admin_token: '', + robotsText: '', + keywords: '', + notify_title: '', + notify_content: '', + openUpload: DEFAULT_PUBLIC_CONFIG.openUpload, + uploadSize: DEFAULT_PUBLIC_CONFIG.uploadSize, + storage_path: '', + uploadMinute: 1, + max_save_seconds: DEFAULT_PUBLIC_CONFIG.max_save_seconds, + trashRetentionDays: 30, + opacity: 0.9, + enableChunk: DEFAULT_PUBLIC_CONFIG.enableChunk, + s3_access_key_id: '', + background: '', + showAdminAddr: 0, + page_explain: '', + s3_secret_access_key: '', + aws_session_token: '', + s3_signature_version: '', + s3_region_name: '', + s3_bucket_name: '', + s3_endpoint_url: '', + s3_hostname: '', + uploadCount: 1, + errorMinute: 1, + errorCount: 1, + s3_proxy: 0, + themesSelect: '', + webdav_url: '', + webdav_username: '', + webdav_password: '' +} + +export function readStoredConfig>(): T | null { + try { + const rawConfig = localStorage.getItem(STORAGE_KEYS.CONFIG) + return rawConfig ? (JSON.parse(rawConfig) as T) : null + } catch { + return null + } +} + +export function toPublicConfig(config: Partial | null | undefined): Partial { + if (!config) return {} + + return { + name: config.name, + description: config.description, + uploadSize: config.uploadSize, + expireStyle: config.expireStyle, + openUpload: config.openUpload, + max_save_seconds: config.max_save_seconds, + enableChunk: config.enableChunk, + notify_title: config.notify_title, + notify_content: config.notify_content, + page_explain: config.page_explain, + showAdminAddr: config.showAdminAddr, + themesSelect: config.themesSelect, + background: config.background, + opacity: config.opacity + } +} + +export function writeStoredConfig(config: object) { + localStorage.setItem(STORAGE_KEYS.CONFIG, JSON.stringify(toPublicConfig(config as Partial))) +} + +export function readNotifyKey(): string | null { + return localStorage.getItem(STORAGE_KEYS.NOTIFY) +} + +export function writeNotifyKey(notifyKey: string) { + localStorage.setItem(STORAGE_KEYS.NOTIFY, notifyKey) +} diff --git a/src/utils/content-preview 2.ts b/src/utils/content-preview 2.ts new file mode 100644 index 0000000..81ed24d --- /dev/null +++ b/src/utils/content-preview 2.ts @@ -0,0 +1,42 @@ +const MARKDOWN_ALLOWED_TAGS = [ + 'p', + 'br', + 'strong', + 'em', + 'u', + 'h1', + 'h2', + 'h3', + 'h4', + 'h5', + 'h6', + 'ul', + 'ol', + 'li', + 'blockquote', + 'code', + 'pre', + 'a', + 'img' +] + +const MARKDOWN_ALLOWED_ATTR = ['href', 'src', 'alt', 'title', 'class'] + +export async function renderMarkdownPreview(content: string): Promise { + try { + const [{ marked }, { default: DOMPurify }] = await Promise.all([ + import('marked'), + import('dompurify') + ]) + const rawHtml = await marked(content) + return DOMPurify.sanitize(rawHtml, { + ALLOWED_TAGS: MARKDOWN_ALLOWED_TAGS, + ALLOWED_ATTR: MARKDOWN_ALLOWED_ATTR, + ALLOWED_URI_REGEXP: + /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|xxx):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i + }) + } catch (error) { + console.error('Markdown 渲染失败:', error) + return content + } +} diff --git a/src/utils/convert 2.ts b/src/utils/convert 2.ts new file mode 100644 index 0000000..6853bd8 --- /dev/null +++ b/src/utils/convert 2.ts @@ -0,0 +1,10 @@ +// 存储单位转换 +export const getStorageUnit = (value: number) => { + if (value >= 1024 * 1024 * 1024) { + return Math.round(value / (1024 * 1024 * 1024)) + 'GB' + } else if (value >= 1024 * 1024) { + return Math.round(value / (1024 * 1024)) + 'MB' + } else { + return Math.round(value / 1024) + 'KB' + } +} diff --git a/src/utils/download-action 2.ts b/src/utils/download-action 2.ts new file mode 100644 index 0000000..b3a4aa5 --- /dev/null +++ b/src/utils/download-action 2.ts @@ -0,0 +1,84 @@ +import { saveAs } from 'file-saver' +import type { AdminFileViewItem, ApiResponse, ReceivedFileRecord } from '@/types' +import { buildDownloadUrl } from '@/utils/share-url' + +const unsafeFilenamePattern = new RegExp( + `[\\\\/:*?"<>|${String.fromCharCode(0)}-${String.fromCharCode(31)}]`, + 'g' +) + +export function downloadReceivedRecord(record: ReceivedFileRecord): void { + if (record.downloadUrl) { + window.open(buildDownloadUrl(record.downloadUrl), '_blank') + return + } + + if (record.content) { + const blob = new Blob([record.content], { type: 'text/plain;charset=utf-8' }) + saveAs(blob, `${record.filename}.txt`) + } +} + +export const getSafeFilename = (name: string) => + name + .replace(unsafeFilenamePattern, '_') + .replace(/\s+/g, ' ') + .trim() + .slice(0, 180) || 'download' + +const getFilenameFromDisposition = (disposition?: string) => { + if (!disposition) return '' + + const utf8Match = disposition.match(/filename\*=UTF-8''([^;]+)/i) + if (utf8Match?.[1]) { + try { + return decodeURIComponent(utf8Match[1]) + } catch { + return utf8Match[1] + } + } + + const asciiMatch = disposition.match(/filename="?([^"]+)"?/i) + return asciiMatch?.[1] || '' +} + +const readBlobAsText = (blob: Blob): Promise => + new Promise((resolve, reject) => { + const reader = new FileReader() + reader.onload = () => resolve(String(reader.result || '')) + reader.onerror = () => reject(reader.error) + reader.readAsText(blob) + }) + +export function exportAdminTextFile(file: AdminFileViewItem, content: string): void { + const filename = getSafeFilename(file.displayName || file.code) + const blob = new Blob([content], { type: 'text/plain;charset=utf-8' }) + saveAs(blob, `${filename}.txt`) +} + +export async function downloadAdminManagedFile( + file: AdminFileViewItem, + response: { data: Blob; headers: Record } +): Promise { + if (file.isTextFile) { + const text = await readBlobAsText(response.data) + let content = text + + try { + const payload = JSON.parse(text) as ApiResponse + content = typeof payload.detail === 'string' ? payload.detail : text + } catch { + content = text + } + + exportAdminTextFile(file, content) + return + } + + const disposition = + response.headers['content-disposition'] || response.headers['Content-Disposition'] + const filename = getSafeFilename( + getFilenameFromDisposition(disposition) || file.displayName || file.code + ) + saveAs(response.data, filename) +} diff --git a/src/utils/file-processing 2.ts b/src/utils/file-processing 2.ts new file mode 100644 index 0000000..4f00fb1 --- /dev/null +++ b/src/utils/file-processing 2.ts @@ -0,0 +1,59 @@ +const SMALL_FILE_HASH_LIMIT = 10 * 1024 * 1024 +const LARGE_FILE_HASH_CHUNK_SIZE = 5 * 1024 * 1024 + +const generateFallbackHash = (file: File): string => { + const fileInfo = `${file.name}-${file.size}-${file.lastModified}` + let hash = 0 + for (let i = 0; i < fileInfo.length; i++) { + const char = fileInfo.charCodeAt(i) + hash = (hash << 5) - hash + char + hash = hash & hash + } + return Math.abs(hash).toString(16).padStart(64, '0') +} + +const createSha256Hash = async (data: BufferSource): Promise => { + const hashBuffer = await crypto.subtle.digest('SHA-256', data) + const hashArray = Array.from(new Uint8Array(hashBuffer)) + return hashArray.map((byte) => byte.toString(16).padStart(2, '0')).join('') +} + +export const calculateFileHash = async (file: File): Promise => { + try { + if (file.size <= SMALL_FILE_HASH_LIMIT) { + const buffer = await file.arrayBuffer() + return window.isSecureContext ? createSha256Hash(buffer) : generateFallbackHash(file) + } + + const firstChunk = file.slice(0, LARGE_FILE_HASH_CHUNK_SIZE) + const lastChunk = file.slice(-LARGE_FILE_HASH_CHUNK_SIZE) + const [firstBuffer, lastBuffer] = await Promise.all([ + firstChunk.arrayBuffer(), + lastChunk.arrayBuffer() + ]) + const combined = new Uint8Array(firstBuffer.byteLength + lastBuffer.byteLength + 16) + combined.set(new Uint8Array(firstBuffer), 0) + combined.set(new Uint8Array(lastBuffer), firstBuffer.byteLength) + const sizeBytes = new TextEncoder().encode(file.size.toString()) + combined.set(sizeBytes, firstBuffer.byteLength + lastBuffer.byteLength) + + return window.isSecureContext ? createSha256Hash(combined) : generateFallbackHash(file) + } catch (error) { + console.error('File hash calculation failed:', error) + return generateFallbackHash(file) + } +} + +export const packFilesAsZip = async (files: File[]): Promise => { + const { default: JSZip } = await import('jszip') + const zip = new JSZip() + for (const file of files) { + zip.file(file.name, file) + } + const blob = await zip.generateAsync({ + type: 'blob', + compression: 'DEFLATE', + compressionOptions: { level: 6 } + }) + return new File([blob], `files_${Date.now()}.zip`, { type: 'application/zip' }) +} diff --git a/src/utils/preference-storage 2.ts b/src/utils/preference-storage 2.ts new file mode 100644 index 0000000..6582123 --- /dev/null +++ b/src/utils/preference-storage 2.ts @@ -0,0 +1,20 @@ +import { STORAGE_KEYS } from '@/constants' +import type { ThemeMode } from '@/types' + +const LOCALE_STORAGE_KEY = 'locale' + +export function readStoredThemeMode(): string | null { + return localStorage.getItem(STORAGE_KEYS.COLOR_MODE) +} + +export function writeStoredThemeMode(mode: ThemeMode) { + localStorage.setItem(STORAGE_KEYS.COLOR_MODE, mode) +} + +export function readStoredLocale(): string | null { + return localStorage.getItem(LOCALE_STORAGE_KEY) +} + +export function writeStoredLocale(locale: string) { + localStorage.setItem(LOCALE_STORAGE_KEY, locale) +} diff --git a/src/utils/record-storage 2.ts b/src/utils/record-storage 2.ts new file mode 100644 index 0000000..6aba34b --- /dev/null +++ b/src/utils/record-storage 2.ts @@ -0,0 +1,23 @@ +export function readStoredRecords(key: string): T[] { + if (typeof window === 'undefined') return [] + + try { + const raw = localStorage.getItem(key) + if (!raw) return [] + + const parsed = JSON.parse(raw) + return Array.isArray(parsed) ? (parsed as T[]) : [] + } catch { + return [] + } +} + +export function writeStoredRecords(key: string, records: T[]) { + if (typeof window === 'undefined') return + + try { + localStorage.setItem(key, JSON.stringify(records)) + } catch { + // 本地存储不可用时保持内存记录,不影响当前会话。 + } +} diff --git a/src/utils/retrieval-code 2.ts b/src/utils/retrieval-code 2.ts new file mode 100644 index 0000000..1b91c90 --- /dev/null +++ b/src/utils/retrieval-code 2.ts @@ -0,0 +1,25 @@ +const CODE_PATTERN = /^[A-Za-z0-9]+$/ + +export const isValidRetrievalCode = (value: string): boolean => { + const code = value.trim() + return (code.length === 5 || code.length === 8) && CODE_PATTERN.test(code) +} + +export const parseRetrievalCode = (value: string): string => { + const raw = value.trim() + if (isValidRetrievalCode(raw)) return raw + try { + const url = new URL(raw) + const queryCode = url.searchParams.get('code') || '' + if (queryCode) return isValidRetrievalCode(queryCode) ? queryCode : '' + if (url.hash) { + const hash = url.hash.startsWith('#') ? url.hash.slice(1) : url.hash + const query = hash.includes('?') ? hash.slice(hash.indexOf('?') + 1) : hash + const hashCode = new URLSearchParams(query).get('code') || '' + return isValidRetrievalCode(hashCode) ? hashCode : '' + } + return '' + } catch { + return '' + } +} diff --git a/src/utils/send-record 2.ts b/src/utils/send-record 2.ts new file mode 100644 index 0000000..00fe046 --- /dev/null +++ b/src/utils/send-record 2.ts @@ -0,0 +1,99 @@ +import type { ApiResponse, SendType, SentFileRecord } from '@/types' + +type Translate = (key: string, params?: Record) => string + +type BuildSentRecordInput = { + response: ApiResponse + sendType: SendType + textContent: string + selectedFile: File | null + selectedFiles: File[] + expirationMethod: string + expirationValue: string + translate: Translate + getUnit: (method: string) => string +} + +const expirationSecondsByMethod: Record = { + minute: 60, + hour: 3600, + day: 86400 +} + +export function isExpirationWithinLimit( + method: string, + value: string, + maxSaveSeconds: number +): boolean { + if (method === 'forever' || method === 'count') return true + if (maxSaveSeconds === 0) return true + + const multiplier = expirationSecondsByMethod[method] + if (!multiplier) return false + + return parseInt(value) * multiplier <= maxSaveSeconds +} + +export function formatExpirationTime( + method: string, + value: string, + translate: Translate, + getUnit: (method: string) => string +): string { + if (method === 'forever') return translate('send.expiration.units.forever') + if (method === 'count') return translate('send.messages.expiresAfterCount', { count: value }) + + const now = new Date() + const expireValue = parseInt(value) + + switch (method) { + case 'minute': + now.setMinutes(now.getMinutes() + expireValue) + break + case 'hour': + now.setHours(now.getHours() + expireValue) + break + case 'day': + now.setDate(now.getDate() + expireValue) + break + default: + return translate('send.messages.expiresAfter', { value, unit: getUnit(method) }) + } + + const year = now.getFullYear() + const month = (now.getMonth() + 1).toString().padStart(2, '0') + const day = now.getDate().toString().padStart(2, '0') + const hours = now.getHours().toString().padStart(2, '0') + const minutes = now.getMinutes().toString().padStart(2, '0') + return translate('send.messages.expiresAt', { date: `${year}-${month}-${day} ${hours}:${minutes}` }) +} + +export function buildSentRecord(input: BuildSentRecordInput): SentFileRecord { + const retrieveCode = (input.response.detail as { code?: string } | undefined)?.code || '' + const fileName = (input.response.detail as { name?: string } | undefined)?.name || '' + + const totalSelectedSize = input.selectedFiles.reduce((total, file) => total + file.size, 0) + const displaySize = + input.sendType === 'text' + ? `${(input.textContent.length / 1024).toFixed(2)} KB` + : input.selectedFiles.length > 0 + ? `${(totalSelectedSize / (1024 * 1024)).toFixed(1)} MB` + : `${((input.selectedFile?.size || 0) / (1024 * 1024)).toFixed(1)} MB` + + return { + id: Date.now(), + filename: fileName, + date: new Date().toISOString().split('T')[0], + size: displaySize, + expiration: + input.expirationMethod === 'forever' + ? input.translate('send.expiration.forever') + : formatExpirationTime( + input.expirationMethod, + input.expirationValue, + input.translate, + input.getUnit + ), + retrieveCode + } +} diff --git a/src/utils/sent-record-actions 2.ts b/src/utils/sent-record-actions 2.ts new file mode 100644 index 0000000..944cbb0 --- /dev/null +++ b/src/utils/sent-record-actions 2.ts @@ -0,0 +1,17 @@ +import type { SentFileRecord } from '@/types' +import { copyRetrieveCode, copyRetrieveLink, copyWgetCommand } from '@/utils/clipboard' +import { buildSentRecordQrValue } from '@/utils/share-url' + +type CopyNotify = (message: string, type: 'success' | 'error') => void + +export function createSentRecordActions(notify: CopyNotify) { + return { + copyLink: (record: SentFileRecord) => + copyRetrieveLink(record.retrieveCode, { notify }), + copyCode: (record: SentFileRecord) => + copyRetrieveCode(record.retrieveCode, { notify }), + copyWgetCommand: (record: SentFileRecord) => + copyWgetCommand(record.retrieveCode, record.filename, { notify }), + getQRCodeValue: (record: SentFileRecord) => buildSentRecordQrValue(record) + } +} diff --git a/src/utils/share-url 2.ts b/src/utils/share-url 2.ts new file mode 100644 index 0000000..b361ab5 --- /dev/null +++ b/src/utils/share-url 2.ts @@ -0,0 +1,38 @@ +import { apiBaseURL } from '@/services/client' + +const getApiOrigin = () => { + if (!apiBaseURL) return window.location.origin + return new URL(apiBaseURL, window.location.origin).origin +} + +export function buildAbsoluteUrl(path: string): string { + if (/^https?:\/\//i.test(path)) { + return path + } + + const normalizedPath = path.startsWith('/') ? path : `/${path}` + return `${getApiOrigin()}${normalizedPath}` +} + +export function buildRetrieveUrl(code: string): string { + return `${window.location.origin}/#/?code=${code}` +} + +export function buildDownloadUrl(downloadUrl: string | null): string { + return downloadUrl ? buildAbsoluteUrl(downloadUrl) : '' +} + +export function buildReceivedRecordQrValue(record: { + code: string + downloadUrl: string | null +}): string { + return record.downloadUrl ? buildDownloadUrl(record.downloadUrl) : buildRetrieveUrl(record.code) +} + +export function buildSentRecordQrValue(record: { retrieveCode: string }): string { + return buildRetrieveUrl(record.retrieveCode) +} + +export function buildWgetCommand(retrieveCode: string, fileName: string): string { + return `wget ${buildAbsoluteUrl(`/share/select?code=${retrieveCode}`)} -O "${fileName}"` +} diff --git a/src/views/RetrievewFileView 2.vue b/src/views/RetrievewFileView 2.vue new file mode 100644 index 0000000..db8ee3e --- /dev/null +++ b/src/views/RetrievewFileView 2.vue @@ -0,0 +1,110 @@ + + + diff --git a/src/views/SendFileView 2.vue b/src/views/SendFileView 2.vue new file mode 100644 index 0000000..068f921 --- /dev/null +++ b/src/views/SendFileView 2.vue @@ -0,0 +1,278 @@ + + + + + diff --git a/src/views/manage/ActivityLogView 2.vue b/src/views/manage/ActivityLogView 2.vue new file mode 100644 index 0000000..c7ff7a8 --- /dev/null +++ b/src/views/manage/ActivityLogView 2.vue @@ -0,0 +1,150 @@ + + + diff --git a/src/views/manage/DashboardView 2.vue b/src/views/manage/DashboardView 2.vue new file mode 100644 index 0000000..21c9438 --- /dev/null +++ b/src/views/manage/DashboardView 2.vue @@ -0,0 +1,694 @@ + + + diff --git a/src/views/manage/FileManageView 2.vue b/src/views/manage/FileManageView 2.vue new file mode 100644 index 0000000..424a57d --- /dev/null +++ b/src/views/manage/FileManageView 2.vue @@ -0,0 +1,2617 @@ + + + + + diff --git a/src/views/manage/LoginView 2.vue b/src/views/manage/LoginView 2.vue new file mode 100644 index 0000000..6324aee --- /dev/null +++ b/src/views/manage/LoginView 2.vue @@ -0,0 +1,230 @@ + + + + + diff --git a/src/views/manage/SystemSettingsView 2.vue b/src/views/manage/SystemSettingsView 2.vue new file mode 100644 index 0000000..4403234 --- /dev/null +++ b/src/views/manage/SystemSettingsView 2.vue @@ -0,0 +1,838 @@ + + + + diff --git a/src/views/manage/TrashView 2.vue b/src/views/manage/TrashView 2.vue new file mode 100644 index 0000000..be14c3d --- /dev/null +++ b/src/views/manage/TrashView 2.vue @@ -0,0 +1,127 @@ + + + diff --git a/src/vite-env.d 2.ts b/src/vite-env.d 2.ts new file mode 100644 index 0000000..7eed4f7 --- /dev/null +++ b/src/vite-env.d 2.ts @@ -0,0 +1,16 @@ +declare module '*.vue' { + import { ComponentOptions } from 'vue' + const componentOptions: ComponentOptions + export default componentOptions +} + +declare module 'vue-router' { + interface RouteMeta { + requiresAuth?: boolean + showGlobalControls?: boolean + showRouteLoading?: boolean + title?: string + } +} + +export {} diff --git a/tailwind.config 2.js b/tailwind.config 2.js new file mode 100644 index 0000000..c02d470 --- /dev/null +++ b/tailwind.config 2.js @@ -0,0 +1,12 @@ +import typography from '@tailwindcss/typography' + +/** @type {import('tailwindcss').Config} */ +export default { + content: ['./index.html', './src/**/*.{vue,js,ts,jsx,tsx}'], + theme: { + extend: {}, + }, + plugins: [ + typography, + ], +} \ No newline at end of file diff --git a/tsconfig.node 2.json b/tsconfig.node 2.json new file mode 100644 index 0000000..f094063 --- /dev/null +++ b/tsconfig.node 2.json @@ -0,0 +1,19 @@ +{ + "extends": "@tsconfig/node20/tsconfig.json", + "include": [ + "vite.config.*", + "vitest.config.*", + "cypress.config.*", + "nightwatch.conf.*", + "playwright.config.*" + ], + "compilerOptions": { + "composite": true, + "noEmit": true, + "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", + + "module": "ESNext", + "moduleResolution": "Bundler", + "types": ["node"] + } +}