🔀 merge: 合并本地文件浏览与分享完整流程
This commit is contained in:
commit
e8c12af834
16 files changed
+402
No files matched your search
@@ -14,3 +14,5 @@ export { useSendFlow } from './useSendFlow'
|
|||||||
export { useSystemConfig } from './useSystemConfig'
|
export { useSystemConfig } from './useSystemConfig'
|
||||||
export { useTheme } from './useTheme'
|
export { useTheme } from './useTheme'
|
||||||
export { useTransferAnalytics } from './useTransferAnalytics'
|
export { useTransferAnalytics } from './useTransferAnalytics'
|
||||||
|
|
||||||
|
export { useLocalFiles } from './useLocalFiles'
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
import { computed, onScopeDispose, ref } from 'vue'
|
||||||
|
import { ConfigService, LocalShareService } from '@/services'
|
||||||
|
import type { LocalFileEntry, LocalShareResult } from '@/types'
|
||||||
|
import { buildLocalShareRequest, expirationChoices, localBreadcrumbs } from '@/utils/local-share'
|
||||||
|
import { copyToClipboard } from '@/utils/clipboard'
|
||||||
|
import { buildRetrieveUrl } from '@/utils/share-url'
|
||||||
|
import { getErrorMessage } from '@/utils/common'
|
||||||
|
|
||||||
|
export function useLocalFiles() {
|
||||||
|
const path = ref(''), parent = ref(''), items = ref<LocalFileEntry[]>([])
|
||||||
|
const page = ref(1), size = ref(20), total = ref(0), keyword = ref('')
|
||||||
|
const loading = ref(false), error = ref(''), configError = ref('')
|
||||||
|
const styles = ref<string[]>([]), maxSaveSeconds = ref(0), configReady = ref(false)
|
||||||
|
const selected = ref<LocalFileEntry | null>(null), sharing = ref(false), shareError = ref('')
|
||||||
|
const expireStyle = ref(''), expireValue = ref('1'), result = ref<LocalShareResult | null>(null), copyStatus = ref('')
|
||||||
|
const choices = computed(() => expirationChoices(styles.value))
|
||||||
|
const breadcrumbs = computed(() => localBreadcrumbs(path.value))
|
||||||
|
const shareUrl = computed(() => result.value ? buildRetrieveUrl(result.value.code) : '')
|
||||||
|
let requestId = 0
|
||||||
|
onScopeDispose(() => { requestId++ })
|
||||||
|
|
||||||
|
const loadConfig = async () => {
|
||||||
|
configReady.value = false; configError.value = ''
|
||||||
|
try {
|
||||||
|
const response = await ConfigService.getUserConfig()
|
||||||
|
if (response.code !== 200 || !response.detail) throw new Error('分享配置加载失败')
|
||||||
|
styles.value = response.detail.config.expireStyle || []
|
||||||
|
maxSaveSeconds.value = response.detail.config.max_save_seconds || 0
|
||||||
|
configReady.value = true
|
||||||
|
} catch (err) { configError.value = getErrorMessage(err, '分享配置加载失败,请重试') }
|
||||||
|
}
|
||||||
|
const load = async (nextPath = path.value, nextPage = page.value) => {
|
||||||
|
const id = ++requestId
|
||||||
|
if (nextPath !== path.value) { keyword.value = ''; nextPage = 1 }
|
||||||
|
path.value = nextPath; loading.value = true; error.value = ''
|
||||||
|
try {
|
||||||
|
const response = await LocalShareService.list({ path: nextPath, page: nextPage, size: size.value, keyword: keyword.value.trim() })
|
||||||
|
if (id !== requestId) return
|
||||||
|
if (response.code !== 200 || !response.detail) throw new Error('目录加载失败')
|
||||||
|
const data = response.detail
|
||||||
|
items.value = data.items; path.value = data.path; parent.value = data.parent
|
||||||
|
page.value = data.page; size.value = data.size; total.value = data.total
|
||||||
|
} catch (err) {
|
||||||
|
if (id !== requestId) return
|
||||||
|
items.value = []; total.value = 0; error.value = getErrorMessage(err, '无法读取目录,请重试')
|
||||||
|
} finally { if (id === requestId) loading.value = false }
|
||||||
|
}
|
||||||
|
const search = () => load(path.value, 1)
|
||||||
|
const changeSize = (value: number) => { size.value = value; return load(path.value, 1) }
|
||||||
|
const openShare = (item: LocalFileEntry) => {
|
||||||
|
if (item.type !== 'file' || !configReady.value || !choices.value.length || sharing.value) return
|
||||||
|
selected.value = item; result.value = null; shareError.value = ''; copyStatus.value = ''
|
||||||
|
expireStyle.value = choices.value[0].value; expireValue.value = '1'
|
||||||
|
}
|
||||||
|
const closeShare = () => { if (!sharing.value) selected.value = null }
|
||||||
|
const share = async () => {
|
||||||
|
if (!selected.value || sharing.value || result.value) return
|
||||||
|
shareError.value = ''
|
||||||
|
try {
|
||||||
|
const payload = buildLocalShareRequest(selected.value.path, expireStyle.value, expireValue.value, styles.value)
|
||||||
|
sharing.value = true
|
||||||
|
const response = await LocalShareService.share(payload)
|
||||||
|
if (response.code !== 200 || !response.detail?.code) throw new Error('未收到取件码,请到文件管理核对')
|
||||||
|
result.value = response.detail
|
||||||
|
} catch (err) { shareError.value = getErrorMessage(err, '生成取件码失败,请重试') }
|
||||||
|
finally { sharing.value = false }
|
||||||
|
}
|
||||||
|
const copy = async (kind: 'code' | 'link') => {
|
||||||
|
if (!result.value) return
|
||||||
|
const ok = await copyToClipboard(kind === 'code' ? result.value.code : shareUrl.value, { showMsg: false })
|
||||||
|
copyStatus.value = ok ? (kind === 'code' ? '取件码已复制' : '分享链接已复制') : '请从下方手动复制'
|
||||||
|
}
|
||||||
|
return { path, parent, items, page, size, total, keyword, loading, error, configError, configReady, maxSaveSeconds,
|
||||||
|
selected, sharing, shareError, expireStyle, expireValue, result, copyStatus, choices, breadcrumbs, shareUrl,
|
||||||
|
loadConfig, load, search, changeSize, openShare, closeShare, share, copy }
|
||||||
|
}
|
||||||
@@ -69,6 +69,7 @@ export const ROUTES = {
|
|||||||
DASHBOARD: '/admin/dashboard',
|
DASHBOARD: '/admin/dashboard',
|
||||||
FILE_MANAGE: '/admin/files',
|
FILE_MANAGE: '/admin/files',
|
||||||
TRASH: '/admin/trash',
|
TRASH: '/admin/trash',
|
||||||
|
LOCAL_FILES: '/admin/local',
|
||||||
ACTIVITY_LOG: '/admin/activities',
|
ACTIVITY_LOG: '/admin/activities',
|
||||||
SETTINGS: '/admin/settings'
|
SETTINGS: '/admin/settings'
|
||||||
} as const
|
} as const
|
||||||
@@ -81,6 +82,7 @@ export const ROUTE_NAMES = {
|
|||||||
DASHBOARD: 'Dashboard',
|
DASHBOARD: 'Dashboard',
|
||||||
FILE_MANAGE: 'FileManage',
|
FILE_MANAGE: 'FileManage',
|
||||||
TRASH: 'Trash',
|
TRASH: 'Trash',
|
||||||
|
LOCAL_FILES: 'LocalFiles',
|
||||||
ACTIVITY_LOG: 'ActivityLog',
|
ACTIVITY_LOG: 'ActivityLog',
|
||||||
SETTINGS: 'Settings'
|
SETTINGS: 'Settings'
|
||||||
} as const
|
} as const
|
||||||
|
|||||||
@@ -126,6 +126,7 @@ import {
|
|||||||
MenuIcon,
|
MenuIcon,
|
||||||
XIcon,
|
XIcon,
|
||||||
FolderIcon,
|
FolderIcon,
|
||||||
|
HardDriveIcon,
|
||||||
Trash2Icon,
|
Trash2Icon,
|
||||||
CogIcon,
|
CogIcon,
|
||||||
LayoutDashboardIcon,
|
LayoutDashboardIcon,
|
||||||
@@ -162,6 +163,12 @@ const menuItems: MenuItem[] = [
|
|||||||
icon: FolderIcon,
|
icon: FolderIcon,
|
||||||
redirect: ROUTES.FILE_MANAGE
|
redirect: ROUTES.FILE_MANAGE
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: ROUTE_NAMES.LOCAL_FILES,
|
||||||
|
name: '本地文件',
|
||||||
|
icon: HardDriveIcon,
|
||||||
|
redirect: ROUTES.LOCAL_FILES
|
||||||
|
},
|
||||||
{
|
{
|
||||||
id: ROUTE_NAMES.TRASH,
|
id: ROUTE_NAMES.TRASH,
|
||||||
name: '回收站',
|
name: '回收站',
|
||||||
|
|||||||
@@ -59,6 +59,12 @@ const routes: RouteRecordRaw[] = [
|
|||||||
title: 'files'
|
title: 'files'
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: 'local',
|
||||||
|
name: ROUTE_NAMES.LOCAL_FILES,
|
||||||
|
component: () => import('@/views/manage/LocalFilesView.vue'),
|
||||||
|
meta: { ...adminPageMeta, title: 'localFiles' }
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: 'trash',
|
path: 'trash',
|
||||||
name: ROUTE_NAMES.TRASH,
|
name: ROUTE_NAMES.TRASH,
|
||||||
|
|||||||
@@ -7,3 +7,5 @@ export { PresignUploadService } from './presign-upload'
|
|||||||
export { StatsService } from './stats'
|
export { StatsService } from './stats'
|
||||||
export { TrashService } from './trash'
|
export { TrashService } from './trash'
|
||||||
export { uploadChunkedFile } from './upload-strategy'
|
export { uploadChunkedFile } from './upload-strategy'
|
||||||
|
|
||||||
|
export { LocalShareService } from './local-share'
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import api from './client'
|
||||||
|
import type { ApiResponse, LocalFileListing, LocalShareRequest, LocalShareResult } from '@/types'
|
||||||
|
|
||||||
|
export class LocalShareService {
|
||||||
|
static list(params: { path: string; page: number; size: number; keyword: string }): Promise<ApiResponse<LocalFileListing>> {
|
||||||
|
return api.get('/admin/local/lists', { params })
|
||||||
|
}
|
||||||
|
static share(request: LocalShareRequest): Promise<ApiResponse<LocalShareResult>> {
|
||||||
|
return api.post('/admin/local/share', request)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,3 +7,5 @@ export * from './file'
|
|||||||
export * from './presign-upload'
|
export * from './presign-upload'
|
||||||
export * from './trash'
|
export * from './trash'
|
||||||
export * from './ui'
|
export * from './ui'
|
||||||
|
|
||||||
|
export * from './local-share'
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
export interface LocalFileEntry {
|
||||||
|
name: string
|
||||||
|
file: string
|
||||||
|
path: string
|
||||||
|
type: 'dir' | 'file'
|
||||||
|
ctime: string | null
|
||||||
|
size: number | null
|
||||||
|
}
|
||||||
|
export interface LocalFileListing {
|
||||||
|
path: string
|
||||||
|
parent: string
|
||||||
|
items: LocalFileEntry[]
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
size: number
|
||||||
|
truncated: boolean
|
||||||
|
}
|
||||||
|
export interface LocalShareRequest { filename: string; expire_style: string; expire_value: number }
|
||||||
|
export interface LocalShareResult { id: number; code: string; name: string; path: string }
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
const labels: Record<string, string> = { day: '按天', hour: '按小时', minute: '按分钟', count: '按取件次数(最长 1 天)', forever: '永久有效' }
|
||||||
|
|
||||||
|
export function expirationChoices(styles: string[]) {
|
||||||
|
return [...new Set(styles)].filter(style => Object.prototype.hasOwnProperty.call(labels, style)).map(value => ({ value, label: labels[value] }))
|
||||||
|
}
|
||||||
|
|
||||||
|
export function localBreadcrumbs(path: string) {
|
||||||
|
const parts = path ? path.split('/') : []
|
||||||
|
return [{ name: '本地文件', path: '' }, ...parts.map((name, index) => ({ name, path: parts.slice(0, index + 1).join('/') }))]
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildLocalShareRequest(filename: string, style: string, value: string, allowed: string[]) {
|
||||||
|
if (!filename) throw new Error('请先选择文件')
|
||||||
|
if (!allowed.includes(style) || !Object.prototype.hasOwnProperty.call(labels, style)) throw new Error('请选择允许的有效期方式')
|
||||||
|
const amount = style === 'forever' ? 1 : Number(value)
|
||||||
|
if (!Number.isSafeInteger(amount) || amount < 1 || amount > 1_000_000) throw new Error('请输入 1 到 1000000 的整数')
|
||||||
|
return { filename, expire_style: style, expire_value: amount }
|
||||||
|
}
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
<template>
|
||||||
|
<div class="p-4 sm:p-6">
|
||||||
|
<header class="mb-5 flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||||
|
<div>
|
||||||
|
<p class="hidden text-xs font-medium tracking-[0.16em] sm:block" :class="mutedClass">LOCAL FILES</p>
|
||||||
|
<h2 class="mt-1 text-xl font-bold sm:text-2xl">本地文件</h2>
|
||||||
|
<p class="mt-2 max-w-2xl text-sm leading-6" :class="mutedClass">给服务器已有文件生成取件码,无需再次上传。分享过期或清理分享记录,原文件仍保留。</p>
|
||||||
|
</div>
|
||||||
|
<BaseButton variant="secondary" :loading="loading" :disabled="sharing" @click="load()"><template #icon><RefreshCwIcon class="mr-2 h-4 w-4" /></template>刷新目录</BaseButton>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<details class="theme-2026-card mb-5 rounded-2xl border p-4 text-sm" :class="panelClass">
|
||||||
|
<summary class="min-h-7 cursor-pointer font-medium">文件放在哪里?</summary>
|
||||||
|
<p class="mt-3 leading-6" :class="mutedClass">将已有文件放入应用数据目录的 <code>local</code> 文件夹,或把 NAS 目录挂载到容器的 <code>/app/data/local</code>。支持子目录;此处只生成分享,不会把原件复制到 WebDAV 或 S3。</p>
|
||||||
|
<p class="mt-2 leading-6" :class="mutedClass">接收者通过取件码下载。分享期间请保持原文件可读,移动、删除或修改原文件会影响下载;已有分享可在“文件管理”调整或删除。</p>
|
||||||
|
</details>
|
||||||
|
|
||||||
|
<section class="theme-2026-card overflow-hidden rounded-[24px] border" :class="panelClass" aria-label="本地文件浏览器" :aria-busy="loading">
|
||||||
|
<div class="border-b p-4" :class="borderClass">
|
||||||
|
<nav aria-label="目录位置" class="mb-4 flex flex-wrap items-center gap-1 text-sm">
|
||||||
|
<template v-for="(crumb, index) in breadcrumbs" :key="crumb.path">
|
||||||
|
<ChevronRightIcon v-if="index" class="h-4 w-4 shrink-0 opacity-50" aria-hidden="true" />
|
||||||
|
<button type="button" class="fcb-action min-h-11 max-w-full break-all rounded-xl px-2 text-left font-medium hover:underline disabled:opacity-60" :disabled="loading || sharing" :aria-current="index === breadcrumbs.length - 1 ? 'location' : undefined" @click="navigate(crumb.path)">{{ crumb.name }}</button>
|
||||||
|
</template>
|
||||||
|
</nav>
|
||||||
|
<form class="flex flex-wrap items-end gap-2" @submit.prevent="search">
|
||||||
|
<label class="min-w-0 flex-1"><span class="mb-1 block text-xs font-medium" :class="mutedClass">在当前目录搜索</span><input v-model="keyword" type="search" maxlength="255" placeholder="文件或文件夹名称" :disabled="loading || sharing" class="min-h-11 w-full rounded-xl border px-3" /></label>
|
||||||
|
<BaseButton type="submit" :disabled="loading || sharing">搜索</BaseButton>
|
||||||
|
<BaseButton v-if="keyword" variant="secondary" :disabled="loading || sharing" @click="keyword = ''; search()">清空</BaseButton>
|
||||||
|
</form>
|
||||||
|
<div class="mt-3 flex flex-wrap items-center justify-between gap-2 text-xs" :class="mutedClass">
|
||||||
|
<span v-if="!loading && !error">{{ total }} 项 · 文件夹优先</span>
|
||||||
|
<BaseButton v-if="path" size="sm" variant="outline" :disabled="loading || sharing" @click="navigate(path.split('/').slice(0, -1).join('/'))">返回上一级</BaseButton>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="configError" role="alert" class="border-b p-4 text-sm text-red-700 dark:text-red-200" :class="borderClass">{{ configError }} <button type="button" class="fcb-action min-h-11 px-2 underline" @click="loadConfig">重试配置</button></div>
|
||||||
|
<p v-else-if="configReady && !choices.length" role="alert" class="p-4 text-sm" :class="mutedClass">未配置可用的分享有效期,请先在系统设置中启用。</p>
|
||||||
|
<div v-if="loading" role="status" class="flex min-h-40 items-center justify-center text-sm" :class="mutedClass"><RefreshCwIcon class="mr-2 h-4 w-4 animate-spin" />正在读取目录…</div>
|
||||||
|
<div v-else-if="error" role="alert" class="p-6 text-center"><p class="text-sm text-red-700 dark:text-red-200">{{ error }}</p><BaseButton variant="secondary" class="mt-3" @click="load()">重试目录</BaseButton></div>
|
||||||
|
<div v-else-if="!items.length" class="px-4 py-12 text-center" :class="mutedClass">
|
||||||
|
<FolderOpenIcon class="mx-auto h-9 w-9" aria-hidden="true" />
|
||||||
|
<p class="mt-3 text-sm">{{ keyword ? '当前目录没有匹配的文件' : '当前目录还没有文件' }}</p>
|
||||||
|
<p class="mt-2 text-xs">{{ keyword ? '试试其他名称,或清空搜索。' : '放入文件后刷新目录,即可直接生成分享。' }}</p>
|
||||||
|
</div>
|
||||||
|
<ul v-else class="divide-y" :class="borderClass">
|
||||||
|
<li v-for="item in items" :key="item.path" class="fcb-interactive-row flex items-center gap-3 px-4 py-4 sm:px-6">
|
||||||
|
<FolderIcon v-if="item.type === 'dir'" class="h-6 w-6 shrink-0 text-[#648b80]" aria-hidden="true" />
|
||||||
|
<FileIcon v-else class="h-6 w-6 shrink-0 opacity-60" aria-hidden="true" />
|
||||||
|
<div class="min-w-0 flex-1">
|
||||||
|
<button v-if="item.type === 'dir'" type="button" class="fcb-action min-h-11 w-full break-all text-left text-sm font-semibold hover:underline" :disabled="sharing" @click="navigate(item.path)">{{ item.name }}</button>
|
||||||
|
<p v-else class="break-all text-sm font-semibold">{{ item.name }}</p>
|
||||||
|
<p class="mt-1 text-xs" :class="mutedClass">{{ item.type === 'dir' ? '文件夹' : formatFileSize(item.size || 0) }}</p>
|
||||||
|
</div>
|
||||||
|
<BaseButton v-if="item.type === 'dir'" variant="secondary" size="sm" :disabled="sharing" :aria-label="`打开 ${item.name}`" @click="navigate(item.path)">打开</BaseButton>
|
||||||
|
<BaseButton v-else size="sm" :disabled="!configReady || !choices.length || sharing" :aria-label="`分享 ${item.name}`" @click="openShare(item)">分享</BaseButton>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<DataPagination v-if="total && !loading && !error" :current-page="page" :page-size="size" :total="total" @page-change="load(path, $event)" @page-size-change="changeSize" />
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<BaseModal :show="Boolean(selected)" :title="result ? '分享已生成' : '生成取件码'" :closable="!sharing" :close-on-backdrop="!sharing" @close="closeShare">
|
||||||
|
<p class="mb-1 break-all text-sm font-semibold">{{ selected?.name }}</p>
|
||||||
|
<p class="mb-4 break-all text-xs" :class="mutedClass">{{ selected?.path }}</p>
|
||||||
|
<div v-if="result" class="space-y-4">
|
||||||
|
<p role="status" class="text-sm">取件码已生成。原文件保留,分享已加入文件管理。</p>
|
||||||
|
<label class="block"><span class="mb-1 block text-sm font-medium">取件码</span><input :value="result.code" readonly class="min-h-12 w-full rounded-xl border px-3 font-mono text-xl tracking-widest" @focus="selectText" /></label>
|
||||||
|
<label class="block"><span class="mb-1 block text-sm font-medium">分享链接</span><input :value="shareUrl" readonly class="min-h-11 w-full rounded-xl border px-3 text-sm" @focus="selectText" /></label>
|
||||||
|
<div class="flex flex-wrap gap-2"><BaseButton @click="copy('code')">复制取件码</BaseButton><BaseButton variant="secondary" @click="copy('link')">复制链接</BaseButton></div>
|
||||||
|
<p v-if="copyStatus" role="status" class="text-sm" :class="mutedClass">{{ copyStatus }}</p>
|
||||||
|
</div>
|
||||||
|
<form v-else id="local-share-form" class="space-y-4" @submit.prevent="share">
|
||||||
|
<fieldset :disabled="sharing">
|
||||||
|
<ExpirationSelector v-model:expiration-method="expireStyle" v-model:expiration-value="expireValue" :options="choices" />
|
||||||
|
</fieldset>
|
||||||
|
<p class="text-xs leading-6" :class="mutedClass">{{ maxSaveSeconds > 0 ? `按时间分享最长 ${formatDuration(maxSaveSeconds, t)}` : '按时间分享最长 7 天' }}。次数分享最长保留 1 天;永久分享需由管理员手动取消。</p>
|
||||||
|
<p class="text-sm leading-6" :class="mutedClass">只生成取件码,不复制文件。请勿移动或删除原文件;删除分享不会删除原件。</p>
|
||||||
|
<p v-if="shareError" role="alert" class="text-sm text-red-700 dark:text-red-200">{{ shareError }}</p>
|
||||||
|
</form>
|
||||||
|
<template #footer>
|
||||||
|
<BaseButton v-if="result" variant="secondary" @click="closeShare">完成</BaseButton>
|
||||||
|
<template v-else><BaseButton variant="secondary" :disabled="sharing" @click="closeShare">取消</BaseButton><BaseButton type="submit" form="local-share-form" :loading="sharing">生成取件码</BaseButton></template>
|
||||||
|
</template>
|
||||||
|
</BaseModal>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed, onMounted, watch } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { useI18n } from 'vue-i18n'
|
||||||
|
import { ChevronRightIcon, FileIcon, FolderIcon, FolderOpenIcon, RefreshCwIcon } from 'lucide-vue-next'
|
||||||
|
import BaseButton from '@/components/common/BaseButton.vue'
|
||||||
|
import BaseModal from '@/components/common/BaseModal.vue'
|
||||||
|
import DataPagination from '@/components/common/DataPagination.vue'
|
||||||
|
import ExpirationSelector from '@/components/common/ExpirationSelector.vue'
|
||||||
|
import { useInjectedDarkMode, useLocalFiles } from '@/composables'
|
||||||
|
import { formatFileSize, formatDuration } from '@/utils/common'
|
||||||
|
const isDarkMode = useInjectedDarkMode(), router = useRouter(), route = useRoute()
|
||||||
|
const { t } = useI18n()
|
||||||
|
const { path, items, page, size, total, keyword, loading, error, configError, configReady, maxSaveSeconds,
|
||||||
|
selected, sharing, shareError, expireStyle, expireValue, result, copyStatus, choices, breadcrumbs, shareUrl,
|
||||||
|
loadConfig, load, search, changeSize, openShare, closeShare, share, copy } = useLocalFiles()
|
||||||
|
const mutedClass = computed(() => isDarkMode.value ? 'text-[#adbec6]' : 'text-[#617980]')
|
||||||
|
const panelClass = computed(() => isDarkMode.value ? 'border-[#495765] bg-[#252b34]' : 'border-[#d7e3e5] bg-[#f8fbfb]')
|
||||||
|
const borderClass = computed(() => isDarkMode.value ? 'divide-[#495765] border-[#495765]' : 'divide-[#d7e3e5] border-[#d7e3e5]')
|
||||||
|
const queryPath = () => typeof route.query.path === 'string' ? route.query.path : ''
|
||||||
|
const navigate = (nextPath: string) => {
|
||||||
|
if (sharing.value) return
|
||||||
|
if (nextPath === queryPath()) { void load(nextPath, 1); return }
|
||||||
|
void router.push({ query: nextPath ? { path: nextPath } : {} })
|
||||||
|
}
|
||||||
|
const selectText = (event: FocusEvent) => (event.target as HTMLInputElement).select()
|
||||||
|
onMounted(() => { void loadConfig(); void load(queryPath(), 1) })
|
||||||
|
watch(() => route.query.path, () => { void load(queryPath(), 1) })
|
||||||
|
</script>
|
||||||
@@ -61,3 +61,11 @@ Primary submit actions must not add white/gradient hover overlays.
|
|||||||
Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http` 和 `network`
|
Playwright Page。Vite 固定运行于 `127.0.0.1:5180`;分别传入 `http` 和 `network`
|
||||||
验证服务端 500、断网时错误显示于弹窗内、原记录保留,以及重新打开时清空旧错误。
|
验证服务端 500、断网时错误显示于弹窗内、原记录保留,以及重新打开时清空旧错误。
|
||||||
测试拦截全部管理 API,不会修改部署实例。
|
测试拦截全部管理 API,不会修改部署实例。
|
||||||
|
|
||||||
|
## 本地文件分享
|
||||||
|
|
||||||
|
- `localShare.test.mjs`:目录导航、路径原样保留、有效期白名单与输入边界。
|
||||||
|
- `localShare.integration.test.mjs`:真实 Vue 状态与服务边界,覆盖目录响应乱序、重复提交、失败重试。
|
||||||
|
- `localShare.browser.mjs`:导出 `runLocalShareChecks(page, dark)`;Vite 运行于
|
||||||
|
`127.0.0.1:5180`。管理 API 全部拦截为独立数据,覆盖目录/搜索/分页、生成失败重试、
|
||||||
|
取件码/链接复制、空目录/加载错误和移动端溢出检查。
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>本地文件分享 · 独立测试</title><div id="app"></div><script type="module">
|
||||||
|
import {createApp,ref} from 'vue';import {createRouter,createMemoryHistory} from 'vue-router';import {createI18n} from 'vue-i18n';import LocalFiles from '/src/views/manage/LocalFilesView.vue';import zh from '/src/i18n/locales/zh-CN.ts';import '/src/assets/style/main.css';
|
||||||
|
const dark=new URLSearchParams(location.search).has('dark');document.documentElement.classList.toggle('dark',dark);
|
||||||
|
const app=createApp(LocalFiles);app.provide('isDarkMode',ref(dark));app.use(createI18n({legacy:false,locale:'zh-CN',messages:{'zh-CN':zh}}));const router=createRouter({history:createMemoryHistory(),routes:[{path:'/',component:{template:'<div/>'}}]});app.use(router);router.isReady().then(()=>app.mount('#app'));
|
||||||
|
</script></html>
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import assert from 'node:assert/strict'
|
||||||
|
|
||||||
|
// Independent API fixture. Never sends requests to a deployed instance.
|
||||||
|
export async function runLocalShareChecks(page, dark = false) {
|
||||||
|
const headers={'access-control-allow-origin':'*','access-control-allow-headers':'*','access-control-allow-methods':'*'}
|
||||||
|
let failShare=true, requests=0, failList=false
|
||||||
|
await page.context().grantPermissions(['clipboard-read','clipboard-write'],{origin:'http://127.0.0.1:5180'})
|
||||||
|
await page.route('**/*',route=>new URL(route.request().url()).hostname==='127.0.0.1'?route.continue():route.abort())
|
||||||
|
const entry=(name,type='file',path=name)=>({name,file:name,path,type,size:type==='dir'?null:1024,ctime:null})
|
||||||
|
await page.route('**/api/v1/config',route=>route.fulfill({headers,json:{code:200,detail:{config:{expireStyle:['day','count','forever'],max_save_seconds:604800}}}}))
|
||||||
|
await page.route('**/admin/**',async route=>{
|
||||||
|
const req=route.request(),url=new URL(req.url())
|
||||||
|
if(req.method()==='OPTIONS') return route.fulfill({status:204,headers})
|
||||||
|
if(url.pathname==='/admin/local/lists'){
|
||||||
|
if(failList){failList=false;return route.fulfill({status:500,headers,json:{detail:'目录暂时不可用'}})}
|
||||||
|
const path=url.searchParams.get('path'),size=Number(url.searchParams.get('size')||20),keyword=url.searchParams.get('keyword')||''
|
||||||
|
let items=path==='文档'?[entry(' final 报告.txt ','file','文档/ final 报告.txt ')]:path==='空目录'?[]:[entry('文档','dir'),entry('空目录','dir'),...Array.from({length:23},(_,n)=>entry(`file-${String(n).padStart(2,'0')}.txt`))]
|
||||||
|
items=items.filter(x=>x.name.includes(keyword));const total=items.length,p=Math.min(Number(url.searchParams.get('page')||1),Math.max(1,Math.ceil(total/size)))
|
||||||
|
return route.fulfill({headers,json:{code:200,detail:{path,parent:'',items:items.slice((p-1)*size,p*size),total,page:p,size,truncated:false}}})
|
||||||
|
}
|
||||||
|
if(url.pathname==='/admin/local/share'){
|
||||||
|
requests++; assert.deepEqual(req.postDataJSON(),{filename:'文档/ final 报告.txt ',expire_style:'count',expire_value:2})
|
||||||
|
await new Promise(r=>setTimeout(r,180))
|
||||||
|
if(failShare){failShare=false;return route.fulfill({status:500,headers,json:{detail:'文件暂时不可读'}})}
|
||||||
|
return route.fulfill({headers,json:{code:200,detail:{id:18,code:'ABCD2345',name:' final 报告.txt ',path:'文档/ final 报告.txt '}}})
|
||||||
|
}
|
||||||
|
throw new Error('Unexpected API '+url.pathname)
|
||||||
|
})
|
||||||
|
await page.goto('http://127.0.0.1:5180/theme-assets/tests/local-files.html'+(dark?'?dark':''))
|
||||||
|
await page.getByRole('button',{name:'打开 文档',exact:true}).waitFor()
|
||||||
|
await page.getByRole('button',{name:'下一页',exact:true}).click()
|
||||||
|
await page.getByText('file-22.txt',{exact:true}).waitFor()
|
||||||
|
await page.getByRole('searchbox',{name:'在当前目录搜索'}).fill('文档')
|
||||||
|
await page.getByRole('button',{name:'搜索',exact:true}).click()
|
||||||
|
await page.getByRole('button',{name:'打开 文档',exact:true}).click()
|
||||||
|
await page.getByRole('button',{name:/分享.*final 报告/}).click()
|
||||||
|
const dialog=page.getByRole('dialog')
|
||||||
|
await dialog.getByRole('combobox').selectOption('count')
|
||||||
|
await dialog.locator('input[type=number]').fill('2')
|
||||||
|
await dialog.getByRole('button',{name:'生成取件码',exact:true}).click()
|
||||||
|
await dialog.getByRole('alert').waitFor()
|
||||||
|
assert.ok((await dialog.getByRole('alert').textContent()).includes('文件暂时不可读'))
|
||||||
|
await dialog.getByRole('button',{name:'生成取件码',exact:true}).click()
|
||||||
|
await dialog.getByRole('textbox',{name:'取件码',exact:true}).waitFor()
|
||||||
|
assert.equal(await dialog.getByRole('textbox',{name:'取件码',exact:true}).inputValue(),'ABCD2345')
|
||||||
|
await dialog.getByRole('button',{name:'复制取件码',exact:true}).click()
|
||||||
|
assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),'ABCD2345')
|
||||||
|
await dialog.getByRole('button',{name:'复制链接',exact:true}).click()
|
||||||
|
assert.equal(await page.evaluate(()=>navigator.clipboard.readText()),'http://127.0.0.1:5180/#/?code=ABCD2345')
|
||||||
|
assert.equal(requests,2)
|
||||||
|
await dialog.getByRole('button',{name:'完成',exact:true}).click()
|
||||||
|
await page.getByRole('button',{name:'返回上一级',exact:true}).click()
|
||||||
|
await page.getByRole('button',{name:'打开 空目录',exact:true}).click()
|
||||||
|
await page.getByText('当前目录还没有文件',{exact:true}).waitFor()
|
||||||
|
failList=true
|
||||||
|
await page.getByRole('button',{name:'刷新目录',exact:true}).click()
|
||||||
|
await page.getByText('目录暂时不可用',{exact:true}).waitFor()
|
||||||
|
await page.getByRole('button',{name:'重试目录',exact:true}).click()
|
||||||
|
await page.getByText('当前目录还没有文件',{exact:true}).waitFor()
|
||||||
|
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth),false)
|
||||||
|
console.log(JSON.stringify({localShare:dark?'dark':'light',directorySearchPagination:true,shareRetryCopy:true,emptyErrorRetry:true,requests}))
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import {test,before,after} from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import {effectScope} 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/useLocalFiles.ts')).useLocalFiles
|
||||||
|
const exports=await server.ssrLoadModule('/src/services/index.ts');service=exports.LocalShareService;config=exports.ConfigService
|
||||||
|
})
|
||||||
|
after(async()=>await server?.close())
|
||||||
|
const listing=path=>({code:200,detail:{path,parent:'',items:[{name:path,type:'file',path,size:1}],page:1,size:20,total:1}})
|
||||||
|
test('slower previous directory response cannot replace current contents',async()=>{
|
||||||
|
const original=service.list,scope=effectScope(),flow=scope.run(create),pending={}
|
||||||
|
service.list=params=>new Promise(resolve=>{pending[params.path]=resolve})
|
||||||
|
try {
|
||||||
|
const old=flow.load('old'),current=flow.load('current')
|
||||||
|
pending.current(listing('current'));await current
|
||||||
|
pending.old(listing('old'));await old
|
||||||
|
assert.equal(flow.path.value,'current');assert.equal(flow.items.value[0].name,'current');assert.equal(flow.loading.value,false)
|
||||||
|
}finally{service.list=original;scope.stop()}
|
||||||
|
})
|
||||||
|
test('share failure keeps dialog retryable and success blocks duplicate generation',async()=>{
|
||||||
|
const originalShare=service.share,originalConfig=config.getUserConfig,scope=effectScope(),flow=scope.run(create)
|
||||||
|
let calls=0,resolveShare
|
||||||
|
config.getUserConfig=async()=>({code:200,detail:{config:{expireStyle:['count'],max_save_seconds:86400}}})
|
||||||
|
service.share=()=>{calls++;return new Promise(resolve=>{resolveShare=resolve})}
|
||||||
|
try {
|
||||||
|
await flow.loadConfig();flow.openShare({name:'a.txt',path:'docs/a.txt',type:'file',size:1})
|
||||||
|
flow.expireValue.value='2';const sending=flow.share();await flow.share();flow.closeShare()
|
||||||
|
assert.equal(calls,1);assert.equal(flow.selected.value.path,'docs/a.txt')
|
||||||
|
resolveShare({code:500,detail:null});await sending
|
||||||
|
assert.ok(flow.shareError.value);assert.equal(flow.sharing.value,false)
|
||||||
|
const retry=flow.share();resolveShare({code:200,detail:{code:'ABCD2345',id:1,name:'a.txt',path:'docs/a.txt'}});await retry
|
||||||
|
await flow.share();assert.equal(calls,2);assert.equal(flow.result.value.code,'ABCD2345')
|
||||||
|
flow.closeShare();assert.equal(flow.selected.value,null)
|
||||||
|
}finally{service.share=originalShare;config.getUserConfig=originalConfig;scope.stop()}
|
||||||
|
})
|
||||||
|
test('failed directory load clears old files and retry restores results',async()=>{
|
||||||
|
const original=service.list,scope=effectScope(),flow=scope.run(create)
|
||||||
|
try{
|
||||||
|
service.list=async()=>listing('old');await flow.load('old')
|
||||||
|
service.list=async()=>{throw new Error('unreadable')};await flow.load('new')
|
||||||
|
assert.deepEqual(flow.items.value,[]);assert.equal(flow.total.value,0);assert.equal(flow.error.value,'unreadable')
|
||||||
|
service.list=async()=>listing('new');await flow.load()
|
||||||
|
assert.equal(flow.error.value,'');assert.equal(flow.items.value[0].path,'new')
|
||||||
|
}finally{service.list=original;scope.stop()}
|
||||||
|
})
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { test } from 'node:test'
|
||||||
|
import assert from 'node:assert/strict'
|
||||||
|
import { localBreadcrumbs, buildLocalShareRequest, expirationChoices } from '../src/utils/local-share.ts'
|
||||||
|
|
||||||
|
test('breadcrumbs preserve literal paths including spaces and unicode', () => {
|
||||||
|
assert.deepEqual(localBreadcrumbs('报告/ final '), [{name:'本地文件',path:''},{name:'报告',path:'报告'},{name:' final ',path:'报告/ final '}])
|
||||||
|
assert.deepEqual(localBreadcrumbs(''), [{name:'本地文件',path:''}])
|
||||||
|
})
|
||||||
|
test('sharing preserves the selected filename and rejects invalid expiration values', () => {
|
||||||
|
assert.deepEqual(buildLocalShareRequest('报告/ final.txt ', 'count', '2',['day','count']), {filename:'报告/ final.txt ',expire_style:'count',expire_value:2})
|
||||||
|
assert.equal(buildLocalShareRequest('a','forever','',['forever']).expire_value,1)
|
||||||
|
for (const value of ['', '0', '-1', '1.5', 'abc', '1000001']) assert.throws(()=>buildLocalShareRequest('a','day',value,['day']))
|
||||||
|
assert.throws(()=>buildLocalShareRequest('a','forever','1',['day']))
|
||||||
|
assert.throws(()=>buildLocalShareRequest('','day','1',['day']))
|
||||||
|
})
|
||||||
|
test('expiration choices only expose server-enabled recognized policies', () => {
|
||||||
|
assert.deepEqual(expirationChoices(['day','count','bad','day']).map(x=>x.value),['day','count'])
|
||||||
|
assert.deepEqual(expirationChoices([]),[])
|
||||||
|
})
|
||||||
Reference in new issue
Block a user