✨ feat(core): 实现管理端后台界面及核心功能模块
* 初始化后台管理布局与路由框架 * 新增文件管理、仪表盘、系统设置及日志视图 * 实现文件上传预签名、提取流程及发送记录管理 * 构建常用组件库如模态框、表格、分页及进度条 * 引入多语言支持(中英文)及主题切换功能 * 封装后台业务逻辑 Hooks 和数据持久化存储功能
This commit is contained in:
1 parent
925c6450ac
commit
8badb80600
114 files changed
+18812
No files matched your search
@@ -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'
|
||||
@@ -0,0 +1,13 @@
|
||||
import { ActivityService } from '@/services'
|
||||
import type { AdminActivityListParams, AdminActivityListResponse } from '@/types'
|
||||
|
||||
export function useAdminActivities() {
|
||||
const fetchAdminActivities = async (
|
||||
params: AdminActivityListParams
|
||||
): Promise<AdminActivityListResponse | null> => {
|
||||
const response = await ActivityService.getAdminActivities(params)
|
||||
return response.detail || null
|
||||
}
|
||||
|
||||
return { fetchAdminActivities }
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { TrashService } from '@/services'
|
||||
import type { TrashListParams, TrashListResponse } from '@/types'
|
||||
|
||||
export function useAdminTrash() {
|
||||
const fetchTrash = async (params: TrashListParams): Promise<TrashListResponse | null> => {
|
||||
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 }
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { copyToClipboard as copy } from '@/utils/clipboard'
|
||||
|
||||
export function useClipboard() {
|
||||
const copyToClipboard = (value: string) => copy(value)
|
||||
return { copyToClipboard }
|
||||
}
|
||||
@@ -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<DashboardViewData>(emptyDashboardData())
|
||||
const isLoading = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const lastUpdatedAt = ref<Date | null>(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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { computed, inject, unref } from 'vue'
|
||||
import type { Ref } from 'vue'
|
||||
|
||||
export function useInjectedDarkMode() {
|
||||
const injectedDarkMode = inject<Ref<boolean> | boolean>('isDarkMode', false)
|
||||
return computed(() => Boolean(unref(injectedDarkMode)))
|
||||
}
|
||||
@@ -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<PresignUploadStatus>(PRESIGN_UPLOAD_STATUS.IDLE)
|
||||
const uploadSession = ref<PresignInitResponse | null>(null)
|
||||
const uploadProgress = ref<UploadProgress>({
|
||||
loaded: 0,
|
||||
total: 0,
|
||||
percentage: 0
|
||||
})
|
||||
const uploadedCode = ref<string>('')
|
||||
const errorMessage = ref<string>('')
|
||||
|
||||
// 计算属性
|
||||
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<PresignUploadMode | null>(() => 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<PresignInitResponse | null> => {
|
||||
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<string | null> => {
|
||||
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<string | null> => {
|
||||
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<string | null> => {
|
||||
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<void> => {
|
||||
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<PresignStatusResponse | null> => {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<ShareMetadataResponse | null>(null)
|
||||
const isInspecting = ref(false)
|
||||
const isRetrieving = ref(false)
|
||||
const inputStatus = ref<InputStatus>({
|
||||
readonly: false,
|
||||
loading: false
|
||||
})
|
||||
const error = ref('')
|
||||
const selectedRecord = ref<ReceivedFileRecord | null>(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
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<SendType>('file')
|
||||
const selectedFile = ref<File | null>(null)
|
||||
const selectedFiles = ref<File[]>([])
|
||||
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<SentFileRecord | null>(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
|
||||
}
|
||||
}
|
||||
@@ -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, string | number | undefined>
|
||||
) => 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<ApiResponse> => {
|
||||
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<ApiResponse<{ code?: string; name?: string }>> => {
|
||||
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<ApiResponse | null> => {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<ConfigState>({ ...DEFAULT_CONFIG_STATE })
|
||||
const isRefreshing = ref(false)
|
||||
const isSaving = ref(false)
|
||||
const savedPayloadSnapshot = ref('')
|
||||
const fileSize = ref(1)
|
||||
const sizeUnit = ref<FileSizeUnit>('MB')
|
||||
const saveTime = ref(1)
|
||||
const saveTimeUnit = ref<SaveTimeUnit>('天')
|
||||
|
||||
const isLoading = computed(() => isRefreshing.value || isSaving.value)
|
||||
|
||||
const buildSubmitPayload = (): Partial<ConfigState> => {
|
||||
const payload: Partial<ConfigState> = 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<ConfigState>) => JSON.stringify(payload)
|
||||
|
||||
const normalizeEditableConfig = (nextConfig: Partial<ConfigState>): 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<Partial<ConfigState>>()
|
||||
return storedConfig ? normalizeEditableConfig(storedConfig) : null
|
||||
}
|
||||
|
||||
// 保存配置到本地存储
|
||||
const saveConfigToStorage = (configData: ConfigState) => {
|
||||
configStore.updateConfig(configData)
|
||||
}
|
||||
|
||||
// 获取系统配置
|
||||
const fetchConfig = async (): Promise<ConfigState | null> => {
|
||||
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<ConfigState>): Promise<boolean> => {
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<ThemeMode>(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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StatsService } from '@/services'
|
||||
import type { AnalyticsData } from '@/types'
|
||||
|
||||
export function useTransferAnalytics() {
|
||||
const fetchAnalytics = async (start?: string, end?: string): Promise<AnalyticsData | null> => {
|
||||
const response = await StatsService.getAnalytics(start, end)
|
||||
return response.detail || null
|
||||
}
|
||||
|
||||
return {
|
||||
fetchAnalytics
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user