✨ feat: 合并文件检测、查取件记录及管理界面更新

* 支持单个、勾选和全量手动检测,默认关闭自动读取并提供进度与取消
* 区分查件和下载时间,将查件事件并入可展开的取件记录
* 居中表头并支持拖动列宽,修复筛选收起和仪表盘刷新按钮
* 完善上传进度、分片配置与取消,修正历史文件状态及取件码输入
* 合入已通过单元、集成和测试站浏览器验证的前端改动
This commit is contained in:
orion committed 2026-09-19 01:34:20 +08:00
commit 519aee1d12
57 files changed
+1379 -236

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
.resizable-columns th {
position: relative;
text-align: center;
white-space: nowrap;
}
.column-resize-handle {
position: absolute;
inset: 0 -4px 0 auto;
width: 9px;
z-index: 1;
cursor: col-resize;
touch-action: none;
}
.column-resize-handle::after {
content: '';
position: absolute;
inset: 25% 4px;
background: currentColor;
opacity: 0.25;
}
.column-resize-handle:hover::after,
.column-resize-handle:focus-visible::after {
opacity: 1;
}
.column-resize-handle:focus-visible {
outline: 2px solid currentColor;
outline-offset: -2px;
}
.columns-resizing,
.columns-resizing * {
cursor: col-resize !important;
user-select: none;
}
.columns-sized td {
overflow: hidden;
text-overflow: ellipsis;
}
+3 -1
View File
@@ -20,6 +20,7 @@
</div> </div>
<div class="overflow-x-auto" tabindex="0" role="region" :aria-label="title"> <div class="overflow-x-auto" tabindex="0" role="region" :aria-label="title">
<table <table
v-resizable-columns
class="divide-y" class="divide-y"
:class="[tableClass, isDarkMode ? 'divide-[#495765]' : 'divide-[#d7e3e5]']" :class="[tableClass, isDarkMode ? 'divide-[#495765]' : 'divide-[#d7e3e5]']"
> >
@@ -30,7 +31,7 @@
v-for="header in headers" v-for="header in headers"
:key="header" :key="header"
scope="col" scope="col"
class="px-6 py-3.5 text-left text-xs font-medium uppercase tracking-wider" class="whitespace-nowrap px-6 py-3.5 text-center text-xs font-medium uppercase tracking-wider"
:class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-500']"
> >
{{ header }} {{ header }}
@@ -50,6 +51,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { vResizableColumns } from '@/directives/resizable-columns'
import { inject, useSlots } from 'vue' import { inject, useSlots } from 'vue'
interface Props { interface Props {
+23 -118
View File
@@ -1,110 +1,27 @@
<template> <template>
<transition name="fade"> <BaseModal :show="visible" :title="t('fileDetail.title')" size="md" @close="$emit('close')">
<div <div v-if="record" class="space-y-4 text-sm">
v-if="visible" <div class="flex items-start gap-3">
class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50" <FileIcon class="mt-1 h-5 w-5 shrink-0 opacity-70" aria-hidden="true" />
@click.self="$emit('close')" <div class="min-w-0"><p class="text-xs opacity-70">{{ t('fileRecord.filename') }}</p><p class="mt-1 break-all font-medium leading-6">{{ record.filename }}</p></div>
>
<div
class="fcb-surface w-full max-w-md mx-3 overflow-hidden rounded-[24px] shadow-2xl transform transition-all duration-200 ease-out backdrop-filter backdrop-blur-lg sm:mx-4 sm:rounded-[30px]"
:class="[isDarkMode ? 'bg-gray-800 bg-opacity-70' : 'bg-white bg-opacity-95']"
>
<h3
class="mb-4 truncate px-4 pt-4 text-xl font-bold sm:mb-5 sm:px-6 sm:pt-6 sm:text-2xl"
:class="[isDarkMode ? 'text-white' : 'text-gray-800']"
>
{{ t('fileDetail.title') }}
</h3>
<div class="space-y-3 px-4 sm:space-y-4 sm:px-6" v-if="record">
<div class="flex items-center">
<FileIcon
class="w-6 h-6 mr-3 flex-shrink-0"
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
/>
<p
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
class="truncate flex-grow"
>
<span class="font-medium">{{ t('fileRecord.filename') }}:</span>{{ record.filename }}
</p>
</div> </div>
<div class="flex items-center"> <div class="grid grid-cols-1 gap-4 sm:grid-cols-2">
<CalendarIcon <div class="flex items-start gap-3"><CalendarIcon class="mt-1 h-5 w-5 shrink-0 opacity-70" aria-hidden="true" /><div class="min-w-0"><p class="text-xs opacity-70">{{ t('fileRecord.queryTime') }}</p><p class="mt-1 break-words leading-6">{{ formatRecordTime(queriedAt(record)) }}</p></div></div>
class="w-6 h-6 mr-3 flex-shrink-0" <div class="flex items-start gap-3"><CalendarIcon class="mt-1 h-5 w-5 shrink-0 opacity-70" aria-hidden="true" /><div class="min-w-0"><p class="text-xs opacity-70">{{ t('fileRecord.retrieveTime') }}</p><p class="mt-1 break-words leading-6">{{ formatRecordTime(record.retrievedAt) || t('fileRecord.notRetrieved') }}</p><p class="mt-1 text-xs opacity-70">{{ t('fileRecord.retrieveTimeHint') }}</p></div></div>
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']" <div class="flex items-start gap-3"><HardDriveIcon class="mt-1 h-5 w-5 shrink-0 opacity-70" aria-hidden="true" /><div><p class="text-xs opacity-70">{{ t('fileRecord.size') }}</p><p class="mt-1 leading-6">{{ record.size }}</p></div></div>
/>
<p
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
class="truncate flex-grow"
>
<span class="font-medium">{{ t('fileRecord.date') }}:</span>{{ record.date }}
</p>
</div> </div>
<div class="flex items-center"> <div class="border-t pt-4" :class="isDarkMode ? 'border-gray-700' : 'border-gray-200'">
<HardDriveIcon <BaseButton v-if="record.type === 'text' || typeof record.content === 'string'" @click="$emit('preview-content')">{{ t('fileDetail.previewContent') }}</BaseButton>
class="w-6 h-6 mr-3 flex-shrink-0" <BaseButton v-else @click="$emit('download-record', record)"><DownloadIcon class="mr-2 h-4 w-4" aria-hidden="true" />{{ t('fileDetail.download') }}</BaseButton>
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']"
/>
<p
:class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']"
class="truncate flex-grow"
>
<span class="font-medium">{{ t('fileRecord.size') }}:</span>{{ record.size }}
</p>
</div> </div>
<div class="flex items-center"> <div class="flex flex-col items-center gap-2 rounded-2xl p-4" :class="isDarkMode ? 'bg-gray-900/30' : 'bg-white/40'">
<DownloadIcon <h4 class="font-semibold">{{ t('fileDetail.qrCode') }}</h4>
class="w-6 h-6 mr-3" <div class="rounded-xl bg-white p-2"><QRCode :value="getQRCodeValue(record)" :size="128" level="M" /></div>
:class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']" <p class="text-xs opacity-70">{{ t('fileDetail.scanQrCode') }}</p>
/>
<p :class="[isDarkMode ? 'text-gray-300' : 'text-gray-800']">
<span class="font-medium">{{ t('fileDetail.content') }}:</span>
</p>
<div v-if="record.filename === 'Text'" class="ml-2">
<button
@click="$emit('preview-content')"
class="fcb-action rounded-[30px] bg-indigo-600 px-4 py-2 text-white transition duration-200 hover:bg-indigo-700"
>
{{ t('fileDetail.previewContent') }}
</button>
</div>
<div v-else>
<a
:href="getDownloadUrl(record)"
target="_blank"
rel="noopener noreferrer"
class="rounded-[30px] bg-indigo-600 px-4 py-2 text-white transition duration-200 hover:bg-indigo-700"
>
{{ t('fileDetail.download') }}
</a>
</div> </div>
</div> </div>
</div> <template #footer><BaseButton variant="secondary" @click="$emit('close')">{{ t('common.close') }}</BaseButton></template>
</BaseModal>
<div class="mt-5 flex flex-col items-center px-4 sm:mt-6 sm:px-6" v-if="record">
<h4
class="text-lg font-semibold mb-3"
:class="[isDarkMode ? 'text-white' : 'text-gray-800']"
>
{{ t('fileDetail.qrCode') }}
</h4>
<div class="bg-white p-2 rounded-lg shadow-md">
<QRCode :value="getQRCodeValue(record)" :size="128" level="M" />
</div>
<p class="mt-2 text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']">
{{ t('fileDetail.scanQrCode') }}
</p>
</div>
<button
@click="$emit('close')"
class="fcb-action mt-6 w-full rounded-[30px] bg-gradient-to-r from-indigo-500 to-purple-600 px-5 py-3 font-medium text-white transition duration-200 transform hover:from-indigo-600 hover:to-purple-700 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 sm:mt-8 sm:px-6"
>
{{ t('common.close') }}
</button>
</div>
</div>
</transition>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
@@ -112,8 +29,11 @@ import { defineAsyncComponent, inject } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { FileIcon, CalendarIcon, HardDriveIcon, DownloadIcon } from 'lucide-vue-next' import { FileIcon, CalendarIcon, HardDriveIcon, DownloadIcon } from 'lucide-vue-next'
import BaseModal from './BaseModal.vue'
import BaseButton from './BaseButton.vue'
import type { ReceivedFileRecord } from '@/types' import type { ReceivedFileRecord } from '@/types'
import { buildDownloadUrl, buildReceivedRecordQrValue } from '@/utils/share-url' import { buildReceivedRecordQrValue } from '@/utils/share-url'
import { queriedAt, formatRecordTime } from '@/utils/receive-record'
interface Props { interface Props {
visible: boolean visible: boolean
@@ -123,6 +43,7 @@ interface Props {
interface Emits { interface Emits {
close: [] close: []
'preview-content': [] 'preview-content': []
'download-record': [record: ReceivedFileRecord]
} }
defineProps<Props>() defineProps<Props>()
@@ -131,23 +52,7 @@ const { t } = useI18n()
const isDarkMode = inject('isDarkMode') const isDarkMode = inject('isDarkMode')
const QRCode = defineAsyncComponent(() => import('qrcode.vue')) const QRCode = defineAsyncComponent(() => import('qrcode.vue'))
const getDownloadUrl = (record: ReceivedFileRecord) => {
return buildDownloadUrl(record.downloadUrl)
}
const getQRCodeValue = (record: ReceivedFileRecord) => { const getQRCodeValue = (record: ReceivedFileRecord) => {
return buildReceivedRecordQrValue(record) return buildReceivedRecordQrValue(record)
} }
</script> </script>
<style scoped>
.fade-enter-active,
.fade-leave-active {
transition: opacity 0.2s ease;
}
.fade-enter-from,
.fade-leave-to {
opacity: 0;
}
</style>
+3 -1
View File
@@ -14,7 +14,8 @@
<FileIcon class="h-9 w-9 shrink-0" :class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']" aria-hidden="true" /> <FileIcon class="h-9 w-9 shrink-0" :class="[isDarkMode ? 'text-indigo-400' : 'text-indigo-600']" aria-hidden="true" />
<div class="min-w-0 flex-1"> <div class="min-w-0 flex-1">
<p class="truncate text-base font-medium" :title="record.filename" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">{{ record.filename }}</p> <p class="truncate text-base font-medium" :title="record.filename" :class="[isDarkMode ? 'text-white' : 'text-gray-800']">{{ record.filename }}</p>
<p class="truncate text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']">{{ record.date }} · {{ record.size }}</p> <p class="truncate text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']">{{ t('fileRecord.queryTime') }}:{{ formatRecordTime(queriedAt(record)) }} · {{ record.size }}</p>
<p class="text-sm" :class="[isDarkMode ? 'text-gray-400' : 'text-gray-600']">{{ t('fileRecord.retrieveTime') }}:{{ formatRecordTime(record.retrievedAt) || t('fileRecord.notRetrieved') }}</p>
</div> </div>
</div> </div>
<div class="mt-3 grid grid-cols-3 gap-2"> <div class="mt-3 grid grid-cols-3 gap-2">
@@ -38,6 +39,7 @@ import { computed, inject } from 'vue'
import { FileIcon, EyeIcon, DownloadIcon, TrashIcon } from 'lucide-vue-next' import { FileIcon, EyeIcon, DownloadIcon, TrashIcon } from 'lucide-vue-next'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import type { ReceivedFileRecord } from '@/types' import type { ReceivedFileRecord } from '@/types'
import { queriedAt, formatRecordTime } from '@/utils/receive-record'
defineProps<{ records: ReceivedFileRecord[] }>() defineProps<{ records: ReceivedFileRecord[] }>()
defineEmits<{ 'view-details': [record: ReceivedFileRecord]; 'download-record': [record: ReceivedFileRecord]; 'delete-record': [id: number] }>() defineEmits<{ 'view-details': [record: ReceivedFileRecord]; 'download-record': [record: ReceivedFileRecord]; 'delete-record': [id: number] }>()
+2 -2
View File
@@ -25,7 +25,7 @@
required required
:aria-invalid="error" :aria-invalid="error"
:readonly="inputStatus.readonly" :readonly="inputStatus.readonly"
maxlength="5" maxlength="8"
@focus="isInputFocused = true" @focus="isInputFocused = true"
@blur="isInputFocused = false" @blur="isInputFocused = false"
/> />
@@ -46,7 +46,7 @@
<button <button
type="submit" type="submit"
class="fcb-action fcb-button-primary group relative w-full overflow-hidden rounded-lg bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 px-4 py-3 font-bold text-white transition duration-300 hover:from-indigo-600 hover:via-purple-600 hover:to-pink-600 hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 disabled:cursor-not-allowed disabled:opacity-50 motion-safe:disabled:hover:scale-100" class="fcb-action fcb-button-primary group relative w-full overflow-hidden rounded-lg bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 px-4 py-3 font-bold text-white transition duration-300 hover:from-indigo-600 hover:via-purple-600 hover:to-pink-600 hover:shadow-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 disabled:cursor-not-allowed disabled:opacity-50 motion-safe:disabled:hover:scale-100"
:disabled="inputStatus.loading || code.trim().length !== 5" :disabled="inputStatus.loading || ![5, 8].includes(code.trim().length)"
> >
<span class="flex items-center justify-center relative z-10"> <span class="flex items-center justify-center relative z-10">
<span>{{ inputStatus.loading ? t('common.loading') : t('retrieve.submit') }}</span> <span>{{ inputStatus.loading ? t('common.loading') : t('retrieve.submit') }}</span>
+4 -1
View File
@@ -8,6 +8,9 @@
:id="inputId" :id="inputId"
type="number" type="number"
:value="modelValue" :value="modelValue"
:min="min"
:max="max"
:step="step"
class="min-h-11 w-28 rounded-md border px-4 py-2.5 shadow-sm outline-none transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500" class="min-h-11 w-28 rounded-md border px-4 py-2.5 shadow-sm outline-none transition-all duration-200 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-500"
:class="[ :class="[
isDarkMode isDarkMode
@@ -24,7 +27,7 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, inject } from 'vue' import { computed, inject } from 'vue'
const props = defineProps<{ label: string; modelValue: number; suffix: string }>() const props = defineProps<{ label: string; modelValue: number; suffix: string; min?: number; max?: number; step?: number }>()
const inputId = computed(() => `setting-number-${props.label.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/gi, '-')}`) const inputId = computed(() => `setting-number-${props.label.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fa5]+/gi, '-')}`)
const isDarkMode = inject('isDarkMode') const isDarkMode = inject('isDarkMode')
const emit = defineEmits<{ 'update:modelValue': [value: number] }>() const emit = defineEmits<{ 'update:modelValue': [value: number] }>()
@@ -0,0 +1,21 @@
<template>
<div class="space-y-1" role="status">
<span class="inline-flex items-center rounded-full px-2 py-1 text-xs font-medium" :class="badgeClass">
<RefreshCw v-if="result.status === 'checking'" class="mr-1 h-3 w-3 animate-spin" />
{{ labels[result.status] }}
</span>
<div v-if="result.checkedAt" class="whitespace-nowrap text-xs opacity-60">{{ new Date(result.checkedAt).toLocaleString() }}</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { RefreshCw } from 'lucide-vue-next'
import type { DownloadCheck } from '@/types/download-check'
const props = defineProps<{ result: DownloadCheck; dark: boolean }>()
const labels = { available: '可下载', unavailable: '不可下载', unknown: '未检测', checking: '检测中' }
const badgeClass = computed(() => {
if (props.result.status === 'available') return props.dark ? 'bg-emerald-900/40 text-emerald-200' : 'bg-emerald-50 text-emerald-800'
if (props.result.status === 'unavailable') return props.dark ? 'bg-red-900/40 text-red-200' : 'bg-red-50 text-red-800'
return props.dark ? 'bg-gray-700 text-gray-200' : 'bg-gray-100 text-gray-700'
})
</script>
+2
View File
@@ -16,3 +16,5 @@ export { useTheme } from './useTheme'
export { useTransferAnalytics } from './useTransferAnalytics' export { useTransferAnalytics } from './useTransferAnalytics'
export { useLocalFiles } from './useLocalFiles' export { useLocalFiles } from './useLocalFiles'
export { useDownloadChecks } from './useDownloadChecks'
+2 -2
View File
@@ -651,7 +651,7 @@ export function useAdminFiles() {
if (numericValue !== null) return t('fileManage.remaining', { count: numericValue }) if (numericValue !== null) return t('fileManage.remaining', { count: numericValue })
} }
if ((item.key === 'retrieved' || item.key === 'retrieved_event') && hasNumericTimelineValue(item)) { if ((item.key === 'retrieved' || item.key === 'retrieved_event' || item.key === 'queried_event') && hasNumericTimelineValue(item)) {
return `${normalizeTimelineNumber(item.value)} ${t('common.times')}` return `${normalizeTimelineNumber(item.value)} ${t('common.times')}`
} }
@@ -673,7 +673,7 @@ export function useAdminFiles() {
} }
const formatTimelineTitleValue = (item: AdminFileDetailTimelineItem, valueText: string) => { const formatTimelineTitleValue = (item: AdminFileDetailTimelineItem, valueText: string) => {
if (item.key === 'retrieved_event') { if (item.key === 'retrieved_event' || item.key === 'queried_event') {
const numericValue = normalizeTimelineNumber(item.value) const numericValue = normalizeTimelineNumber(item.value)
return numericValue === null ? '' : String(numericValue) return numericValue === null ? '' : String(numericValue)
} }
+124
View File
@@ -0,0 +1,124 @@
import { onScopeDispose, ref, type Ref } from 'vue'
import { DownloadCheckService, ConfigService } from '@/services'
import type { DownloadCheck } from '@/types/download-check'
export function useDownloadChecks(files: Ref<{ id: number }[]>) {
const checks = ref<Record<number, DownloadCheck>>({})
const interval = ref(0)
const saving = ref(false)
const error = ref('')
const checking = ref(false)
const progress = ref({ completed: 0, total: 0 })
const progressText = ref('')
let controller: AbortController | undefined
let timer: ReturnType<typeof setTimeout> | undefined
let disposed = false
const statusFor = (id: number): DownloadCheck => checks.value[id] ?? {
id, status: 'unknown', message: '尚未检测', checkedAt: null
}
const schedule = () => {
clearTimeout(timer)
if (!disposed && interval.value > 0) timer = setTimeout(() => {
if (typeof document !== 'undefined' && document.hidden) schedule()
else void refresh()
}, interval.value * 1000)
}
const cancel = () => {
controller?.abort()
controller = undefined
for (const [id, result] of Object.entries(checks.value)) {
if (result.status === 'checking') checks.value[Number(id)] = {
...result, status: 'unknown', message: '检测已取消'
}
}
if (checking.value) progressText.value = '已取消'
checking.value = false
schedule()
}
const run = async (requestedIds?: number[]) => {
if (checking.value || disposed) return
const current = new AbortController()
controller = current
clearTimeout(timer)
checking.value = true
error.value = ''
progress.value = { completed: 0, total: 0 }
progressText.value = requestedIds ? '检测中' : '正在读取全部文件'
const isCurrent = () => controller === current && !current.signal.aborted && !disposed
try {
let ids = requestedIds
if (!ids) {
const response = await DownloadCheckService.listIds(current.signal)
if (!isCurrent()) return
if (response.code !== 200 || !Array.isArray(response.detail)) throw new Error('无法读取全部文件')
ids = response.detail
}
ids = [...new Set(ids)]
progress.value.total = ids.length
progressText.value = '检测中'
// A single file per request limits each run to one active storage read.
for (const id of ids) {
if (!isCurrent()) return
checks.value[id] = { ...statusFor(id), status: 'checking', message: '正在检测' }
try {
const response = await DownloadCheckService.check([id], current.signal)
if (!isCurrent()) return
if (response.code !== 200 || !Array.isArray(response.detail)) throw new Error('检测请求失败')
checks.value[id] = response.detail.find(item => item.id === id) ?? {
id, status: 'unknown', message: '未返回检测结果,请重试', checkedAt: null
}
} catch {
if (!isCurrent()) return
checks.value[id] = { id, status: 'unknown', message: '检测请求失败,请重试', checkedAt: null }
}
progress.value.completed++
}
progressText.value = ids.length ? '检测完成' : '没有可检测的文件'
} catch {
if (isCurrent()) {
error.value = '无法读取全部文件,请重试'
progressText.value = '检测未开始'
}
} finally {
if (isCurrent()) {
controller = undefined
checking.value = false
schedule()
}
}
}
const refresh = () => run(files.value.map(file => file.id))
const checkIds = (ids: number[]) => run(ids)
const checkAll = () => run()
const loadInterval = async () => {
try {
const response = await ConfigService.getConfig()
if (response.code !== 200) throw new Error('config failed')
if (!disposed) {
interval.value = response.detail?.downloadCheckInterval ?? 0
if (!checking.value) schedule()
}
} catch { error.value = '无法读取检测间隔,请手动检测' }
}
const saveInterval = async (value: number) => {
if (saving.value) return
saving.value = true
error.value = ''
try {
const response = await ConfigService.updateConfig({ downloadCheckInterval: value })
if (response.code !== 200) throw new Error('save failed')
interval.value = value
if (!checking.value) schedule()
} catch { error.value = '检测间隔保存失败,请重试' }
finally { saving.value = false }
}
// Loading, refreshing, filtering and paginating the list never initiate checks.
onScopeDispose(() => {
disposed = true
controller?.abort()
clearTimeout(timer)
})
return { checks, interval, saving, error, checking, progress, progressText, statusFor,
refresh, checkIds, checkAll, cancel, loadInterval, saveInterval }
}
+9 -3
View File
@@ -141,11 +141,14 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
if (response.code === 200 && response.detail) { if (response.code === 200 && response.detail) {
uploadSession.value = response.detail uploadSession.value = response.detail
options?.onSession?.(response.detail.upload_id)
options?.signal?.throwIfAborted()
return response.detail return response.detail
} else { } else {
throw new Error(response.message || '初始化上传失败') throw new Error(response.message || '初始化上传失败')
} }
} catch (error) { } catch (error) {
if (options?.signal?.aborted) throw error
handleUploadError(error) handleUploadError(error)
return null return null
} }
@@ -167,7 +170,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
const uploadSuccess = await PresignUploadService.directUploadToS3( const uploadSuccess = await PresignUploadService.directUploadToS3(
session.upload_url, session.upload_url,
file, file,
progressHandler progressHandler, options?.signal
) )
if (!uploadSuccess) { if (!uploadSuccess) {
@@ -175,11 +178,12 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
} }
// 确认上传 // 确认上传
options?.signal?.throwIfAborted()
presignStatus.value = PRESIGN_UPLOAD_STATUS.CONFIRMING presignStatus.value = PRESIGN_UPLOAD_STATUS.CONFIRMING
const confirmResponse = await PresignUploadService.confirmUpload(session.upload_id, { const confirmResponse = await PresignUploadService.confirmUpload(session.upload_id, {
expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE, expire_value: options?.expireValue ?? DEFAULT_EXPIRE_VALUE,
expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE expire_style: options?.expireStyle ?? DEFAULT_EXPIRE_STYLE
}) }, options?.signal)
if (confirmResponse.code === 200 && confirmResponse.detail?.code) { if (confirmResponse.code === 200 && confirmResponse.detail?.code) {
presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS presignStatus.value = PRESIGN_UPLOAD_STATUS.SUCCESS
@@ -196,6 +200,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
throw new Error(confirmResponse.message || '确认上传失败') throw new Error(confirmResponse.message || '确认上传失败')
} }
} catch (error) { } catch (error) {
if (options?.signal?.aborted) throw error
handleUploadError(error) handleUploadError(error)
return null return null
} }
@@ -219,7 +224,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
session.upload_id, session.upload_id,
file, file,
progressHandler, progressHandler,
uploadUrl uploadUrl, options?.signal
) )
if (response.code === 200 && response.detail?.code) { if (response.code === 200 && response.detail?.code) {
@@ -237,6 +242,7 @@ export function usePresignedUpload(options: UsePresignedUploadOptions = {}) {
throw new Error(response.message || '代理上传失败') throw new Error(response.message || '代理上传失败')
} }
} catch (error) { } catch (error) {
if (options?.signal?.aborted) throw error
handleUploadError(error) handleUploadError(error)
return null return null
} }
+11 -4
View File
@@ -9,6 +9,7 @@ import { copyToClipboard } from '@/utils/clipboard'
import { getErrorMessage } from '@/utils/common' import { getErrorMessage } from '@/utils/common'
import { renderMarkdownPreview } from '@/utils/content-preview' import { renderMarkdownPreview } from '@/utils/content-preview'
import { downloadReceivedRecord } from '@/utils/download-action' import { downloadReceivedRecord } from '@/utils/download-action'
import { markRecordRetrieved } from '@/utils/receive-record'
type InputStatus = { type InputStatus = {
readonly: boolean readonly: boolean
@@ -36,7 +37,7 @@ export function useRetrieveFlow() {
const renderedContent = ref('') const renderedContent = ref('')
const normalizedCode = computed(() => code.value.trim()) const normalizedCode = computed(() => code.value.trim())
const isWorking = computed(() => isInspecting.value || isRetrieving.value) const isWorking = computed(() => isInspecting.value || isRetrieving.value)
const hasValidCode = computed(() => normalizedCode.value.length === 5) const hasValidCode = computed(() => [5, 8].includes(normalizedCode.value.length))
const formatFileSize = (bytes: number) => { const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 ' + t('fileSize.bytes') if (bytes === 0) return '0 ' + t('fileSize.bytes')
@@ -60,8 +61,9 @@ export function useRetrieveFlow() {
? detail.type === 'text' ? detail.type === 'text'
: detail.name === 'Text' && !detail.text.startsWith('/share/download') : detail.name === 'Text' && !detail.text.startsWith('/share/download')
const content = isText ? (detail.content ?? detail.text) : null const content = isText ? (detail.content ?? detail.text) : null
const downloadUrl = isText ? null : (detail.download_url ?? detail.text) const downloadUrl = detail.download_url ?? (isText ? null : detail.text)
const queriedAt = new Date().toISOString()
return { return {
id: Date.now(), id: Date.now(),
code: detail.code, code: detail.code,
@@ -69,7 +71,9 @@ export function useRetrieveFlow() {
size: formatFileSize(detail.size), size: formatFileSize(detail.size),
downloadUrl, downloadUrl,
content, content,
date: new Date().toLocaleString(), date: queriedAt,
queriedAt,
retrievedAt: null,
type: isText ? 'text' : 'file', type: isText ? 'text' : 'file',
remainingDownloads: detail.remaining_downloads remainingDownloads: detail.remaining_downloads
} }
@@ -130,6 +134,7 @@ export function useRetrieveFlow() {
(file) => file.code === newFileData.code (file) => file.code === newFileData.code
) )
if (existingIndex !== -1) { if (existingIndex !== -1) {
newFileData.retrievedAt = fileStore.receiveData[existingIndex].retrievedAt ?? null
fileStore.deleteReceiveData(existingIndex) fileStore.deleteReceiveData(existingIndex)
} }
fileStore.addReceiveData(newFileData) fileStore.addReceiveData(newFileData)
@@ -186,7 +191,9 @@ export function useRetrieveFlow() {
} }
const downloadRecord = (record: ReceivedFileRecord) => { const downloadRecord = (record: ReceivedFileRecord) => {
downloadReceivedRecord(record) if (downloadReceivedRecord(record)) {
markRecordRetrieved(record)
}
} }
const showContentPreview = () => { const showContentPreview = () => {
+39 -4
View File
@@ -27,9 +27,14 @@ export function useSendFlow() {
const expirationMethod = ref(config.value.expireStyle[0] || 'day') const expirationMethod = ref(config.value.expireStyle[0] || 'day')
const expirationValue = ref('1') const expirationValue = ref('1')
const uploadProgress = ref(0) const uploadProgress = ref(0)
const uploadedBytes = ref(0)
const totalBytes = ref(0)
const showDrawer = ref(false) const showDrawer = ref(false)
const selectedRecord = ref<SentFileRecord | null>(null) const selectedRecord = ref<SentFileRecord | null>(null)
const isSubmitting = ref(false) const isSubmitting = ref(false)
const isCancelling = ref(false)
const cleanupPending = ref(false)
const submitMessage = ref('')
const isFinalizing = ref(false) const isFinalizing = ref(false)
const fileHash = ref('') const fileHash = ref('')
const sendRecords = computed(() => fileDataStore.shareData) const sendRecords = computed(() => fileDataStore.shareData)
@@ -57,12 +62,15 @@ export function useSendFlow() {
alertStore.showAlert(message, type) alertStore.showAlert(message, type)
} }
const sentRecordActions = createSentRecordActions(notifyCopyResult) const sentRecordActions = createSentRecordActions(notifyCopyResult)
const { resetPresignUpload, submitFile, submitText } = useSendSubmit({ const { requestCancel, needsCleanup, retryCleanup, isUploadInterrupted, resetPresignUpload, submitFile, submitText } = useSendSubmit({
getMaxFileSize: () => configStore.uploadSizeLimit, getMaxFileSize: () => configStore.uploadSizeLimit,
getChunkSizeMB: () => config.value.chunkSizeMB,
notify: (message, type) => alertStore.showAlert(message, type), notify: (message, type) => alertStore.showAlert(message, type),
translate: t, translate: t,
onProgress: (progress) => { onProgress: (progress) => {
uploadProgress.value = progress uploadProgress.value = progress.percentage
uploadedBytes.value = progress.loaded
totalBytes.value = progress.total
}, },
onFinalizing: () => { isFinalizing.value = true }, onFinalizing: () => { isFinalizing.value = true },
onHashCalculated: (hash) => { onHashCalculated: (hash) => {
@@ -207,8 +215,9 @@ export function useSendFlow() {
} }
const handleSubmit = async () => { const handleSubmit = async () => {
if (isSubmitting.value) return if (isSubmitting.value || cleanupPending.value) return
isSubmitting.value = true isSubmitting.value = true
submitMessage.value = ''
try { try {
if (sendType.value === 'file' && !selectedFile.value && selectedFiles.value.length === 0) { if (sendType.value === 'file' && !selectedFile.value && selectedFiles.value.length === 0) {
@@ -282,14 +291,37 @@ export function useSendFlow() {
throw new Error(t('send.messages.serverError')) throw new Error(t('send.messages.serverError'))
} }
} catch (error: unknown) { } catch (error: unknown) {
alertStore.showAlert(getErrorMessage(error, t('send.messages.sendFailed')), 'error') if (isUploadInterrupted(error)) {
submitMessage.value = error.cleanupPending ? '上传已中断,临时文件将在上传授权到期后自动清理' : '上传已中断,临时分片已清理,可重新发送'
} else {
cleanupPending.value = needsCleanup()
submitMessage.value = cleanupPending.value ? '传输已停止,临时文件清理未完成,请重试中断' : getErrorMessage(error, t('send.messages.sendFailed'))
alertStore.showAlert(submitMessage.value, 'error')
}
} finally { } finally {
uploadProgress.value = 0 uploadProgress.value = 0
uploadedBytes.value = 0
totalBytes.value = 0
isCancelling.value = false
isSubmitting.value = false isSubmitting.value = false
isFinalizing.value = false isFinalizing.value = false
} }
} }
const cancelUpload = async () => {
if (isCancelling.value) return
isCancelling.value = true
requestCancel()
if (isSubmitting.value) return
try {
const result = await retryCleanup()
cleanupPending.value = false
submitMessage.value = result?.detail?.completed ? `文件已上传完成,取件码:${result.detail.code}` : '上传已中断,临时分片已清理'
} catch {
submitMessage.value = '临时文件清理失败,请再次点击重试中断'
} finally { isCancelling.value = false }
}
const toggleDrawer = () => { const toggleDrawer = () => {
showDrawer.value = !showDrawer.value showDrawer.value = !showDrawer.value
} }
@@ -319,9 +351,12 @@ export function useSendFlow() {
expirationMethod, expirationMethod,
expirationValue, expirationValue,
uploadProgress, uploadProgress,
uploadedBytes,
totalBytes,
showDrawer, showDrawer,
selectedRecord, selectedRecord,
isSubmitting, isSubmitting,
isCancelling, cleanupPending, submitMessage, cancelUpload,
isFinalizing, isFinalizing,
sendRecords, sendRecords,
uploadDescription, uploadDescription,
+30 -6
View File
@@ -1,4 +1,4 @@
import { FileService, uploadChunkedFile } from '@/services' import { FileService, PresignUploadService, uploadChunkedFile, UploadCancellation, UploadInterrupted, isUploadInterrupted } from '@/services'
import type { AlertType, ApiResponse, ExpireStyle, UploadProgress } from '@/types' import type { AlertType, ApiResponse, ExpireStyle, UploadProgress } from '@/types'
import { calculateFileHash, packFilesAsZip } from '@/utils/file-processing' import { calculateFileHash, packFilesAsZip } from '@/utils/file-processing'
import { usePresignedUpload } from './usePresignedUpload' import { usePresignedUpload } from './usePresignedUpload'
@@ -10,9 +10,10 @@ type Translate = (
type UseSendSubmitOptions = { type UseSendSubmitOptions = {
getMaxFileSize: () => number getMaxFileSize: () => number
getChunkSizeMB: () => number
notify: (message: string, type: AlertType) => void notify: (message: string, type: AlertType) => void
translate: Translate translate: Translate
onProgress: (progress: number) => void onProgress: (progress: UploadProgress) => void
onFinalizing: () => void onFinalizing: () => void
onHashCalculated: (hash: string) => void onHashCalculated: (hash: string) => void
} }
@@ -33,6 +34,10 @@ type SubmitTextOptions = {
} }
export function useSendSubmit(options: UseSendSubmitOptions) { export function useSendSubmit(options: UseSendSubmitOptions) {
let active: UploadCancellation | undefined
const requestCancel = () => active?.request()
const needsCleanup = () => Boolean(active?.signal.aborted && active.needsCleanup)
const retryCleanup = async () => active?.clean()
const { uploadFile: presignUploadFile, reset: resetPresignUpload } = usePresignedUpload({ const { uploadFile: presignUploadFile, reset: resetPresignUpload } = usePresignedUpload({
getMaxFileSize: options.getMaxFileSize, getMaxFileSize: options.getMaxFileSize,
notify: options.notify notify: options.notify
@@ -46,10 +51,12 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
return uploadChunkedFile(file, { return uploadChunkedFile(file, {
expireValue, expireValue,
expireStyle, expireStyle,
cancellation: active,
chunkSizeMB: options.getChunkSizeMB(),
onHashCalculated: options.onHashCalculated, onHashCalculated: options.onHashCalculated,
onFinalizing: options.onFinalizing, onFinalizing: options.onFinalizing,
onProgress: (progress: UploadProgress) => { onProgress: (progress: UploadProgress) => {
options.onProgress(progress.percentage) options.onProgress(progress)
}, },
messages: { messages: {
initFailed: options.translate('send.messages.initChunkUploadFailed'), initFailed: options.translate('send.messages.initChunkUploadFailed'),
@@ -67,8 +74,10 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
const code = await presignUploadFile(file, { const code = await presignUploadFile(file, {
expireValue, expireValue,
expireStyle: expireStyle as ExpireStyle, expireStyle: expireStyle as ExpireStyle,
signal: active?.signal,
onSession: (uploadId) => active?.register(() => PresignUploadService.cancelUpload(uploadId)),
onProgress: (progress) => { onProgress: (progress) => {
options.onProgress(progress.percentage) options.onProgress(progress)
} }
}) })
@@ -93,7 +102,11 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
enableChunk, enableChunk,
validateFileSize validateFileSize
}: SubmitFileOptions): Promise<ApiResponse | null> => { }: SubmitFileOptions): Promise<ApiResponse | null> => {
if (needsCleanup()) throw new Error('请先重试中断并清理上次上传')
const operation = new UploadCancellation()
active = operation
let fileToUpload = selectedFile let fileToUpload = selectedFile
try {
if (selectedFiles.length > 0) { if (selectedFiles.length > 0) {
options.notify('正在打包文件...', 'success') options.notify('正在打包文件...', 'success')
@@ -108,15 +121,26 @@ export function useSendSubmit(options: UseSendSubmitOptions) {
throw new Error(options.translate('send.messages.selectFile')) throw new Error(options.translate('send.messages.selectFile'))
} }
return enableChunk operation.check()
options.onProgress({ loaded:0,total:fileToUpload.size,percentage:0 })
const result = await (enableChunk
? handleChunkUpload(fileToUpload, expireValue, expireStyle) ? handleChunkUpload(fileToUpload, expireValue, expireStyle)
: handlePresignedUpload(fileToUpload, expireValue, expireStyle) : handlePresignedUpload(fileToUpload, expireValue, expireStyle))
operation.clear()
return result
} catch (error) {
if (!operation.signal.aborted || isUploadInterrupted(error)) throw error
const cleanup = await operation.clean()
if (cleanup?.detail?.completed && cleanup.detail.code) return cleanup
throw new UploadInterrupted(Boolean(cleanup?.detail?.cleanup_pending))
}
} }
const submitText = ({ text, expireValue, expireStyle }: SubmitTextOptions) => const submitText = ({ text, expireValue, expireStyle }: SubmitTextOptions) =>
FileService.uploadText(text, expireValue, expireStyle) FileService.uploadText(text, expireValue, expireStyle)
return { return {
requestCancel, needsCleanup, retryCleanup, isUploadInterrupted,
resetPresignUpload, resetPresignUpload,
submitFile, submitFile,
submitText submitText
+5
View File
@@ -161,6 +161,11 @@ export function useSystemConfig() {
return Promise.resolve(false) return Promise.resolve(false)
} }
const size = config.value.chunkSizeMB
if (!Number.isInteger(size) || size < 1 || size > 100) {
alertStore.showAlert('分片大小必须是 1–100 MB 的整数', 'error')
return Promise.resolve(false)
}
return updateConfig(buildSubmitPayload()) return updateConfig(buildSubmitPayload())
} }
+114
View File
@@ -0,0 +1,114 @@
import type { ObjectDirective } from 'vue'
import { resizeColumn } from '../utils/column-width'
import '../assets/style/resizable-columns.css'
const states = new WeakMap<HTMLTableElement, { cleanup: () => void; signature: () => boolean }>()
function mount(table: HTMLTableElement) {
const view = table.ownerDocument.defaultView!
const headers = Array.from(table.querySelectorAll<HTMLTableCellElement>('thead th'))
const labels = headers.map(header => header.textContent?.trim() || '')
const handles: HTMLElement[] = []
let stopDrag = () => {}
table.classList.add('resizable-columns')
function measure() {
return headers.map(header => header.getBoundingClientRect().width)
}
function minimum(header: HTMLTableCellElement) {
const range = table.ownerDocument.createRange()
range.selectNodeContents(header)
// Keep the label and padding visible even when the data column is narrowed.
const labelWidth = Array.from(range.getClientRects()).reduce((max, rect) => Math.max(max, rect.width), 0)
const style = view.getComputedStyle(header)
return Math.ceil(Math.max(72, labelWidth + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight)))
}
function apply(widths: number[]) {
table.style.tableLayout = 'fixed'
table.style.minWidth = '0'
table.style.width = `${widths.reduce((sum, width) => sum + width, 0)}px`
table.classList.add('columns-sized')
headers.forEach((header, index) => {
header.style.width = `${widths[index]}px`
handles[index]!.setAttribute('aria-valuenow', String(Math.round(widths[index]!)))
})
}
headers.forEach((header, index) => {
const handle = table.ownerDocument.createElement('span')
handle.className = 'column-resize-handle'
handle.tabIndex = 0
handle.setAttribute('role', 'separator')
handle.setAttribute('aria-orientation', 'vertical')
header.setAttribute('aria-label', labels[index]!)
handle.setAttribute('aria-label', `${labels[index]} — ↔`)
handle.setAttribute('aria-valuenow', String(Math.round(header.getBoundingClientRect().width)))
header.append(handle)
handles.push(handle)
handle.onpointerdown = event => {
if (event.button !== 0) return
event.preventDefault()
event.stopPropagation()
stopDrag()
const widths = measure()
const min = minimum(header)
const startX = event.clientX
const pointerId = event.pointerId
handle.setPointerCapture(pointerId)
table.classList.add('columns-resizing')
const move = (event: PointerEvent) => {
if (event.pointerId === pointerId) apply(resizeColumn(widths, index, event.clientX - startX, min))
}
const finish = (event: PointerEvent) => {
if (event.pointerId === pointerId) stopDrag()
}
stopDrag = () => {
view.removeEventListener('pointermove', move)
view.removeEventListener('pointerup', finish)
view.removeEventListener('pointercancel', finish)
view.removeEventListener('blur', stopDrag)
handle.removeEventListener('lostpointercapture', finish)
if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId)
table.classList.remove('columns-resizing')
stopDrag = () => {}
}
view.addEventListener('pointermove', move)
view.addEventListener('pointerup', finish)
view.addEventListener('pointercancel', finish)
view.addEventListener('blur', stopDrag)
handle.addEventListener('lostpointercapture', finish)
}
handle.onkeydown = event => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return
event.preventDefault()
apply(resizeColumn(measure(), index, event.key === 'ArrowRight' ? 16 : -16, minimum(header)))
}
})
states.set(table, { signature: () => {
const current = Array.from(table.querySelectorAll('thead th'))
return current.length === headers.length && current.every((header, index) =>
header === headers[index] && header.textContent?.trim() === labels[index] && handles[index]?.isConnected)
}, cleanup: () => {
stopDrag()
handles.forEach(handle => handle.remove())
headers.forEach(header => header.removeAttribute('aria-label'))
} })
}
export const vResizableColumns: ObjectDirective<HTMLTableElement> = {
mounted: mount,
updated(table) {
const state = states.get(table)
if (!state?.signature()) {
state?.cleanup()
mount(table)
}
},
beforeUnmount(table) {
states.get(table)?.cleanup()
states.delete(table)
}
}
+11 -3
View File
@@ -406,7 +406,11 @@ export default {
fileRecord: { fileRecord: {
filename: 'Filename', filename: 'Filename',
size: 'Size', size: 'Size',
date: 'Date', date: 'Lookup time',
queryTime: 'Lookup time',
retrieveTime: 'Retrieval time',
notRetrieved: 'Not retrieved yet',
retrieveTimeHint: 'Most recent download click; does not indicate completion.',
code: 'Code', code: 'Code',
actions: 'Actions', actions: 'Actions',
download: 'Download', download: 'Download',
@@ -666,13 +670,17 @@ export default {
title: 'Retrieval History', title: 'Retrieval History',
description: 'Retrieved {value}; current status is {status}.' description: 'Retrieved {value}; current status is {status}.'
}, },
queried_event: {
title: 'Lookup #{value}',
description: 'Lookup succeeded. Source IP: {detail}.'
},
retrieved_event: { retrieved_event: {
title: 'Retrieval #{value}', title: 'Retrieval #{value}',
description: 'This retrieval is complete; current status is {status}.' description: 'Retrieval started; this does not indicate download completion.'
}, },
retrieved_event_unknown: { retrieved_event_unknown: {
title: 'Retrieval History', title: 'Retrieval History',
description: 'This retrieval is complete; current status is {status}.' description: 'Retrieval started; this does not indicate download completion.'
} }
}, },
headers: { headers: {
+12 -4
View File
@@ -581,7 +581,7 @@ export default {
lifecycle: '生命周期', lifecycle: '生命周期',
expandLifecycle: '展开全部生命周期记录(共 {count} 条)', expandLifecycle: '展开全部生命周期记录(共 {count} 条)',
collapseLifecycle: '收起生命周期记录', collapseLifecycle: '收起生命周期记录',
expandRetrievalHistory: '展开全部取件记录(共 {count} 次)', expandRetrievalHistory: '展开全部取件记录(共 {count} 条)',
collapseRetrievalHistory: '收起取件记录', collapseRetrievalHistory: '收起取件记录',
permanent: '永久有效', permanent: '永久有效',
createdAt: '创建时间', createdAt: '创建时间',
@@ -662,13 +662,17 @@ export default {
title: '取件记录', title: '取件记录',
description: '累计取件 {value},当前状态为 {status}。' description: '累计取件 {value},当前状态为 {status}。'
}, },
queried_event: {
title: '第 {value} 次查件',
description: '查件成功,来源 IP:{detail}。'
},
retrieved_event: { retrieved_event: {
title: '第 {value} 次取件', title: '第 {value} 次取件',
description: '本次取件已完成,当前状态为 {status}。' description: '已发起取件,不代表下载完成。'
}, },
retrieved_event_unknown: { retrieved_event_unknown: {
title: '取件记录', title: '取件记录',
description: '本次取件已完成,当前状态为 {status}。' description: '已发起取件,不代表下载完成。'
} }
}, },
headers: { headers: {
@@ -709,7 +713,11 @@ export default {
fileRecord: { fileRecord: {
filename: '文件名', filename: '文件名',
size: '文件大小', size: '文件大小',
date: '取件日期', date: '查件时间',
queryTime: '查件时间',
retrieveTime: '取件时间',
notRetrieved: '尚未取件',
retrieveTimeHint: '最近一次点击下载的时间,不代表下载完成。',
code: '取件码', code: '取件码',
actions: '操作', actions: '操作',
download: '下载', download: '下载',
+12
View File
@@ -0,0 +1,12 @@
import api from './client'
import type { ApiResponse } from '@/types'
import type { DownloadCheck } from '@/types/download-check'
export const DownloadCheckService = {
listIds(signal?: AbortSignal): Promise<ApiResponse<number[]>> {
return api.get('/admin/file/download-check-ids', { signal })
},
check(ids: number[], signal?: AbortSignal): Promise<ApiResponse<DownloadCheck[]>> {
return api.post('/admin/file/download-check', { ids }, { signal, timeout: 70000 })
}
}
+10 -25
View File
@@ -87,33 +87,18 @@ export class FileService {
) )
} }
static async uploadChunk( static async uploadChunk(uploadId: string, chunkIndex: number, chunk: Blob, onProgress?: (progress: UploadProgress) => void, signal?: AbortSignal): Promise<ApiResponse<ChunkUploadResponse>> {
uploadId: string, return api.post(`/chunk/upload/raw/${uploadId}/${chunkIndex}`, chunk, {
chunkIndex: number, ...multipartUploadConfig(onProgress), headers: { 'Content-Type': 'application/octet-stream' }, signal
chunk: Blob, })
onProgress?: (progress: UploadProgress) => void
): Promise<ApiResponse<ChunkUploadResponse>> {
const formData = new FormData()
formData.append('chunk', chunk)
return api.post(
`/chunk/upload/chunk/${uploadId}/${chunkIndex}`,
formData,
multipartUploadConfig(onProgress)
)
} }
static async completeChunkUpload( static async cancelChunkUpload(uploadId: string): Promise<ApiResponse<{ cancelled?: boolean; completed?: boolean; code?: string; name?: string }>> {
uploadId: string, return api.delete(`/chunk/upload/${uploadId}`)
request: ChunkUploadCompleteRequest }
): Promise<ApiResponse<FileUploadResponse>> {
return api.post( static async completeChunkUpload(uploadId: string, request: ChunkUploadCompleteRequest, signal?: AbortSignal): Promise<ApiResponse<FileUploadResponse>> {
`/chunk/upload/complete/${uploadId}`, return api.post(`/chunk/upload/complete/${uploadId}`, toUrlEncodedForm({expire_value:request.expire_value,expire_style:request.expire_style}), {...urlEncodedConfig,signal})
toUrlEncodedForm({
expire_value: request.expire_value,
expire_style: request.expire_style
}),
urlEncodedConfig
)
} }
static async selectFile(code: string): Promise<ApiResponse<ShareSelectResponse>> { static async selectFile(code: string): Promise<ApiResponse<ShareSelectResponse>> {
+4
View File
@@ -9,3 +9,7 @@ export { TrashService } from './trash'
export { uploadChunkedFile } from './upload-strategy' export { uploadChunkedFile } from './upload-strategy'
export { LocalShareService } from './local-share' export { LocalShareService } from './local-share'
export { UploadCancellation, UploadInterrupted, isUploadInterrupted } from './upload-cancellation'
export { DownloadCheckService } from './download-check'
+10 -7
View File
@@ -20,7 +20,8 @@ export class PresignUploadService {
uploadId: string, uploadId: string,
file: File, file: File,
onProgress?: (progress: UploadProgress) => void, onProgress?: (progress: UploadProgress) => void,
uploadUrl?: string uploadUrl?: string,
signal?: AbortSignal
): Promise<ApiResponse<PresignUploadResult>> { ): Promise<ApiResponse<PresignUploadResult>> {
const formData = new FormData() const formData = new FormData()
formData.append('file', file) formData.append('file', file)
@@ -28,31 +29,33 @@ export class PresignUploadService {
return api.put( return api.put(
uploadUrl || `/presign/upload/proxy/${uploadId}`, uploadUrl || `/presign/upload/proxy/${uploadId}`,
formData, formData,
multipartUploadConfig(onProgress) {...multipartUploadConfig(onProgress),signal}
) )
} }
static async confirmUpload( static async confirmUpload(
uploadId: string, uploadId: string,
request?: PresignConfirmRequest request?: PresignConfirmRequest,
signal?: AbortSignal
): Promise<ApiResponse<PresignUploadResult>> { ): Promise<ApiResponse<PresignUploadResult>> {
return api.post(`/presign/upload/confirm/${uploadId}`, request || {}) return api.post(`/presign/upload/confirm/${uploadId}`, request || {}, {signal})
} }
static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> { static async getUploadStatus(uploadId: string): Promise<ApiResponse<PresignStatusResponse>> {
return api.get(`/presign/upload/status/${uploadId}`) return api.get(`/presign/upload/status/${uploadId}`)
} }
static async cancelUpload(uploadId: string): Promise<ApiResponse<{ message: string }>> { static async cancelUpload(uploadId: string): Promise<ApiResponse<{ cancelled?: boolean; completed?: boolean; code?: string; name?: string; message?: string }>> {
return api.delete(`/presign/upload/${uploadId}`) return api.delete(`/presign/upload/${uploadId}`)
} }
static async directUploadToS3( static async directUploadToS3(
uploadUrl: string, uploadUrl: string,
file: File, file: File,
onProgress?: (progress: UploadProgress) => void onProgress?: (progress: UploadProgress) => void,
signal?: AbortSignal
): Promise<boolean> { ): Promise<boolean> {
await uploadToExternalUrl(uploadUrl, file, onProgress) await uploadToExternalUrl(uploadUrl, file, onProgress, signal)
return true return true
} }
} }
+26
View File
@@ -0,0 +1,26 @@
import type { ApiResponse } from '@/types'
export type CancelResult = ApiResponse<{ cancelled?: boolean; cleanup_pending?: boolean; completed?: boolean; code?: string; name?: string }>
export class UploadInterrupted extends Error {
constructor(public readonly cleanupPending = false) { super('上传已中断'); this.name = 'UploadInterrupted' }
}
export class UploadCancellation {
readonly controller = new AbortController()
private cleanup?: () => Promise<CancelResult>
private cleaning?: Promise<CancelResult | undefined>
get signal() { return this.controller.signal }
get needsCleanup() { return Boolean(this.cleanup) }
request() { this.controller.abort() }
check() { if (this.signal.aborted) throw new UploadInterrupted() }
register(cleanup: () => Promise<CancelResult>) { this.cleanup = cleanup }
clear() { this.cleanup = undefined }
async clean(): Promise<CancelResult | undefined> {
if (this.cleaning) return this.cleaning
if (!this.cleanup) return undefined
this.cleaning = this.cleanup().then(result => {
if (result.code !== 200) throw new Error('上传已停止,临时分片清理失败,请重试中断')
this.clear(); return result
}).finally(() => { this.cleaning = undefined })
return this.cleaning
}
}
export function isUploadInterrupted(error: unknown): error is UploadInterrupted { return error instanceof UploadInterrupted }
+3 -1
View File
@@ -4,9 +4,11 @@ import type { UploadProgress } from '@/types'
export async function uploadToExternalUrl( export async function uploadToExternalUrl(
uploadUrl: string, uploadUrl: string,
file: File, file: File,
onProgress?: (progress: UploadProgress) => void onProgress?: (progress: UploadProgress) => void,
signal?: AbortSignal
): Promise<void> { ): Promise<void> {
await axios.put(uploadUrl, file, { await axios.put(uploadUrl, file, {
signal,
headers: { headers: {
'Content-Type': 'application/octet-stream' 'Content-Type': 'application/octet-stream'
}, },
+3 -1
View File
@@ -5,15 +5,17 @@ export function isTransientCompletionError(error: unknown): boolean {
return !failure?.response || [408, 502, 503, 504].includes(failure.response.status || 0) return !failure?.response || [408, 502, 503, 504].includes(failure.response.status || 0)
} }
export async function waitForUploadCompletion<T>(request: () => Promise<ApiResponse<T>>, onFinalizing?: () => void): Promise<ApiResponse<T>> { export async function waitForUploadCompletion<T>(request: () => Promise<ApiResponse<T>>, onFinalizing?: () => void, signal?: AbortSignal): Promise<ApiResponse<T>> {
let announced = false, failures = 0 let announced = false, failures = 0
while (true) { while (true) {
signal?.throwIfAborted()
try { try {
const response = await request() const response = await request()
failures = 0 failures = 0
if (response.code !== 202) return response if (response.code !== 202) return response
if (!announced) { announced = true; onFinalizing?.() } if (!announced) { announced = true; onFinalizing?.() }
} catch (error) { } catch (error) {
signal?.throwIfAborted()
if (!isTransientCompletionError(error) || ++failures >= 4) throw error if (!isTransientCompletionError(error) || ++failures >= 4) throw error
} }
await new Promise(resolve => setTimeout(resolve, Math.min(1000 * (failures || 1), 3000))) await new Promise(resolve => setTimeout(resolve, Math.min(1000 * (failures || 1), 3000)))
+40 -10
View File
@@ -1,11 +1,14 @@
import { FileService } from './file' import { FileService } from './file'
import { UploadCancellation, UploadInterrupted } from './upload-cancellation'
import { waitForUploadCompletion, isTransientCompletionError } from './upload-completion' import { waitForUploadCompletion, isTransientCompletionError } from './upload-completion'
import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types' import type { ApiResponse, ChunkUploadInitResponse, FileUploadResponse, UploadProgress } from '@/types'
import { calculateFileHash } from '@/utils/file-processing' import { calculateFileHash } from '@/utils/file-processing'
const CHUNK_SIZE = 5 * 1024 * 1024 export const CHUNK_SIZE = 90 * 1024 * 1024
type ChunkedUploadOptions = { type ChunkedUploadOptions = {
cancellation?: UploadCancellation
chunkSizeMB?: number
expireValue: number expireValue: number
expireStyle: string expireStyle: string
onFinalizing?: () => void onFinalizing?: () => void
@@ -26,11 +29,12 @@ const pendingCompletion = new WeakMap<File, { uploadId: string; expireValue: num
async function finishUpload(file: File, options: ChunkedUploadOptions): Promise<ApiResponse<ChunkedUploadResult>> { async function finishUpload(file: File, options: ChunkedUploadOptions): Promise<ApiResponse<ChunkedUploadResult>> {
const session = pendingCompletion.get(file)! const session = pendingCompletion.get(file)!
options.onProgress?.({loaded:file.size,total:file.size,percentage:99})
options.onFinalizing?.() options.onFinalizing?.()
try { try {
const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, { const response = await waitForUploadCompletion(() => FileService.completeChunkUpload(session.uploadId, {
expire_value: session.expireValue, expire_style: session.expireStyle expire_value: session.expireValue, expire_style: session.expireStyle
})) }, options.cancellation?.signal), undefined, options.cancellation?.signal)
if (response.code !== 200) throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed') if (response.code !== 200) throw new Error(options.messages?.completeFailed || 'Complete chunk upload failed')
pendingCompletion.delete(file) pendingCompletion.delete(file)
return response return response
@@ -47,19 +51,25 @@ const calculateCompletedBytes = (uploadedChunks: Set<number>, chunkSize: number,
return total + Math.max(0, chunkEnd - chunkStart) return total + Math.max(0, chunkEnd - chunkStart)
}, 0) }, 0)
export const uploadChunkedFile = async ( const runChunkedFile = async (
file: File, file: File,
options: ChunkedUploadOptions options: ChunkedUploadOptions
): Promise<ApiResponse<ChunkedUploadResult>> => { ): Promise<ApiResponse<ChunkedUploadResult>> => {
if (pendingCompletion.has(file)) return finishUpload(file, options) if (pendingCompletion.has(file)) {
const previous = pendingCompletion.get(file)!
options.cancellation?.register(() => FileService.cancelChunkUpload(previous.uploadId))
options.cancellation?.check()
return finishUpload(file, options)
}
options.cancellation?.check()
const fileHash = await calculateFileHash(file) const fileHash = await calculateFileHash(file)
options.cancellation?.check()
options.onHashCalculated?.(fileHash) options.onHashCalculated?.(fileHash)
const chunks = Math.ceil(file.size / CHUNK_SIZE)
const initResponse = await FileService.initChunkUpload({ const initResponse = await FileService.initChunkUpload({
file_name: file.name, file_name: file.name,
file_size: file.size, file_size: file.size,
chunk_size: CHUNK_SIZE, chunk_size: Math.min((Number.isInteger(options.chunkSizeMB) && options.chunkSizeMB! >= 1 && options.chunkSizeMB! <= 100 ? options.chunkSizeMB! * 1024 * 1024 : CHUNK_SIZE), file.size),
file_hash: fileHash file_hash: fileHash
}) })
@@ -77,28 +87,34 @@ export const uploadChunkedFile = async (
throw new Error(options.messages?.initFailed || 'Init chunk upload failed') throw new Error(options.messages?.initFailed || 'Init chunk upload failed')
} }
options.cancellation?.register(() => FileService.cancelChunkUpload(uploadId))
options.cancellation?.check()
const chunkSize = initDetail.chunk_size || CHUNK_SIZE
const chunks = Math.ceil(file.size / chunkSize)
const uploadedChunks = new Set(initDetail.uploaded_chunks || []) const uploadedChunks = new Set(initDetail.uploaded_chunks || [])
options.onProgress?.({loaded:calculateCompletedBytes(uploadedChunks,chunkSize,file.size),total:file.size,percentage:0})
for (let index = 0; index < chunks; index++) { for (let index = 0; index < chunks; index++) {
options.cancellation?.check()
if (uploadedChunks.has(index)) { if (uploadedChunks.has(index)) {
continue continue
} }
const start = index * CHUNK_SIZE const start = index * chunkSize
const end = Math.min(start + CHUNK_SIZE, file.size) const end = Math.min(start + chunkSize, file.size)
const chunk = file.slice(start, end) const chunk = file.slice(start, end)
const chunkResponse = await FileService.uploadChunk( const chunkResponse = await FileService.uploadChunk(
uploadId, uploadId,
index, index,
new Blob([chunk], { type: file.type }), new Blob([chunk], { type: file.type }),
(progress) => { (progress) => {
const completedBytes = calculateCompletedBytes(uploadedChunks, CHUNK_SIZE, file.size) const completedBytes = calculateCompletedBytes(uploadedChunks, chunkSize, file.size)
const percentage = Math.round(((completedBytes + progress.loaded) * 100) / file.size) const percentage = Math.round(((completedBytes + progress.loaded) * 100) / file.size)
options.onProgress?.({ options.onProgress?.({
loaded: completedBytes + progress.loaded, loaded: completedBytes + progress.loaded,
total: file.size, total: file.size,
percentage: Math.min(percentage, 99) percentage: Math.min(percentage, 99)
}) })
} }, options.cancellation?.signal
) )
if (chunkResponse.code !== 200) { if (chunkResponse.code !== 200) {
@@ -110,3 +126,17 @@ export const uploadChunkedFile = async (
pendingCompletion.set(file, { uploadId, expireValue: options.expireValue, expireStyle: options.expireStyle }) pendingCompletion.set(file, { uploadId, expireValue: options.expireValue, expireStyle: options.expireStyle })
return finishUpload(file, options) return finishUpload(file, options)
} }
export async function uploadChunkedFile(file: File, options: ChunkedUploadOptions): Promise<ApiResponse<ChunkedUploadResult>> {
try {
const result = await runChunkedFile(file, options)
options.cancellation?.clear()
return result
} catch (error) {
if (!options.cancellation?.signal.aborted) throw error
pendingCompletion.delete(file)
const cancelled = await options.cancellation.clean()
if (cancelled?.detail?.completed && cancelled.detail.code) return cancelled as ApiResponse<ChunkedUploadResult>
throw new UploadInterrupted()
}
}
+2
View File
@@ -46,6 +46,8 @@ export interface ConfigState {
trashRetentionDays: number trashRetentionDays: number
opacity: number opacity: number
enableChunk: number enableChunk: number
chunkSizeMB: number
downloadCheckInterval?: number
s3_access_key_id: string s3_access_key_id: string
background: string background: string
showAdminAddr: number showAdminAddr: number
+8
View File
@@ -106,6 +106,14 @@ export interface AnalyticsDailyRow {
} }
export interface AnalyticsFileRow { export interface AnalyticsFileRow {
status?: 'active' | 'expired' | 'trashed' | 'purged' | 'deleted' | 'history'
is_trashed?: boolean
is_purged?: boolean
trash_reason?: string
was_restored?: boolean
can_download?: boolean
trashed_at?: string
purged_at?: string
code: string code: string
name: string name: string
size: number | string size: number | string
+6
View File
@@ -0,0 +1,6 @@
export interface DownloadCheck {
id: number
status: 'available' | 'unavailable' | 'unknown' | 'checking'
message: string
checkedAt: string | null
}
+5
View File
@@ -453,7 +453,10 @@ export interface ReceivedFileRecord {
size: string size: string
downloadUrl: string | null downloadUrl: string | null
content: string | null content: string | null
/** Legacy query time, retained for existing records. */
date: string date: string
queriedAt?: string
retrievedAt?: string | null
type?: 'file' | 'text' type?: 'file' | 'text'
remainingDownloads?: number | null remainingDownloads?: number | null
} }
@@ -481,6 +484,8 @@ export interface ChunkUploadInitRequest {
} }
export interface ChunkUploadInitResponse { export interface ChunkUploadInitResponse {
chunk_size?: number
total_chunks?: number
code?: string code?: string
name?: string name?: string
upload_id?: string upload_id?: string
+2
View File
@@ -49,6 +49,8 @@ export interface PresignStatusResponse {
} }
export interface PresignUploadOptions { export interface PresignUploadOptions {
signal?: AbortSignal
onSession?: (uploadId: string) => void
expireValue?: number expireValue?: number
expireStyle?: ExpireStyle expireStyle?: ExpireStyle
onProgress?: (progress: UploadProgress) => void onProgress?: (progress: UploadProgress) => void
+3
View File
@@ -0,0 +1,3 @@
export function resizeColumn(widths: number[], index: number, delta: number, minimum: number): number[] {
return widths.map((width, column) => column === index ? Math.max(minimum, width + delta) : width)
}
+5 -1
View File
@@ -7,6 +7,7 @@ export type PublicConfig = SystemConfig & {
openUpload: number openUpload: number
max_save_seconds: number max_save_seconds: number
enableChunk: number enableChunk: number
chunkSizeMB: number
notify_title?: string notify_title?: string
notify_content?: string notify_content?: string
page_explain?: string page_explain?: string
@@ -22,7 +23,8 @@ export const DEFAULT_PUBLIC_CONFIG: PublicConfig = {
expireStyle: ['day'], expireStyle: ['day'],
openUpload: 1, openUpload: 1,
max_save_seconds: 0, max_save_seconds: 0,
enableChunk: 0 enableChunk: 0,
chunkSizeMB: 90
} }
export const DEFAULT_CONFIG_STATE: ConfigState = { export const DEFAULT_CONFIG_STATE: ConfigState = {
@@ -44,6 +46,7 @@ export const DEFAULT_CONFIG_STATE: ConfigState = {
trashRetentionDays: 30, trashRetentionDays: 30,
opacity: 0.9, opacity: 0.9,
enableChunk: DEFAULT_PUBLIC_CONFIG.enableChunk, enableChunk: DEFAULT_PUBLIC_CONFIG.enableChunk,
chunkSizeMB: DEFAULT_PUBLIC_CONFIG.chunkSizeMB,
s3_access_key_id: '', s3_access_key_id: '',
background: '', background: '',
showAdminAddr: 0, showAdminAddr: 0,
@@ -85,6 +88,7 @@ export function toPublicConfig(config: Partial<ConfigState> | null | undefined):
openUpload: config.openUpload, openUpload: config.openUpload,
max_save_seconds: config.max_save_seconds, max_save_seconds: config.max_save_seconds,
enableChunk: config.enableChunk, enableChunk: config.enableChunk,
chunkSizeMB: config.chunkSizeMB ?? DEFAULT_PUBLIC_CONFIG.chunkSizeMB,
notify_title: config.notify_title, notify_title: config.notify_title,
notify_content: config.notify_content, notify_content: config.notify_content,
page_explain: config.page_explain, page_explain: config.page_explain,
+5 -3
View File
@@ -7,16 +7,18 @@ const unsafeFilenamePattern = new RegExp(
'g' 'g'
) )
export function downloadReceivedRecord(record: ReceivedFileRecord): void { export function downloadReceivedRecord(record: ReceivedFileRecord): boolean {
if (record.downloadUrl) { if (record.downloadUrl) {
window.open(buildDownloadUrl(record.downloadUrl), '_blank') window.open(buildDownloadUrl(record.downloadUrl), '_blank')
return return true
} }
if (record.content) { if (typeof record.content === 'string') {
const blob = new Blob([record.content], { type: 'text/plain;charset=utf-8' }) const blob = new Blob([record.content], { type: 'text/plain;charset=utf-8' })
saveAs(blob, `${record.filename}.txt`) saveAs(blob, `${record.filename}.txt`)
return true
} }
return false
} }
export const getSafeFilename = (name: string) => export const getSafeFilename = (name: string) =>
+10
View File
@@ -0,0 +1,10 @@
import type { AnalyticsFileRow } from '@/types'
import { getTrashReasonLabel } from './trashPresentation.ts'
export function getHistoryStatusLabel(file: AnalyticsFileRow): string {
if (file.status === 'purged' || file.is_purged) return '已清理'
if (file.status === 'trashed' || file.is_trashed) return file.trash_reason ? getTrashReasonLabel(file.trash_reason) : '回收站中'
if (file.current || file.status === 'active' || file.status === 'expired') return file.was_restored ? '现存,已从回收站恢复' : '现存'
if (file.deleted) return '已删除'
return '历史'
}
+18
View File
@@ -0,0 +1,18 @@
import type { ReceivedFileRecord } from '../types/file'
/** Legacy date was written on lookup, never on download. */
export function queriedAt(record: ReceivedFileRecord): string {
return record.queriedAt || record.date
}
export function formatRecordTime(value?: string | null): string {
if (!value) return ''
// Old records contain locale-formatted dates; retain them without guessing.
if (!/^\d{4}-\d{2}-\d{2}T/.test(value)) return value
const time = new Date(value)
return Number.isNaN(time.getTime()) ? value : time.toLocaleString()
}
export function markRecordRetrieved(record: ReceivedFileRecord, at = new Date()): void {
record.retrievedAt = at.toISOString()
}
+6 -5
View File
@@ -19,11 +19,7 @@ export function formatTrashTime(value?: string | null, now?: number): string {
} }
export function getTrashPresentation(item: TrashFileItem, now: number) { export function getTrashPresentation(item: TrashFileItem, now: number) {
const reasons: Record<string, string> = { const reason = getTrashReasonLabel(item.trashReason)
manual: '手动删除', batch_delete: '批量删除', expired_time: '保存到期',
expired_count: '次数用尽', expired_both: '到期且次数用尽', expired: '历史自动回收'
}
const reason = item.trashReason ? reasons[item.trashReason] || '其他原因' : '未记录'
if (item.isTrashPurged) return { if (item.isTrashPurged) return {
state: '已清理', tone: 'muted', reason, reminder: '', state: '已清理', tone: 'muted', reason, reminder: '',
@@ -45,3 +41,8 @@ export function getTrashPresentation(item: TrashFileItem, now: number) {
note: valid && remainingMs <= 0 ? '已到清理时间,等待后台处理。' : '' note: valid && remainingMs <= 0 ? '已到清理时间,等待后台处理。' : ''
} }
} }
export function getTrashReasonLabel(reason?: string | null): string {
const labels: Record<string,string> = {manual:'手动删除',batch_delete:'批量删除',expired_time:'保存到期',expired_count:'次数用尽',expired_both:'到期且次数用尽',expired:'历史自动回收'}
return reason ? labels[reason] || '其他原因' : '未记录'
}
+4 -7
View File
@@ -44,6 +44,7 @@
:record="selectedRecord" :record="selectedRecord"
@close="closeDetails" @close="closeDetails"
@preview-content="showContentPreview" @preview-content="showContentPreview"
@download-record="downloadRecord"
/> />
<ContentPreviewModal <ContentPreviewModal
@@ -56,7 +57,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { inject, onMounted, watch } from 'vue' import { inject, onMounted } from 'vue'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
import PageHeader from '@/components/common/PageHeader.vue' import PageHeader from '@/components/common/PageHeader.vue'
@@ -101,13 +102,9 @@ const toSend = () => {
onMounted(() => { onMounted(() => {
const queryCode = route.query.code const queryCode = route.query.code
if (queryCode && typeof queryCode === 'string') { if (queryCode && typeof queryCode === 'string') {
code.value = queryCode code.value = queryCode.trim()
if ([5, 8].includes(code.value.length)) void handleSubmit()
} }
}) })
watch(code, (newCode) => {
if (newCode.length === 5) {
void handleSubmit()
}
})
</script> </script>
+14 -2
View File
@@ -14,10 +14,12 @@
<div class="p-5 sm:p-8"> <div class="p-5 sm:p-8">
<PageHeader :title="config.name" @title-click="toRetrieve" /> <PageHeader :title="config.name" @title-click="toRetrieve" />
<form @submit.prevent="handleSubmit" class="space-y-5 sm:space-y-8"> <form @submit.prevent="handleSubmit" class="space-y-5 sm:space-y-8">
<fieldset :disabled="isSubmitting || cleanupPending">
<SendTypeSelector <SendTypeSelector
:selected-type="sendType" :selected-type="sendType"
@update:selected-type="sendType = $event" @update:selected-type="sendType = $event"
/> />
</fieldset>
<transition name="fade" mode="out-in"> <transition name="fade" mode="out-in">
<div v-if="sendType === 'file'" key="file" class="grid grid-cols-1 gap-8"> <div v-if="sendType === 'file'" key="file" class="grid grid-cols-1 gap-8">
@@ -26,7 +28,9 @@
:selected-file="selectedFile" :selected-file="selectedFile"
:selected-files="selectedFiles" :selected-files="selectedFiles"
:progress="uploadProgress" :progress="uploadProgress"
:disabled="isSubmitting" :uploaded-bytes="uploadedBytes"
:total-bytes="totalBytes"
:disabled="isSubmitting || cleanupPending"
:upload-status="isFinalizing ? 'confirming' : isSubmitting ? 'uploading' : 'idle'" :upload-status="isFinalizing ? 'confirming' : isSubmitting ? 'uploading' : 'idle'"
:description="uploadDescription" :description="uploadDescription"
@file-selected="handleFileSelected" @file-selected="handleFileSelected"
@@ -42,15 +46,17 @@
/> />
</div> </div>
</transition> </transition>
<fieldset :disabled="isSubmitting || cleanupPending">
<ExpirationSelector <ExpirationSelector
v-model:expiration-method="expirationMethod" v-model:expiration-method="expirationMethod"
v-model:expiration-value="expirationValue" v-model:expiration-value="expirationValue"
:options="expirationOptions" :options="expirationOptions"
/> />
</fieldset>
<!-- 提交按钮 --> <!-- 提交按钮 -->
<button <button
type="submit" type="submit"
:disabled="isSubmitting" :disabled="isSubmitting || cleanupPending"
class="fcb-action fcb-button-primary w-full bg-[#7198a6] text-white font-bold shadow-[0_10px_20px_rgba(113,152,166,.24)] py-4 px-6 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 transition-all duration-300 transform hover:shadow-lg relative overflow-hidden group disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none disabled:hover:scale-100" class="fcb-action fcb-button-primary w-full bg-[#7198a6] text-white font-bold shadow-[0_10px_20px_rgba(113,152,166,.24)] py-4 px-6 rounded-lg focus:outline-none focus:ring-2 focus:ring-purple-500 focus:ring-opacity-50 transition-all duration-300 transform hover:shadow-lg relative overflow-hidden group disabled:opacity-50 disabled:cursor-not-allowed disabled:transform-none disabled:hover:scale-100"
> >
<span class="relative z-10 flex items-center justify-center text-sm sm:text-lg"> <span class="relative z-10 flex items-center justify-center text-sm sm:text-lg">
@@ -79,6 +85,9 @@
<span>{{ isSubmitting ? t('send.submitting') : t('send.submit') }}</span> <span>{{ isSubmitting ? t('send.submitting') : t('send.submit') }}</span>
</span> </span>
</button> </button>
<button v-if="(isSubmitting && sendType === 'file') || cleanupPending" type="button" class="fcb-action fcb-button-danger min-h-11 w-full rounded-xl px-4 py-3 font-semibold disabled:opacity-60" :disabled="isCancelling" @click="cancelUpload">{{ isCancelling ? '正在中断并清理…' : cleanupPending ? '重试中断并清理' : '中断上传' }}</button>
<p v-if="isCancelling" role="status" class="text-center text-sm opacity-75">正在停止传输并清理临时文件,请稍候。</p>
<p v-else-if="submitMessage" role="status" class="text-center text-sm">{{ submitMessage }}</p>
</form> </form>
<div class="mt-6 text-center"> <div class="mt-6 text-center">
<router-link to="/" class="fcb-action inline-flex min-h-11 items-center rounded-lg px-2 text-sm text-[#3f6a77] transition duration-200 hover:bg-[#dcebed] hover:text-[#315c69] dark:text-[#b8d4dc] dark:hover:bg-[#333d49] sm:px-3 sm:text-base"> <router-link to="/" class="fcb-action inline-flex min-h-11 items-center rounded-lg px-2 text-sm text-[#3f6a77] transition duration-200 hover:bg-[#dcebed] hover:text-[#315c69] dark:text-[#b8d4dc] dark:hover:bg-[#333d49] sm:px-3 sm:text-base">
@@ -161,9 +170,12 @@ const {
expirationMethod, expirationMethod,
expirationValue, expirationValue,
uploadProgress, uploadProgress,
uploadedBytes,
totalBytes,
showDrawer, showDrawer,
selectedRecord, selectedRecord,
isSubmitting, isSubmitting,
isCancelling, cleanupPending, submitMessage, cancelUpload,
isFinalizing, isFinalizing,
sendRecords, sendRecords,
uploadDescription, uploadDescription,
+22 -5
View File
@@ -15,7 +15,7 @@
:loading="isDashboardRefreshing" :loading="isDashboardRefreshing"
:title="t('admin.dashboard.refresh')" :title="t('admin.dashboard.refresh')"
:aria-label="t('admin.dashboard.refresh')" :aria-label="t('admin.dashboard.refresh')"
class="fcb-icon-action shrink-0 max-sm:h-11 max-sm:w-11 max-sm:!px-0" class="fcb-dashboard-refresh shrink-0 whitespace-nowrap"
@click="refreshDashboardPage" @click="refreshDashboardPage"
> >
<template #icon> <template #icon>
@@ -329,31 +329,32 @@
</div> </div>
<div class="overflow-x-auto" tabindex="0" role="region" :aria-label="t('admin.dashboard.topDownloads.title')"> <div class="overflow-x-auto" tabindex="0" role="region" :aria-label="t('admin.dashboard.topDownloads.title')">
<table <table
v-resizable-columns
class="min-w-full divide-y" class="min-w-full divide-y"
:class="[isDarkMode ? 'divide-gray-700' : 'divide-gray-200']" :class="[isDarkMode ? 'divide-gray-700' : 'divide-gray-200']"
> >
<thead> <thead>
<tr> <tr>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
{{ t('admin.dashboard.topDownloads.file') }} {{ t('admin.dashboard.topDownloads.file') }}
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
{{ t('admin.dashboard.topDownloads.downloads') }} {{ t('admin.dashboard.topDownloads.downloads') }}
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
{{ t('admin.dashboard.topDownloads.traffic') }} {{ t('admin.dashboard.topDownloads.traffic') }}
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
{{ t('admin.dashboard.topDownloads.status') }} {{ t('admin.dashboard.topDownloads.status') }}
@@ -417,6 +418,7 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { vResizableColumns } from '@/directives/resizable-columns'
import { computed, defineComponent, h, onMounted, ref } from 'vue' import { computed, defineComponent, h, onMounted, ref } from 'vue'
import type { Component, PropType } from 'vue' import type { Component, PropType } from 'vue'
import { storeToRefs } from 'pinia' import { storeToRefs } from 'pinia'
@@ -687,3 +689,18 @@ onMounted(() => {
void refreshDashboardPage() void refreshDashboardPage()
}) })
</script> </script>
<style scoped>
@media (max-width: 639px) {
.fcb-dashboard-refresh {
width: var(--fcb-control-size);
height: var(--fcb-control-size) !important;
padding: 0 !important;
}
.fcb-dashboard-refresh :deep(svg),
.fcb-dashboard-refresh :deep(.animate-spin) {
margin-inline: 0 !important;
}
}
</style>
+60 -18
View File
@@ -14,6 +14,25 @@
</div> </div>
</div> </div>
<div class="mb-4 flex flex-wrap items-center gap-3 text-sm" :class="mutedTextClass">
<label class="flex items-center gap-2">
自动检测当前页
<select :value="downloadCheckInterval" :disabled="savingCheckInterval" class="min-h-11 rounded-lg border px-3" :class="fieldClass" @change="handleCheckIntervalChange">
<option :value="0">仅手动检测</option>
<option :value="30">每 30 秒</option>
<option :value="60">每分钟</option>
<option :value="300">每 5 分钟</option>
<option :value="600">每 10 分钟</option>
<option :value="1800">每 30 分钟</option>
</select>
</label>
<BaseButton variant="secondary" :disabled="!hasSelectedFiles || checkingDownloads" @click="checkDownloadIds([...selectedFileIds])">检测选中可下载状态({{ selectedCount }})</BaseButton>
<BaseButton variant="secondary" :disabled="checkingDownloads" @click="checkAllDownloads" title="检测全部文件,包括未显示的分页">检测可下载状态</BaseButton>
<BaseButton v-if="checkingDownloads" variant="outline" @click="cancelDownloadChecks">取消检测</BaseButton>
<span v-if="downloadProgressText" role="status">{{ downloadProgressText }} {{ downloadProgress.completed }}/{{ downloadProgress.total }}</span>
<span v-if="checkIntervalError" role="alert" class="text-red-500">{{ checkIntervalError }}</span>
</div>
<div v-if="!hasSelectedFiles" class="mb-5 grid grid-cols-2 gap-3 sm:mb-6 sm:gap-4 xl:grid-cols-4"> <div v-if="!hasSelectedFiles" class="mb-5 grid grid-cols-2 gap-3 sm:mb-6 sm:gap-4 xl:grid-cols-4">
<div <div
v-for="card in summaryCards" v-for="card in summaryCards"
@@ -70,7 +89,8 @@
</div> </div>
<Transition :css="false" @before-enter="beforeExpandPanelEnter" @enter="enterExpandPanel" @after-enter="afterExpandPanelEnter" @before-leave="beforeExpandPanelLeave" @leave="leaveExpandPanel"> <Transition :css="false" @before-enter="beforeExpandPanelEnter" @enter="enterExpandPanel" @after-enter="afterExpandPanelEnter" @before-leave="beforeExpandPanelLeave" @leave="leaveExpandPanel">
<div id="file-filter-panel" v-show="filterBodyVisible" class="fcb-expand-content mt-4 grid gap-4"> <div id="file-filter-panel" v-show="filterBodyVisible" class="fcb-expand-content">
<div class="grid gap-4 pt-4">
<div class="flex flex-col gap-3 lg:flex-row lg:items-center"> <div class="flex flex-col gap-3 lg:flex-row lg:items-center">
<label class="min-w-0 flex-1"> <label class="min-w-0 flex-1">
<span class="sr-only">{{ t('fileManage.searchPlaceholder') }}</span> <span class="sr-only">{{ t('fileManage.searchPlaceholder') }}</span>
@@ -256,6 +276,7 @@
</BaseButton> </BaseButton>
</div> </div>
</div> </div>
</div>
</Transition> </Transition>
</section> </section>
@@ -362,6 +383,10 @@
{{ file.displayHealthState }} {{ file.displayHealthState }}
</span> </span>
</div> </div>
<div class="mt-2 flex items-center justify-between gap-2">
<DownloadCheckStatus :result="downloadStatusFor(file.id)" :dark="isDarkMode" />
<BaseButton variant="outline" size="sm" :disabled="checkingDownloads" @click="checkDownloadIds([file.id])">检测可下载状态</BaseButton>
</div>
<div class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1 text-xs" :class="[mutedTextClass]"> <div class="mt-2 grid grid-cols-2 gap-x-3 gap-y-1 text-xs" :class="[mutedTextClass]">
<span>{{ file.code }} · {{ file.displaySize }}</span> <span>{{ file.code }} · {{ file.displaySize }}</span>
<span class="text-right">{{ file.displayUsage }}</span> <span class="text-right">{{ file.displayUsage }}</span>
@@ -694,6 +719,12 @@
{{ file.isExpiredFile ? t('fileManage.expired') : t('fileManage.active') }} {{ file.isExpiredFile ? t('fileManage.expired') : t('fileManage.active') }}
</span> </span>
</td> </td>
<td class="px-6 py-4" :class="primaryTextClass">
<div class="flex items-center gap-2">
<DownloadCheckStatus :result="downloadStatusFor(file.id)" :dark="isDarkMode" />
<BaseButton variant="outline" size="sm" :disabled="checkingDownloads" @click="checkDownloadIds([file.id])">检测可下载状态</BaseButton>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium"> <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<div class="flex items-center justify-end gap-2"> <div class="flex items-center justify-end gap-2">
<button <button
@@ -806,55 +837,56 @@
</div> </div>
<div class="overflow-x-auto" tabindex="0" role="region" :aria-label="t('fileManage.history.title')"> <div class="overflow-x-auto" tabindex="0" role="region" :aria-label="t('fileManage.history.title')">
<table <table
v-resizable-columns
class="min-w-full divide-y" class="min-w-full divide-y"
:class="[isDarkMode ? 'divide-gray-700' : 'divide-gray-200']" :class="[isDarkMode ? 'divide-gray-700' : 'divide-gray-200']"
> >
<thead> <thead>
<tr> <tr>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
文件 文件
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
大小 大小
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
取件码 取件码
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
上传时间 上传时间
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
过期时间 过期时间
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
下载 下载
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
流量 流量
</th> </th>
<th <th
class="px-4 py-3 text-left text-xs font-semibold uppercase" class="px-4 py-3 text-center text-xs font-semibold uppercase"
:class="[mutedTextClass]" :class="[mutedTextClass]"
> >
状态 状态
@@ -1704,6 +1736,9 @@
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { vResizableColumns } from '@/directives/resizable-columns'
import DownloadCheckStatus from '@/components/manage/DownloadCheckStatus.vue'
import { getHistoryStatusLabel } from '@/utils/history-status'
import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from 'vue' import { computed, nextTick, onMounted, onUnmounted, ref, watch, type Component } from 'vue'
import { useI18n } from 'vue-i18n' import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router' import { useRoute, useRouter } from 'vue-router'
@@ -1748,7 +1783,7 @@ import NativeDateSelect from '@/components/common/NativeDateSelect.vue'
import BaseModal from '@/components/common/BaseModal.vue' import BaseModal from '@/components/common/BaseModal.vue'
import BaseButton from '@/components/common/BaseButton.vue' import BaseButton from '@/components/common/BaseButton.vue'
import AdaptiveValue from '@/components/common/AdaptiveValue.vue' import AdaptiveValue from '@/components/common/AdaptiveValue.vue'
import { useAdminFiles, useInjectedDarkMode, useTransferAnalytics } from '@/composables' import { useAdminFiles, useInjectedDarkMode, useTransferAnalytics, useDownloadChecks } from '@/composables'
import { formatFileSize, formatTimestamp } from '@/utils/common' import { formatFileSize, formatTimestamp } from '@/utils/common'
import { createDetailMotion } from '@/utils/detailMotion' import { createDetailMotion } from '@/utils/detailMotion'
@@ -1767,6 +1802,7 @@ const fileTableHeaders = computed(() => [
t('fileManage.headers.usage'), t('fileManage.headers.usage'),
t('fileManage.headers.expiration'), t('fileManage.headers.expiration'),
t('fileManage.headers.status'), t('fileManage.headers.status'),
'可下载状态',
t('fileManage.headers.actions') t('fileManage.headers.actions')
]) ])
@@ -1851,6 +1887,17 @@ const {
toggleFileSelection toggleFileSelection
} = useAdminFiles() } = useAdminFiles()
const {
interval: downloadCheckInterval, saving: savingCheckInterval, error: checkIntervalError,
statusFor: downloadStatusFor, loadInterval: loadCheckInterval, saveInterval: saveCheckInterval,
checking: checkingDownloads, progress: downloadProgress, progressText: downloadProgressText,
checkIds: checkDownloadIds, checkAll: checkAllDownloads, cancel: cancelDownloadChecks
} = useDownloadChecks(tableData)
const handleCheckIntervalChange = (event: Event) => {
void saveCheckInterval(Number((event.target as HTMLSelectElement).value))
}
const isFilterPanelOpen = ref(false) const isFilterPanelOpen = ref(false)
const showMobilePolicyActions = ref(false) const showMobilePolicyActions = ref(false)
const mobileMediaQuery = window.matchMedia('(max-width: 767px)') const mobileMediaQuery = window.matchMedia('(max-width: 767px)')
@@ -1863,12 +1910,12 @@ const lifecycleViewportRef = ref<HTMLElement | null>(null)
let lifecycleHeightRevision = 0 let lifecycleHeightRevision = 0
const isRetrievalHistoryExpanded = ref(false) const isRetrievalHistoryExpanded = ref(false)
const retrievalTimelineEvents = computed(() => const retrievalTimelineEvents = computed(() =>
(selectedFileDetail.value?.detailTimeline || []).filter((item) => item.key === 'retrieved_event') (selectedFileDetail.value?.detailTimeline || []).filter((item) => item.key === 'retrieved_event' || item.key === 'queried_event')
) )
const retrievalTimelineCount = computed(() => retrievalTimelineEvents.value.length) const retrievalTimelineCount = computed(() => retrievalTimelineEvents.value.length)
const detailTimelineRows = computed(() => { const detailTimelineRows = computed(() => {
const timeline = selectedFileDetail.value?.detailTimeline || [] const timeline = selectedFileDetail.value?.detailTimeline || []
return timeline.filter((item) => item.key !== 'retrieved_event') return timeline.filter((item) => item.key !== 'retrieved_event' && item.key !== 'queried_event')
}) })
const visibleDetailTimeline = computed(() => const visibleDetailTimeline = computed(() =>
isLifecycleExpanded.value ? detailTimelineRows.value : detailTimelineRows.value.slice(0, 3) isLifecycleExpanded.value ? detailTimelineRows.value : detailTimelineRows.value.slice(0, 3)
@@ -2057,12 +2104,6 @@ const handleHistoryPageSizeChange = (size: number) => {
const formatHistoryBytes = (value: number | string | undefined) => const formatHistoryBytes = (value: number | string | undefined) =>
formatFileSize(Number(value || 0), 1) formatFileSize(Number(value || 0), 1)
const formatHistoryDate = (value?: string) => (value ? formatTimestamp(value) : '-') const formatHistoryDate = (value?: string) => (value ? formatTimestamp(value) : '-')
const getHistoryStatusLabel = (file: AnalyticsFileRow) => {
if (file.deleted) return '已删除'
if (file.expired) return '已过期'
if (file.current) return '现存'
return '历史'
}
const primaryTextClass = computed(() => (isDarkMode.value ? 'text-white' : 'text-gray-900')) const primaryTextClass = computed(() => (isDarkMode.value ? 'text-white' : 'text-gray-900'))
const mutedTextClass = computed(() => (isDarkMode.value ? 'text-gray-400' : 'text-gray-500')) const mutedTextClass = computed(() => (isDarkMode.value ? 'text-gray-400' : 'text-gray-500'))
@@ -2514,6 +2555,7 @@ watch(
onMounted(() => { onMounted(() => {
mobileMediaQuery.addEventListener('change', syncMobileViewport) mobileMediaQuery.addEventListener('change', syncMobileViewport)
params.value.health = getRouteHealthFilter() params.value.health = getRouteHealthFilter()
void loadCheckInterval()
void loadViewPresets() void loadViewPresets()
void loadFiles() void loadFiles()
void loadHistoryFiles() void loadHistoryFiles()
+6 -1
View File
@@ -378,7 +378,7 @@ onMounted(() => {
</select> </select>
</div> </div>
<SettingSwitch <SettingSwitch
v-if="config.file_storage === 'local'" v-if="config.file_storage === 'local' || config.file_storage === 'webdav'"
:label="t('manage.settings.chunkUploadNote')" :label="t('manage.settings.chunkUploadNote')"
:model-value="config.enableChunk" :model-value="config.enableChunk"
:enabled-text="t('common.enabled')" :enabled-text="t('common.enabled')"
@@ -627,6 +627,11 @@ onMounted(() => {
</h3> </h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
<div class="space-y-2">
<SettingNumberInput v-model="config.chunkSizeMB" label="上传分片大小" suffix="MB" :min="1" :max="100" :step="1" />
<p class="text-xs leading-5" :class="isDarkMode ? 'text-gray-400' : 'text-gray-500'">1–100 MB,默认 90 MB。保存后用于新上传,已开始的上传保留原分片大小。仅启用分片上传时生效。</p>
</div>
<SettingNumberInput <SettingNumberInput
v-model="config.uploadMinute" v-model="config.uploadMinute"
:label="t('manage.settings.uploadPerMinute')" :label="t('manage.settings.uploadPerMinute')"
+68
View File
@@ -75,3 +75,71 @@ Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http`
`uploadCompletion.test.mjs` 覆盖 202 轮询、临时网络错误重试及明确失败退出; `uploadCompletion.test.mjs` 覆盖 202 轮询、临时网络错误重试及明确失败退出;
`uploadStrategy.integration.test.mjs` 验证用户在丢失完成响应后手动重试时复用原上传 ID, `uploadStrategy.integration.test.mjs` 验证用户在丢失完成响应后手动重试时复用原上传 ID,
不重新上传分片。发送页在此阶段显示文件校验提示,确认成功后才给出取件码。 不重新上传分片。发送页在此阶段显示文件校验提示,确认成功后才给出取件码。
## 中断上传与历史状态
`uploadCancellation.integration.test.mjs` 验证中断当前请求、等待初始化返回会话后清理、
清理失败后重试及同文件重新上传。`cancelUpload.browser.mjs` 使用隔离 API 数据验证
发送页“中断上传”按钮和清理反馈,不会访问线上文件。
`historyStatus.test.mjs` 验证回收站原因共用标签、已清理、恢复后的现存状态。
分片使用原始请求体发送,最大 100 MiB,避免 multipart 额外开销超过 CDN 上限。
## 可配置分片大小
`uploadStrategy.integration.test.mjs` 验证配置决定新会话请求大小,服务端返回的
会话大小决定续传切片。`chunkSizeSettings.browser.mjs` 验证真实设置页面拒绝无效值、
保存/刷新后保留以及发送页读取公共配置;全部 API 拦截为隔离数据。
## 可下载状态
`downloadChecks.integration.test.mjs` 覆盖当前页批量检测、分页乱序响应隔离、
请求失败与重试、间隔保存及失败保留旧值、自动刷新与离开页面取消、状态组件渲染。
沿用 `node --experimental-strip-types --test --experimental-test-coverage tests/*.test.mjs`。
真实测试站验收另验证 WebDAV 小文件上传、检测不扣次数、桌面/移动端显示和间隔持久化;
验收完成后恢复间隔并清理验收文件。
## 查件与取件时间
- `receiveRecord.test.mjs`:旧日期按查件时间兼容、ISO 显示、最近下载时间独立更新。
- `retrieveTimes.integration.test.mjs`:真实 Vue/Pinia 查件流程、两种时间分离、
再次查件保留取件时间、重复下载更新、无下载动作不生成取件时间、弹窗与列表文案。
- 浏览器验收:测试站创建独立次数限制文件,查件不扣次数,分别点击弹窗和记录下载,
核对显示时间及后台次数,结束后清理测试文件。
- 表头验收:1440/1024/800px 下所有表头单行,390px 移动端无页面横向溢出。
### 表格列宽、查件生命周期和筛选动画
- `columnWidth.test.mjs` 覆盖指定列增减宽度、最小宽度及相邻列不受影响。
- `retrieveTimes.integration.test.mjs` 同时验证签名文本下载入口,以及查件和取件事件的顺序与显示。
- `tests/browser/admin-tables.cjs` 用真实浏览器验证所有文件、历史文件、下载排行表头居中及拖拽,
包括键盘调整、松开/失焦/卸载清理、窄屏无页面溢出、精简下载状态。
同时逐帧测量筛选收起末段,验证快速反向切换及减少动态效果模式。
- 浏览器脚本需要有现存文件的测试站、Playwright 和 Chromium,以及环境变量
`FCB_TEST_PASSWORD`;可通过 `FCB_TEST_URL` 指定站点。用 Playwright skill 的 `run.js`
运行该脚本,或在安装 Playwright 的环境中直接运行。`FCB_FRONTEND_DIST` 可指定本地构建目录,
仅在浏览器内替换静态资源进行部署前验证,不修改站点。
- 前端单元/集成 72 项通过;新增列宽计算工具覆盖率 100%。Node 原生覆盖率
不涵盖 Vite SSR 动态载入的 Vue 和指令模块,真实 DOM 行为由浏览器验收覆盖。
### 仪表盘刷新按钮
- `tests/browser/dashboard-refresh.cjs` 验证深浅主题和 1440/640/390px 屏宽下的左右留白、
图标间距、移动端图标及加载动画居中,同时确认禁用加载状态和两类数据刷新请求。
- 使用 `FCB_TEST_PASSWORD`、可选 `FCB_TEST_URL` 和 `FCB_FRONTEND_DIST`,运行方式同表格验收脚本。
- 72 项前端单元/集成与覆盖率检查、类型检查、架构检查和生产构建通过;
本轮仅修改仪表盘按钮样式,未变更后端。Vue 样式行为通过真实浏览器测量验证。
### 手动检测范围与取消
- 默认关闭定时检测;进入页面、列表刷新、搜索、分页都不会主动读取文件。
- 每行「检测可下载状态」检测单个文件;勾选检测只处理选中 ID;顶部同名按钮
检测全部未回收文件,包含当前过滤和分页之外的文件。
- 每次只发起一个文件的检测请求,显示已处理/总数,可取消后续请求。
- `downloadChecks.integration.test.mjs` 覆盖默认静默、选择去重、串行请求、失败重试、
全量 ID 枚举、空结果、取消、旧响应隔离和卸载清理。
- `tests/browser/manual-download-checks.cjs` 通过 25 文件的受控 API 响应验证跨页全量、
单个、选中、取消、移动布局,防止测试向真实网盘批量发起请求。
可使用 `FCB_TEST_TOKEN` 或 `FCB_TEST_PASSWORD`;可选本地前端产物路径。
- 当前前端单元/集成 75 项通过,架构/类型/构建通过;Node 覆盖率不覆盖 SSR 动态 Vue 模块,
交互另经真实浏览器验证。此前自动随列表刷新的行为已撤销。
+96
View File
@@ -0,0 +1,96 @@
const {chromium}=require('playwright');
const {expect}=require('playwright/test');
const assert=require('node:assert/strict');
const fs=require('node:fs');
const path=require('node:path');
const site=process.env.FCB_TEST_URL || 'https://filetest.orionc.me';
(async()=>{
const browser=await chromium.launch({headless:false});
try {
const context=await browser.newContext({viewport:{width:1440,height:1000}});
const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
const login=await page.request.post(site+'/admin/login',{data:{password:process.env.FCB_TEST_PASSWORD}});
const body=await login.json();assert.ok(body.detail?.token,'Test login must succeed');
await context.addInitScript(token=>localStorage.setItem('token',token),body.detail.token);
if(process.env.FCB_FRONTEND_DIST){
await page.route(site+'/**',async route=>{
const url=new URL(route.request().url());
const relative=url.pathname==='/'?'index.html':url.pathname.startsWith('/theme-assets/')?url.pathname.slice('/theme-assets/'.length):null;
const file=relative&&path.join(process.env.FCB_FRONTEND_DIST,relative);
if(file&&fs.existsSync(file)&&fs.statSync(file).isFile())await route.fulfill({path:file});else await route.continue();
});
}
await page.goto(site+'/#/admin/files');
const all=page.locator('.data-table-2026 table');
await all.getByRole('status').first().waitFor();
await page.getByTitle('检测全部文件,包括未显示的分页', {exact:true}).click();
await all.getByRole('status').filter({hasText:'可下载'}).first().waitFor();
const statuses=await all.getByRole('status').evaluateAll(nodes=>nodes.map(n=>({children:n.children.length,title:n.getAttribute('title'),text:n.textContent})));
statuses.forEach(s=>{assert.ok(s.children<=2,JSON.stringify(s));assert.equal(s.title,null)});
async function verifyTable(table,name) {
await table.scrollIntoViewIfNeeded();
const headers=table.locator('th');const handles=table.getByRole('separator');
assert.equal(await handles.count(),await headers.count());
for(const style of await headers.evaluateAll(hs=>hs.map(h=>({align:getComputedStyle(h).textAlign,whiteSpace:getComputedStyle(h).whiteSpace})))){
assert.equal(style.align,'center');assert.equal(style.whiteSpace,'nowrap');
}
const widths=()=>headers.evaluateAll(hs=>hs.map(h=>h.getBoundingClientRect().width));
const index=1;const handle=handles.nth(index);await handle.scrollIntoViewIfNeeded();
const before=await widths();const box=await handle.boundingBox();
await page.mouse.move(box.x+box.width/2,box.y+box.height/2);await page.mouse.down();
await page.mouse.move(box.x+box.width/2+90,box.y+box.height/2,{steps:12});await page.mouse.up();
const after=await widths();assert.ok(Math.abs(after[index]-before[index]-90)<2,`${name}: ${before} -> ${after}`);
before.forEach((w,i)=>{if(i!==index)assert.ok(Math.abs(w-after[i])<2,`${name} other column changed`)})
// Continued widening and keyboard narrowing must agree with the actual geometry.
await handle.focus();await page.keyboard.press('ArrowRight');assert.ok(Math.abs((await widths())[index]-after[index]-16)<2);
await page.keyboard.press('ArrowLeft');assert.ok(Math.abs((await widths())[index]-after[index])<2);
const b=await handle.boundingBox();await page.mouse.move(b.x+4,b.y+b.height/2);await page.mouse.down();
await page.mouse.move(b.x-500,b.y+b.height/2,{steps:10});await page.mouse.up();
assert.ok((await widths())[index]>=72);assert.equal(await table.evaluate(t=>t.classList.contains('columns-resizing')),false);
const frozen=await widths();await page.mouse.move(900,500);assert.deepEqual(await widths(),frozen);
console.log(name+': centered, drag +/- and minimum, keyboard, other columns stable, release cleanup OK');
}
const toggle=page.locator('[aria-controls="file-filter-panel"]');
await toggle.scrollIntoViewIfNeeded();await toggle.click();
await page.waitForFunction(()=>{const p=document.querySelector('#file-filter-panel');return getComputedStyle(p).display!=='none'&&!p.style.height});
const samples=await page.evaluate(async()=>{
const panel=document.querySelector('#file-filter-panel'),card=panel.closest('section'),samples=[];
const start=performance.now();document.querySelector('[aria-controls="file-filter-panel"]').click();
await new Promise(resolve=>{const frame=()=>{const elapsed=performance.now()-start;samples.push({t:elapsed,height:card.getBoundingClientRect().height});if(elapsed<650)requestAnimationFrame(frame);else resolve()};requestAnimationFrame(frame)});
return samples;
});
let lateJump=0;for(let i=1;i<samples.length;i++)if(samples[i-1].t>=300)lateJump=Math.max(lateJump,Math.abs(samples[i].height-samples[i-1].height));
fs.writeFileSync('/tmp/fcb-filter-animation-samples.json',JSON.stringify(samples));
assert.ok(lateJump<5,'Filter final collapse jump: '+lateJump);
await page.evaluate(async()=>{const b=document.querySelector('[aria-controls="file-filter-panel"]');b.click();await new Promise(r=>setTimeout(r,80));b.click();await new Promise(r=>setTimeout(r,80));b.click()});
await page.waitForFunction(()=>{const p=document.querySelector('#file-filter-panel');return getComputedStyle(p).display!=='none'&&!p.style.height});
await page.emulateMedia({reducedMotion:'reduce'});await toggle.click();
await page.waitForFunction(()=>getComputedStyle(document.querySelector('#file-filter-panel')).display==='none');
await page.emulateMedia({reducedMotion:'no-preference'});
console.log('Filter collapse final frame delta '+lateJump.toFixed(2)+'px; rapid reversal and reduced motion PASS');
await verifyTable(all,'All files');
const history=page.locator('table').filter({has:page.getByRole('columnheader',{name:'流量',exact:true})});
await verifyTable(history,'History');
await all.scrollIntoViewIfNeeded();await page.screenshot({path:'/tmp/fcb-columns-light.png'});
await page.goto(site+'/#/admin/dashboard');
const dashboard=page.locator('table');await expect(dashboard).toHaveCount(1);await dashboard.getByRole('separator').first().waitFor();
await verifyTable(dashboard,'Download ranking');
await page.goto(site+'/#/admin/files');await expect(page.locator('table')).toHaveCount(2);await all.getByRole('separator').first().waitFor();
// Cancel the active drag through page blur, then navigate away during another drag.
const h=all.getByRole('separator').nth(1);await h.scrollIntoViewIfNeeded();let b=await h.boundingBox();
await page.mouse.move(b.x+4,b.y+b.height/2);await page.mouse.down();await page.evaluate(()=>window.dispatchEvent(new Event('blur')));await page.mouse.up();
assert.equal(await all.evaluate(t=>t.classList.contains('columns-resizing')),false);
b=await h.boundingBox();await page.mouse.move(b.x+4,b.y+b.height/2);await page.mouse.down();
await page.goto(site+'/#/admin/dashboard');await page.mouse.up();
await page.goto(site+'/#/admin/files');await expect(page.locator('table')).toHaveCount(2);await all.getByRole('separator').first().waitFor();
for(const width of [1024,800,390]){
await page.setViewportSize({width,height:1000});
assert.ok(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),'No document horizontal overflow '+width);
}
await page.setViewportSize({width:1440,height:1000});await page.emulateMedia({colorScheme:'dark'});await page.reload();
await all.getByRole('separator').first().waitFor();await all.scrollIntoViewIfNeeded();await page.screenshot({path:'/tmp/fcb-columns-dark.png'});
assert.deepEqual(errors,[]);console.log('Compact status, responsive widths, navigation/blur cleanup: PASS');
}finally{await browser.close()}
})().catch(e=>{console.error(e);process.exitCode=1});
+24
View File
@@ -0,0 +1,24 @@
const {chromium}=require('playwright');const {expect}=require('playwright/test');const assert=require('node:assert/strict');const fs=require('node:fs');const path=require('node:path');
const site=process.env.FCB_TEST_URL||'https://filetest.orionc.me';
(async()=>{const browser=await chromium.launch({headless:false});try{
const context=await browser.newContext({viewport:{width:1440,height:1000},colorScheme:'dark'});const page=await context.newPage();const errors=[];page.on('pageerror',e=>errors.push(e.message));
const login=await page.request.post(site+'/admin/login',{data:{password:process.env.FCB_TEST_PASSWORD}});const token=(await login.json()).detail.token;assert.ok(token);
await context.addInitScript(token=>localStorage.setItem('token',token),token);
if(process.env.FCB_FRONTEND_DIST)await page.route(site+'/**',async route=>{const u=new URL(route.request().url());const rel=u.pathname==='/'?'index.html':u.pathname.startsWith('/theme-assets/')?u.pathname.slice(14):null;const file=rel&&path.join(process.env.FCB_FRONTEND_DIST,rel);if(file&&fs.existsSync(file)&&fs.statSync(file).isFile())await route.fulfill({path:file});else await route.continue()});
await page.goto(site+'/#/admin/dashboard');const button=page.getByRole('button',{name:'刷新数据',exact:true});await expect(button).toBeEnabled();
let hold=false;const gates=[];const counts={dashboard:0,analytics:0};
for(const endpoint of Object.keys(counts))await page.route(site+'/admin/'+endpoint+'**',async route=>{counts[endpoint]++;if(hold)await new Promise(r=>gates.push(r));await route.continue()});
const geometry=()=>button.evaluate(b=>{const icon=b.querySelector('svg,.animate-spin'),label=b.querySelector('span'),r=b.getBoundingClientRect(),i=icon.getBoundingClientRect(),l=label.getBoundingClientRect(),s=getComputedStyle(b);return {width:r.width,height:r.height,left:i.left-r.left,right:r.right-l.right,gap:l.left-i.right,centerDelta:(i.left+i.right-r.left-r.right)/2,paddingLeft:parseFloat(s.paddingLeft),paddingRight:parseFloat(s.paddingRight)}});
for(const theme of ['dark','light']){
await page.emulateMedia({colorScheme:theme});
for(const width of [1440,640,390]){
await page.setViewportSize({width,height:1000});await button.scrollIntoViewIfNeeded();const idle=await geometry();
if(width>=640){assert.ok(idle.paddingLeft>=15&&idle.paddingRight>=15,JSON.stringify(idle));assert.ok(idle.gap>=7,JSON.stringify(idle));assert.ok(idle.left>=15&&idle.right>=15,JSON.stringify(idle))}else assert.ok(Math.abs(idle.centerDelta)<1,JSON.stringify(idle));
hold=true;await button.click();await expect(button).toBeDisabled();await expect.poll(()=>gates.length).toBe(2);
const loading=await geometry();if(width>=640)assert.ok(loading.gap>=7,JSON.stringify(loading));else assert.ok(Math.abs(loading.centerDelta)<1,JSON.stringify(loading));
hold=false;gates.splice(0).forEach(r=>r());await expect(button).toBeEnabled();
await page.screenshot({path:`/tmp/fcb-refresh-${theme}-${width}.png`});
}
}
assert.deepEqual(counts,{dashboard:6,analytics:6});assert.deepEqual(errors,[]);console.log('PASS: dark/light at 1440/640/390; desktop padding/gap, mobile icon/spinner centering; both refresh requests and disabled loading state.');
}finally{await browser.close()}})().catch(e=>{console.error(e);process.exitCode=1});
+64
View File
@@ -0,0 +1,64 @@
const { chromium } = require('playwright')
const { expect } = require('playwright/test')
const assert = require('node:assert/strict')
const fs = require('node:fs'), path = require('node:path')
const site = process.env.FCB_TEST_URL || 'https://filetest.orionc.me'
;(async () => {
const browser = await chromium.launch({ headless: false })
try {
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } })
const page = await context.newPage(), errors = []
page.on('pageerror', error => errors.push(error.message))
let token = process.env.FCB_TEST_TOKEN
if (!token) token = (await (await page.request.post(site + '/admin/login', { data: { password: process.env.FCB_TEST_PASSWORD } })).json()).detail.token
await context.addInitScript(token => localStorage.setItem('token', token), token)
const source = await page.request.get(site + '/admin/file/list?size=10', { headers: { Authorization: `Bearer ${token}` } })
const base = (await source.json()).detail.data[0];assert.ok(base, 'Test site needs one file for its fixture schema')
const files = Array.from({ length: 25 }, (_, index) => ({ ...base, id: 1001 + index, prefix: `manual-check-${index + 1}`, code: `TEST${1001 + index}` }))
if (process.env.FCB_FRONTEND_DIST) await page.route(site + '/**', async route => {
const u = new URL(route.request().url()), relative = u.pathname === '/' ? 'index.html' : u.pathname.startsWith('/theme-assets/') ? u.pathname.slice(14) : null
const file = relative && path.join(process.env.FCB_FRONTEND_DIST, relative)
if (file && fs.existsSync(file) && fs.statSync(file).isFile()) await route.fulfill({ path: file });else await route.continue()
})
await page.route(site + '/admin/config/get', async route => { const response = await route.fetch(), body = await response.json();body.detail.downloadCheckInterval = 0;await route.fulfill({ json: body }) })
await page.route(site + '/admin/file/list**', async route => {
const u = new URL(route.request().url()), page = Number(u.searchParams.get('page') || 1), size = Number(u.searchParams.get('size') || 10)
await route.fulfill({ json: { code: 200, detail: { page, size, total: 25, data: files.slice((page - 1) * size, page * size), summary: { totalFiles: 25 } } } })
})
let calls = [], active = 0, peak = 0, hold = false, release, enumerations = 0
await page.route(site + '/admin/file/download-check-ids', async route => { enumerations++;await route.fulfill({ json: { code: 200, detail: files.map(f => f.id) } }) })
await page.route(site + '/admin/file/download-check', async route => {
const ids = route.request().postDataJSON().ids;calls.push(ids);active++;peak = Math.max(peak, active)
try {
if (hold) await new Promise(resolve => { release = resolve })
await route.fulfill({ json: { code: 200, detail: ids.map(id => ({ id, status: 'available', message: 'probe', checkedAt: new Date().toISOString() })) } })
} catch (error) { if (!String(error).includes('closed') && !String(error).includes('Invalid Interception')) throw error }
finally { active-- }
})
await page.goto(site + '/#/admin/files')
const table = page.locator('.data-table-2026'), rows = table.locator('tbody tr')
await expect(rows).toHaveCount(10)
await expect(page.getByLabel('自动检测当前页')).toHaveValue('0')
assert.equal(calls.length, 0)
await table.getByRole('button', { name: '刷新列表', exact: true }).click();await expect(rows).toHaveCount(10)
await table.getByRole('button', { name: '下一页', exact: true }).click();await expect(rows.first()).toContainText('TEST1011')
await page.clock.install();await page.clock.fastForward(3600000);await page.clock.resume();assert.equal(calls.length, 0)
await rows.first().getByRole('button', { name: '检测可下载状态', exact: true }).click()
await expect(page.getByRole('status').filter({ hasText: '检测完成 1/1' })).toBeVisible();assert.deepEqual(calls, [[1011]])
calls = [];await rows.nth(0).getByRole('checkbox').check();await rows.nth(1).getByRole('checkbox').check()
await page.getByRole('button', { name: '检测选中可下载状态(2)', exact: true }).click()
await expect(page.getByRole('status').filter({ hasText: '检测完成 2/2' })).toBeVisible();assert.deepEqual(calls, [[1011], [1012]])
calls = [];await page.getByTitle('检测全部文件,包括未显示的分页', { exact: true }).click()
await expect(page.getByRole('status').filter({ hasText: '检测完成 25/25' })).toBeVisible()
assert.equal(enumerations, 1);assert.deepEqual(calls, files.map(f => [f.id]));assert.equal(peak, 1)
calls = [];hold = true;await page.getByTitle('检测全部文件,包括未显示的分页', { exact: true }).click()
await expect.poll(() => calls.length).toBe(1);await page.getByRole('button', { name: '取消检测', exact: true }).click()
await expect(page.getByRole('status').filter({ hasText: '已取消' })).toBeVisible();hold = false;release()
await expect.poll(() => active).toBe(0);assert.equal(calls.length, 1)
await page.setViewportSize({ width: 390, height: 844 });await expect(page.getByTitle('检测全部文件,包括未显示的分页')).toBeVisible()
assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth + 1))
await page.screenshot({ path: '/tmp/fcb-manual-check-mobile.png' })
await page.setViewportSize({ width: 1440, height: 1000 });await page.screenshot({ path: '/tmp/fcb-manual-check-desktop.png' })
assert.deepEqual(errors, []);console.log('PASS: no checks on entry/refresh/pagination/time; single, selected, all 25 across pages, serial requests, cancel, mobile layout.')
} finally { await browser.close() }
})().catch(error => { console.error(error);process.exitCode = 1 })
+18
View File
@@ -0,0 +1,18 @@
import assert from 'node:assert/strict'
export async function runCancelUploadCheck(page, base='http://127.0.0.1:5180/theme-assets/') {
let cleanup=0,completes=0,requests=0,startedResolve
const started=new Promise(resolve=>startedResolve=resolve)
await page.route('**/api/v1/config',r=>r.fulfill({json:{code:200,detail:{config:{name:'test',expireStyle:['day'],max_save_seconds:0,openUpload:1,enableChunk:1,uploadSize:1073741824}}}}))
await page.route('**/chunk/upload/init/**',r=>r.fulfill({json:{code:200,detail:{upload_id:'isolated-cancel',chunk_size:1048576,uploaded_chunks:[]}}}))
await page.route('**/chunk/upload/raw/**',async r=>{requests++;startedResolve();await new Promise(resolve=>setTimeout(resolve,1500));try{await r.fulfill({json:{code:200}})}catch{}})
await page.route('**/chunk/upload/complete/**',r=>{completes++;return r.fulfill({json:{code:200,detail:{code:'UNEXPECTED'}}})})
await page.route('**/chunk/upload/isolated-cancel',r=>{assert.equal(r.request().method(),'DELETE');cleanup++;return r.fulfill({json:{code:200,detail:{cancelled:true}}})})
await page.goto(base+'#/send')
await page.locator('input[type=file]').setInputFiles({name:'cancel.txt',mimeType:'text/plain',buffer:Buffer.alloc(3*1024*1024,97)})
await page.locator('button[type=submit]').click();await started
await page.getByRole('button',{name:'中断上传',exact:true}).click()
await page.getByText('上传已中断,临时分片已清理,可重新发送',{exact:true}).waitFor()
assert.equal(cleanup,1);assert.equal(requests,1);assert.equal(completes,0)
assert.equal(await page.locator('button[type=submit]').isEnabled(),true)
console.log('browser cancellation: stopped raw request, cleaned once, no subsequent chunks/publication')
}
+20
View File
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict'
// Isolated app/API fixture. Never changes deployed configuration.
export async function runChunkSizeSettingsCheck(page, base='http://127.0.0.1:5180/theme-assets/') {
let size=90, saves=0, requested
await page.addInitScript(()=>localStorage.setItem('token','fixture-only-token'))
await page.route('**/api/v1/config',r=>r.fulfill({json:{code:200,detail:{config:{name:'fixture',expireStyle:['day'],max_save_seconds:604800,enableChunk:1,chunkSizeMB:size,uploadSize:1073741824,openUpload:1}}}}))
await page.route('**/admin/verify',r=>r.fulfill({json:{code:200,detail:{is_admin:true}}}))
await page.route('**/admin/config/get',r=>r.fulfill({json:{code:200,detail:{name:'fixture',file_storage:'webdav',chunkSizeMB:size,enableChunk:1,uploadSize:1073741824,max_save_seconds:604800,expireStyle:['day'],openUpload:1}}}))
await page.route('**/admin/config/update',r=>{size=r.request().postDataJSON().chunkSizeMB;saves++;return r.fulfill({json:{code:200}})})
await page.route('**/chunk/upload/init/**',r=>{requested=Number(new URLSearchParams(r.request().postData()).get('chunk_size'));return r.fulfill({json:{code:400,message:'stop after checking configured size'}})})
await page.goto(base+'#/admin/settings',{waitUntil:'networkidle'})
const field=page.getByRole('spinbutton',{name:'上传分片大小',exact:true});await field.waitFor()
assert.equal(await field.inputValue(),'90')
await field.fill('0');await page.getByRole('button',{name:'保存设置',exact:true}).click();await page.waitForTimeout(100);assert.equal(saves,0)
await field.fill('2');await page.getByRole('button',{name:'保存设置',exact:true}).click();await page.waitForTimeout(200);assert.equal(size,2);assert.equal(saves,1)
await page.reload({waitUntil:'networkidle'});assert.equal(await field.inputValue(),'2')
await page.goto(base+'#/send',{waitUntil:'networkidle'});await page.locator('input[type=file]').setInputFiles({name:'configured.txt',mimeType:'text/plain',buffer:Buffer.alloc(3*1024*1024,97)})
await page.locator('button[type=submit]').click();await page.waitForTimeout(500);assert.equal(requested,2*1024*1024)
console.log('settings: reject invalid, save/reload 2MB, new upload requests 2MB: passed')
}
+17
View File
@@ -0,0 +1,17 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { resizeColumn } from '../src/utils/column-width.ts'
test('dragging changes only the selected column and preserves the starting widths', () => {
const widths = [100, 240, 180]
assert.deepEqual(resizeColumn(widths, 1, 65, 80), [100, 305, 180])
assert.deepEqual(resizeColumn(widths, 1, -50, 80), [100, 190, 180])
assert.deepEqual(widths, [100, 240, 180])
})
test('narrowing stops at the header minimum and widening works again', () => {
const widths = [100, 240, 180]
assert.deepEqual(resizeColumn(widths, 2, -1000, 96), [100, 240, 96])
assert.deepEqual(resizeColumn([100, 240, 96], 2, 16, 96), [100, 240, 112])
assert.deepEqual(resizeColumn(widths, 0, 0, 72), widths)
})
+100
View File
@@ -0,0 +1,100 @@
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { effectScope, ref, nextTick } from 'vue'
import { createServer } from 'vite'
let server, create, service, config
before(async () => {
server = await createServer({ server: { middlewareMode: true, watch: null }, appType: 'custom' })
create = (await server.ssrLoadModule('/src/composables/useDownloadChecks.ts')).useDownloadChecks
const exports = await server.ssrLoadModule('/src/services/index.ts')
service = exports.DownloadCheckService; config = exports.ConfigService
})
after(async () => await server?.close())
const ok = ids => ({ code: 200, detail: ids.map(id => ({id, status: 'available', message: 'ok', checkedAt: '2026-09-18T00:00:00Z'})) })
test('manual mode does not check on mount, config load, refresh, pagination or elapsed time', async t => {
const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files))
const oldCheck=service.check,oldGet=config.getConfig;let calls=0
t.mock.timers.enable({apis:['setTimeout']})
try {
service.check=async ids=>{calls++;return ok(ids)}
config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:0}})
assert.equal(f.interval.value,0);await f.loadInterval()
files.value=[{id:2}];await nextTick();files.value=[{id:2}];await nextTick()
t.mock.timers.tick(3600000);assert.equal(calls,0)
await f.checkIds([2]);assert.equal(calls,1)
} finally {scope.stop();service.check=oldCheck;config.getConfig=oldGet;t.mock.timers.reset()}
})
test('single and selected checks deduplicate IDs, run sequentially, tolerate failure and report progress',async()=>{
const scope=effectScope(),files=ref([{id:1},{id:2},{id:3}]),f=scope.run(()=>create(files))
const original=service.check;let active=0,max=0;const seen=[]
try {
service.check=async ids=>{active++;max=Math.max(max,active);seen.push(ids);await Promise.resolve();active--;if(ids[0]===2)throw Error('offline');return ok(ids)}
await f.checkIds([1,2,1,3]);assert.deepEqual(seen,[[1],[2],[3]]);assert.equal(max,1)
assert.equal(f.statusFor(1).status,'available');assert.equal(f.statusFor(2).status,'unknown')
assert.deepEqual(f.progress.value,{completed:3,total:3});assert.equal(files.value.length,3)
service.check=async ids=>ok(ids);await f.checkIds([2]);assert.equal(f.statusFor(2).status,'available')
}finally{scope.stop();service.check=original}
})
test('all-files check includes IDs outside the visible page and ignores changing list filters',async()=>{
const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files))
const oldCheck=service.check,oldIds=service.listIds;const seen=[]
try {
service.listIds=async()=>({code:200,detail:[1,2,3,4]})
service.check=async ids=>{seen.push(ids[0]);files.value=[{id:99}];await nextTick();return ok(ids)}
await f.checkAll();assert.deepEqual(seen,[1,2,3,4]);assert.equal(f.progress.value.completed,4)
assert.equal(f.statusFor(4).status,'available');assert.equal(f.statusFor(99).status,'unknown')
}finally{scope.stop();service.check=oldCheck;service.listIds=oldIds}
})
test('cancel stops subsequent requests and stale responses cannot overwrite a new run',async()=>{
const scope=effectScope(),f=scope.run(()=>create(ref([{id:1},{id:2}]))),old=service.check
let resolveFirst,signal;const seen=[]
try {
service.check=(ids,s)=>{signal=s;seen.push(ids[0]);return new Promise(r=>resolveFirst=r)}
const first=f.checkIds([1,2]);await f.checkIds([3]);assert.deepEqual(seen,[1])
f.cancel();assert.equal(signal.aborted,true);assert.equal(f.checking.value,false)
assert.equal(f.statusFor(1).status,'unknown');assert.equal(f.progressText.value,'已取消')
service.check=async ids=>ok(ids);await f.checkIds([1]);const fresh=f.statusFor(1)
resolveFirst({code:200,detail:[{id:1,status:'unavailable'}]});await first
assert.deepEqual(f.statusFor(1),fresh);assert.deepEqual(seen,[1])
}finally{scope.stop();service.check=old}
})
test('all-files enumeration handles failure, cancellation, empty results and disposal',async()=>{
const oldIds=service.listIds,oldCheck=service.check,scope=effectScope(),f=scope.run(()=>create(ref([])))
let calls=0
try {
service.check=async ids=>{calls++;return ok(ids)}
service.listIds=async()=>{throw Error('offline')};await f.checkAll();assert.ok(f.error.value);assert.equal(calls,0)
service.listIds=async()=>({code:200,detail:[]});await f.checkAll();assert.equal(f.progressText.value,'没有可检测的文件')
let resolveIds,signal;service.listIds=s=>{signal=s;return new Promise(r=>resolveIds=r)}
const pending=f.checkAll();scope.stop();assert.equal(signal.aborted,true);resolveIds({code:200,detail:[1]});await pending;assert.equal(calls,0)
}finally{scope.stop();service.listIds=oldIds;service.check=oldCheck}
})
test('interval settings persist, save failures retain old value, manual works with timer off',async()=>{
const scope=effectScope(),f=scope.run(()=>create(ref([{id:1}]))),oldGet=config.getConfig,oldSave=config.updateConfig,oldCheck=service.check
try {
config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:60}});await f.loadInterval();assert.equal(f.interval.value,60)
config.updateConfig=async data=>{assert.equal(data.downloadCheckInterval,0);return {code:200}}
await f.saveInterval(0);assert.equal(f.interval.value,0)
config.updateConfig=async()=>{throw Error('offline')};await f.saveInterval(300);assert.equal(f.interval.value,0);assert.ok(f.error.value)
service.check=async ids=>ok(ids);await f.refresh();assert.equal(f.statusFor(1).status,'available')
}finally{scope.stop();config.getConfig=oldGet;config.updateConfig=oldSave;service.check=oldCheck}
})
test('explicitly enabled timer runs only after its interval and stops on disposal',async t=>{
const scope=effectScope(),files=ref([{id:1}]),f=scope.run(()=>create(files)),oldCheck=service.check,oldGet=config.getConfig
let calls=0;t.mock.timers.enable({apis:['setTimeout']})
try {
service.check=async ids=>{calls++;return ok(ids)};config.getConfig=async()=>({code:200,detail:{downloadCheckInterval:300}})
await f.loadInterval();files.value=[{id:2}];await nextTick();assert.equal(calls,0)
t.mock.timers.tick(300000);await new Promise(r=>setImmediate(r));assert.equal(calls,1)
scope.stop();t.mock.timers.tick(300000);assert.equal(calls,1)
}finally{scope.stop();service.check=oldCheck;config.getConfig=oldGet;t.mock.timers.reset()}
})
test('status component renders only label and last checked time',async()=>{
const {createSSRApp}=await import('vue'),{renderToString}=await import('vue/server-renderer')
const Component=(await server.ssrLoadModule('/src/components/manage/DownloadCheckStatus.vue')).default
for(const [status,label] of Object.entries({available:'可下载',unavailable:'不可下载',unknown:'未检测',checking:'检测中'})){
const html=await renderToString(createSSRApp(Component,{result:{id:1,status,message:'reason',checkedAt:'2026-09-18T00:00:00Z'},dark:false}))
assert.ok(html.includes(label));assert.ok(!html.includes('reason'));assert.ok(html.includes('2026'))
}
})
+1
View File
@@ -0,0 +1 @@
export function saveAs() { throw new Error('Browser download is not used in SSR layout tests') }
+13
View File
@@ -0,0 +1,13 @@
import {test} from 'node:test'
import assert from 'node:assert/strict'
import {getHistoryStatusLabel} from '../src/utils/history-status.ts'
test('history labels follow trash and purge before expiry/current flags',()=>{
for(const [value,want] of [[{current:true},'现存'],[{status:'trashed',current:false,expired:true},'回收站中'],[{status:'purged',deleted:true},'已清理'],[{status:'active',current:true},'现存'],[{status:'expired',current:true},'现存'],[{deleted:true,current:false},'已删除'],[{current:false},'历史']])assert.equal(getHistoryStatusLabel(value),want)
})
test('restored history is distinct and recoverable reasons match trash labels',()=>{
assert.equal(getHistoryStatusLabel({status:'active',current:true,was_restored:true}),'现存,已从回收站恢复')
assert.equal(getHistoryStatusLabel({status:'trashed',trash_reason:'expired_count'}),'次数用尽')
assert.equal(getHistoryStatusLabel({status:'trashed',trash_reason:'expired_time'}),'保存到期')
assert.equal(getHistoryStatusLabel({status:'trashed',trash_reason:'manual'}),'手动删除')
})
+25
View File
@@ -0,0 +1,25 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { queriedAt, formatRecordTime, markRecordRetrieved } from '../src/utils/receive-record.ts'
test('legacy lookup dates never imply a retrieval happened', () => {
const record = { date: '2026/9/18 15:08:09' }
assert.equal(queriedAt(record), record.date)
assert.equal(formatRecordTime(queriedAt(record)), record.date)
assert.equal(formatRecordTime(record.retrievedAt), '')
})
test('download click updates retrieval independently of query and legacy timestamps', () => {
const record = { date: 'legacy', queriedAt: '2026-09-18T07:00:00.000Z' }
markRecordRetrieved(record, new Date('2026-09-18T07:01:00Z'))
assert.equal(record.retrievedAt, '2026-09-18T07:01:00.000Z')
markRecordRetrieved(record, new Date('2026-09-18T07:02:00Z'))
assert.equal(record.retrievedAt, '2026-09-18T07:02:00.000Z')
assert.equal(queriedAt(record), '2026-09-18T07:00:00.000Z')
assert.equal(record.date, 'legacy')
})
test('ISO dates display in local time while invalid legacy values are preserved', () => {
const iso = '2026-09-18T07:00:00.000Z'
assert.equal(formatRecordTime(iso), new Date(iso).toLocaleString())
assert.equal(formatRecordTime('2026-99-99T00:00:00Z'), '2026-99-99T00:00:00Z')
assert.equal(formatRecordTime(null), '')
})
+106
View File
@@ -0,0 +1,106 @@
import { test, before, after } from 'node:test'
import assert from 'node:assert/strict'
import { createServer } from 'vite'
import { fileURLToPath } from 'node:url'
import { createSSRApp, h } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { createPinia } from 'pinia'
import { createI18n } from 'vue-i18n'
let server, createFlow, service, Detail, List, zh, oldWindow, opened
before(async () => {
oldWindow = globalThis.window; opened = []
globalThis.window = { location: {origin:'https://example.test'}, open: url => { opened.push(url); return {} } }
server = await createServer({resolve:{alias:{'file-saver':fileURLToPath(new URL('./fixtures/browser-save.stub.mjs',import.meta.url))}},server:{middlewareMode:true,watch:null},appType:'custom'})
createFlow = (await server.ssrLoadModule('/src/composables/useRetrieveFlow.ts')).useRetrieveFlow
service = (await server.ssrLoadModule('/src/services/index.ts')).FileService
Detail = (await server.ssrLoadModule('/src/components/common/FileDetailModal.vue')).default
List = (await server.ssrLoadModule('/src/components/common/FileRecordList.vue')).default
zh = (await server.ssrLoadModule('/src/i18n/locales/zh-CN.ts')).default
})
after(async () => { await server?.close(); globalThis.window = oldWindow })
const i18n = () => createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}})
async function flow() {
let result
const app=createSSRApp({setup(){result=createFlow();return()=>h('div')}})
app.use(createPinia()); app.use(i18n()); await renderToString(app); return result
}
const detail={code:'ABCD2345',name:'file.apk',size:3,text:'/share/download?code=ABCD2345',download_url:'/share/download?code=ABCD2345',type:'file',is_text:false,remaining_downloads:2}
test('lookup creates only query time; click records retrieval; querying again preserves retrieval', async t => {
const original=service.selectFile; const f=await flow()
t.mock.timers.enable({apis:['Date'],now:Date.parse('2026-09-18T07:00:00Z')})
service.selectFile=async()=>({code:200,detail})
try {
f.code.value=detail.code; await f.handleSubmit()
const first=f.selectedRecord.value
assert.equal(first.queriedAt,'2026-09-18T07:00:00.000Z')
assert.equal(first.retrievedAt,null)
f.viewDetails(first); assert.equal(first.retrievedAt,null)
t.mock.timers.tick(1000); f.downloadRecord(first)
assert.equal(first.retrievedAt,'2026-09-18T07:00:01.000Z')
assert.equal(f.records.value[0].retrievedAt,first.retrievedAt)
assert.ok(opened.at(-1).includes('/share/download?code=ABCD2345'))
t.mock.timers.tick(1000); f.code.value=detail.code; await f.handleSubmit()
assert.equal(f.records.value.length,1)
assert.equal(f.selectedRecord.value.queriedAt,'2026-09-18T07:00:02.000Z')
assert.equal(f.selectedRecord.value.retrievedAt,'2026-09-18T07:00:01.000Z')
t.mock.timers.tick(1000);f.downloadRecord(f.records.value[0])
assert.equal(f.selectedRecord.value.retrievedAt,'2026-09-18T07:00:03.000Z')
} finally {service.selectFile=original;t.mock.timers.reset()}
})
test('empty or failed download actions do not fabricate retrieval times', async () => {
const f=await flow(), record={id:1,code:'ABCD2345',filename:'a',size:'0',date:'legacy',content:null,downloadUrl:null}
f.downloadRecord(record);assert.equal(record.retrievedAt,undefined)
assert.throws(()=>f.downloadRecord({...record,content:''}), /Browser download/)
assert.equal(record.retrievedAt,undefined)
})
async function render(component,props){
const context={},app=createSSRApp({render:()=>h(component,props)});app.use(i18n())
return (await renderToString(app,context))+Object.values(context.teleports||{}).join('')
}
test('dialog and records show legacy date as query time and no invented retrieval',async()=>{
const record={id:1,code:'ABCD2345',filename:'file.apk',size:'3 B',date:'2026/9/18 15:00:00',content:null,downloadUrl:'/share/download?code=ABCD2345'}
for(const [component,props] of [[Detail,{visible:true,record}],[List,{records:[record]}]]){
const html=await render(component,props)
for(const text of ['查件时间','取件时间','尚未取件',record.date]) assert.ok(html.includes(text),text)
}
record.retrievedAt='2026-09-18T07:01:00Z'
const html=await render(Detail,{visible:true,record})
assert.ok(!html.includes('尚未取件'));assert.ok(html.includes(new Date(record.retrievedAt).toLocaleString()))
assert.ok(html.includes('不代表下载完成'))
})
test('text lookups preserve the signed download entry and clicking records retrieval', async () => {
const original=service.selectFile, f=await flow()
service.selectFile=async()=>({code:200,detail:{...detail,type:'text',is_text:true,content:'',text:''}})
try {
f.code.value=detail.code;await f.handleSubmit()
assert.equal(f.selectedRecord.value.content,'')
assert.equal(f.selectedRecord.value.downloadUrl,detail.download_url)
assert.equal(f.selectedRecord.value.retrievedAt,null)
f.downloadRecord(f.selectedRecord.value)
assert.ok(opened.at(-1).includes(detail.download_url))
assert.ok(f.selectedRecord.value.retrievedAt)
} finally { service.selectFile=original }
})
test('admin lifecycle formats lookup and retrieval events in the supplied chronological order', async () => {
const createAdmin=(await server.ssrLoadModule('/src/composables/useAdminFiles.ts')).useAdminFiles
let admin
const app=createSSRApp({setup(){admin=createAdmin();return()=>h('div')}})
app.use(createPinia());app.use(i18n());await renderToString(app)
const original=service.getAdminFileDetail
const file={id:42,code:'LIFE2345',prefix:'sample',suffix:'.txt',size:3,used_count:1,expired_count:3,created_at:'2026-09-18T07:00:00Z',timeline:[
{key:'retrieved',value:1,status:'done'},
{key:'queried_event',value:1,status:'done',detail:'127.0.0.1',timestamp:'2026-09-18T07:01:00Z'},
{key:'retrieved_event',value:1,status:'done',detail:'127.0.0.1',timestamp:'2026-09-18T07:02:00Z'},
{key:'queried_event',value:2,status:'done',detail:'127.0.0.1',timestamp:'2026-09-18T07:03:00Z'}
]}
service.getAdminFileDetail=async()=>({code:200,detail:file})
try {
await admin.openFileDetail(file)
const rows=admin.selectedFileDetail.value.detailTimeline
assert.deepEqual(rows.map(x=>x.displayTitle),['取件记录','第 1 次查件','第 1 次取件','第 2 次查件'])
assert.ok(rows[1].displayDescription.includes('127.0.0.1'))
assert.ok(rows[2].displayDescription.includes('不代表下载完成'))
} finally { service.getAdminFileDetail=original }
})
+26
View File
@@ -0,0 +1,26 @@
import {test,before,after} from 'node:test'
import assert from 'node:assert/strict'
import {createServer} from 'vite'
import {fileURLToPath} from 'node:url'
import {createSSRApp,h} from 'vue'
import {renderToString} from 'vue/server-renderer'
import {createI18n} from 'vue-i18n'
let server,Area,Detail,zh,originalWindow
before(async()=>{originalWindow=globalThis.window;globalThis.window={location:{origin:'https://test.example'}};server=await createServer({resolve:{alias:{'file-saver':fileURLToPath(new URL('./fixtures/browser-save.stub.mjs',import.meta.url))}},server:{middlewareMode:true,watch:null},appType:'custom'});Area=(await server.ssrLoadModule('/src/components/common/FileUploadArea.vue')).default;Detail=(await server.ssrLoadModule('/src/components/common/FileDetailModal.vue')).default;zh=(await server.ssrLoadModule('/src/i18n/locales/zh-CN.ts')).default})
after(async()=>{await server?.close();globalThis.window=originalWindow})
async function render(component,props){const context={};const app=createSSRApp({render:()=>h(component,props)});app.use(createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}}));return (await renderToString(app,context))+Object.values(context.teleports||{}).join('')}
test('upload area displays actual bytes while sending and verifying',async()=>{
for(const uploadStatus of ['uploading','confirming']){const html=await render(Area,{uploadStatus,uploadedBytes:52428800,totalBytes:94371840,progress:50});assert.ok(html.includes('50 MB / 90 MB'));assert.ok(!html.includes('0 B / 0 B'))}
})
test('retrieval detail uses accessible shared dialog and exposes entire long filename',async()=>{
const filename='FlClash-'+'long-'.repeat(25)+'android-arm64-v8a.apk';const html=await render(Detail,{visible:true,record:{filename,size:'51.58 MB',date:'2026/09/18 15:08:09',code:'ABCD2345',downloadUrl:'/share/download?code=ABCD2345'}})
assert.ok(html.includes('role="dialog"'));assert.ok(html.includes(filename));assert.ok(html.includes('aria-modal="true"'));assert.ok(html.includes('点击下载'))
})
test('retrieve form enables both complete legacy and current codes without truncating eight digits',async()=>{
const Form=(await server.ssrLoadModule('/src/components/common/RetrieveForm.vue')).default
for(const code of ['ABCDE','ABCD2345']){
const html=await render(Form,{modelValue:code,inputStatus:{readonly:false,loading:false}})
assert.ok(html.includes('maxlength="8"'));assert.ok(html.includes(`value="${code}"`));assert.ok(!/<button[^>]* disabled(?:=|>| )/.test(html))
}
const html=await render(Form,{modelValue:'ABC',inputStatus:{readonly:false,loading:false}});assert.ok(/<button[^>]* disabled(?:=|>| )/.test(html))
})
@@ -0,0 +1,41 @@
import {test,before,after} from 'node:test'
import assert from 'node:assert/strict'
import {createServer} from 'vite'
let server,upload,service,Control
before(async()=>{
server=await createServer({server:{middlewareMode:true,watch:null,hmr:false},optimizeDeps:{noDiscovery:true,include:[]},appType:'custom'})
service=(await server.ssrLoadModule('/src/services/file.ts')).FileService
upload=(await server.ssrLoadModule('/src/services/upload-strategy.ts')).uploadChunkedFile
Control=(await server.ssrLoadModule('/src/services/upload-cancellation.ts')).UploadCancellation
globalThis.window={isSecureContext:true}
})
after(async()=>{await server?.close();delete globalThis.window})
test('cancel during chunk stops later chunks, waits for cleanup and does not publish',async()=>{
const original={init:service.initChunkUpload,chunk:service.uploadChunk,complete:service.completeChunkUpload,cancel:service.cancelChunkUpload};const control=new Control();let chunks=0,cleanup=0,completes=0
service.initChunkUpload=async()=>({code:200,detail:{upload_id:'cancel-id',chunk_size:4,uploaded_chunks:[]}})
service.uploadChunk=async(id,i,chunk,progress,signal)=>{chunks++;control.request();throw new DOMException('Aborted','AbortError')}
service.cancelChunkUpload=async id=>{assert.equal(id,'cancel-id');cleanup++;return {code:200,detail:{cancelled:true}}}
service.completeChunkUpload=async()=>{completes++;return {code:200}}
try{await assert.rejects(upload(new File(['abcdefghijkl'],'a.txt'),{expireValue:1,expireStyle:'day',cancellation:control}),/上传已中断/);assert.equal(chunks,1);assert.equal(cleanup,1);assert.equal(completes,0)}finally{Object.assign(service,{initChunkUpload:original.init,uploadChunk:original.chunk,completeChunkUpload:original.complete,cancelChunkUpload:original.cancel})}
})
test('cancel while initialization is pending cleans the returned id rather than leaking session',async()=>{
const original={init:service.initChunkUpload,cancel:service.cancelChunkUpload};const control=new Control();let cleaned=false
service.initChunkUpload=async()=>{control.request();return {code:200,detail:{upload_id:'late-id',chunk_size:4}}}
service.cancelChunkUpload=async id=>{cleaned=id==='late-id';return {code:200,detail:{cancelled:true}}}
try{await assert.rejects(upload(new File(['abcd'],'b.txt'),{expireValue:1,expireStyle:'day',cancellation:control}),/上传已中断/);assert.ok(cleaned)}finally{service.initChunkUpload=original.init;service.cancelChunkUpload=original.cancel}
})
test('failed cancellation cleanup is retryable and next submission initializes a new session',async()=>{
const original={init:service.initChunkUpload,chunk:service.uploadChunk,complete:service.completeChunkUpload,cancel:service.cancelChunkUpload}
const control=new Control();let inits=0,cancelCalls=0,completeCalls=0
service.initChunkUpload=async()=>({code:200,detail:{upload_id:'id-'+(++inits),chunk_size:4,uploaded_chunks:[]}})
service.uploadChunk=async()=>({code:200})
service.completeChunkUpload=async()=>{completeCalls++;if(completeCalls===1){control.request();throw new Error('aborted')}return {code:200,detail:{code:'NEWCODE1'}}}
service.cancelChunkUpload=async()=>{cancelCalls++;if(cancelCalls===1)throw new Error('cleanup unavailable');return {code:200,detail:{cancelled:true}}}
const file=new File(['abcd'],'retry.txt')
try{
await assert.rejects(upload(file,{expireValue:1,expireStyle:'day',cancellation:control}),/cleanup unavailable/)
assert.equal(control.needsCleanup,true);await control.clean();assert.equal(control.needsCleanup,false)
const done=await upload(file,{expireValue:1,expireStyle:'day',cancellation:new Control()})
assert.equal(done.detail.code,'NEWCODE1');assert.equal(inits,2)
}finally{Object.assign(service,{initChunkUpload:original.init,uploadChunk:original.chunk,completeChunkUpload:original.complete,cancelChunkUpload:original.cancel})}
})
+18 -1
View File
@@ -3,7 +3,7 @@ import assert from 'node:assert/strict'
import {createServer} from 'vite' import {createServer} from 'vite'
let server,upload,service let server,upload,service
before(async()=>{ before(async()=>{
server=await createServer({server:{middlewareMode:true,watch:null},appType:'custom'}) server=await createServer({optimizeDeps:{noDiscovery:true,include:[]},server:{middlewareMode:true,watch:null},appType:'custom'})
service=(await server.ssrLoadModule('/src/services/file.ts')).FileService service=(await server.ssrLoadModule('/src/services/file.ts')).FileService
upload=(await server.ssrLoadModule('/src/services/upload-strategy.ts')).uploadChunkedFile upload=(await server.ssrLoadModule('/src/services/upload-strategy.ts')).uploadChunkedFile
}) })
@@ -22,3 +22,20 @@ test('manual retry after lost completion response reuses upload id and never ret
assert.equal(result.detail.code,'ORIGINAL');assert.equal(inits,1);assert.equal(chunks,1);assert.equal(completions,5) assert.equal(result.detail.code,'ORIGINAL');assert.equal(inits,1);assert.equal(chunks,1);assert.equal(completions,5)
}finally{service.initChunkUpload=originals.init;service.uploadChunk=originals.chunk;service.completeChunkUpload=originals.complete;globalThis.window=previousWindow} }finally{service.initChunkUpload=originals.init;service.uploadChunk=originals.chunk;service.completeChunkUpload=originals.complete;globalThis.window=previousWindow}
}) })
test('small file initialization never requests a chunk bigger than the file',async()=>{
const originalInit=service.initChunkUpload;let size
const previousWindow=globalThis.window;globalThis.window={isSecureContext:true}
service.initChunkUpload=async request=>{size=request.chunk_size;return {code:200,detail:{existed:true,code:'existing'}}}
try{await upload(new File(['small'],'a.txt'),{expireValue:1,expireStyle:'day'});assert.equal(size,5)}finally{service.initChunkUpload=originalInit;globalThis.window=previousWindow}
})
test('configured chunk size determines new requests; server session size controls resumed slicing',async()=>{
const original={init:service.initChunkUpload,chunk:service.uploadChunk,complete:service.completeChunkUpload};const previousWindow=globalThis.window;globalThis.window={isSecureContext:true}
let requested;const slices=[]
service.initChunkUpload=async request=>{requested=request.chunk_size;return {code:200,detail:{upload_id:'configured',chunk_size:1048576,uploaded_chunks:[0]}}}
service.uploadChunk=async(id,index,blob)=>{slices.push([index,blob.size]);return {code:200}}
service.completeChunkUpload=async()=>({code:200,detail:{code:'CONFIG01'}})
try{
await upload(new File([new Uint8Array(3*1048576+1)],'configured.bin'),{expireValue:1,expireStyle:'day',chunkSizeMB:2})
assert.equal(requested,2*1048576);assert.deepEqual(slices,[[1,1048576],[2,1048576],[3,1]])
}finally{service.initChunkUpload=original.init;service.uploadChunk=original.chunk;service.completeChunkUpload=original.complete;globalThis.window=previousWindow}
})