Files
FileHost/app/composables/useMediaUpload.ts
T
Yeomai 89ea2fb25d
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
feat: 新增视频床与文件床,视频支持 HLS 转码
文件床
- 新增 files/ 存储前缀与 media_type 索引列,图片、视频、文件三类资源独立
- 新增文件上传、列表、删除、批量删除接口,禁止 html/htm/svg
- 支持公开直链与 Token 访问两种模式,后台可切换,直链强制附件下载

视频床
- 新增 videos/ 存储前缀与视频上传接口,单文件上限 500MB
- 接入 ffmpeg 转码队列,并发数与单任务核心数可配,默认串行
- 五档转码质量:直接封装 / 速度 / 平衡 / 质量 / 压缩(压缩档可调码率比例)
- 码率控制避免转码后体积反超源文件,音频跟随源音轨不放大不压缩
- 转码进度实时上报,成功后删除源文件,失败时保留源文件与可用链接
- 上传时自动抽帧生成封面,视频与封面各有独立链接
- 删除视频时中断转码并清理切片、封面与源文件

媒体库
- 图库、视频库、文件库三套独立统计,含趋势、占用与来源分布
- 统一筛选、多选、批量删除、批量标签、网格/列表切换,显示方式按类型分别记忆
- 视频详情对齐图片详情,视频库支持在线播放(hls.js,兼容回退原文件)

修复
- 清理无主的切片、封面与开发期遗留的 ffmpeg 进程
- 源文件按设计删除后,索引不再被启动孤儿清理误删
- 视频统计口径与列表一致,转码中的视频不计入统计
- 转码失败时回收已写入的部分切片,避免残留
- 设置页停用检查更新(与上游版本号已不对应)

其他
- Docker 镜像安装 ffmpeg
- git remote 指向内网仓库
2026-10-17 03:14:57 +08:00

287 lines
8.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import type { UploadProgressItem } from '~/types/image'
import type { FileItem, FileListResponse, FileUploadResponse } from '~/types/file'
import type { CopyFormat, UploadMediaKind } from './useUploadPreferences'
import { isUnauthorizedError } from './useAuth'
const MAX_FILES = 10
function buildCopyText(item: FileItem, format: CopyFormat): string {
switch (format) {
case 'url':
return item.url
case 'html':
return `<a href="${item.url}">${item.originalName}</a>`
case 'bbcode':
return `[url=${item.url}]${item.originalName}[/url]`
default:
return `[${item.originalName}](${item.url})`
}
}
async function copyToClipboard(text: string): Promise<boolean> {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
return true
}
} catch {
// 内网 http:// 等非安全上下文继续走回退方案
}
try {
const textarea = document.createElement('textarea')
textarea.value = text
textarea.style.position = 'fixed'
textarea.style.left = '-9999px'
document.body.appendChild(textarea)
textarea.select()
const ok = document.execCommand('copy')
document.body.removeChild(textarea)
return ok
} catch {
return false
}
}
/** 视频床 / 文件床的上传:走文件床接口,偏好按类型独立 */
export function useMediaUpload(kind: UploadMediaKind) {
const toast = useToast()
const { t } = useI18n()
const {
autoCopyMarkdown,
copyFormat,
transcodeToHls,
loadPreferences
} = useUploadPreferences(kind)
const uploading = ref(false)
const progressItems = ref<UploadProgressItem[]>([])
const lastResult = ref<FileUploadResponse | null>(null)
/** 本次会话内上传的条目,页面刷新后清空 */
const sessionItems = ref<FileItem[]>([])
const accessMode = ref<'public' | 'token'>('public')
const apiToken = ref('')
const endpoint = kind === 'video' ? '/api/videos/upload' : '/api/files/upload'
loadPreferences()
async function loadApiToken() {
try {
const data = await $fetch<{ apiUploadToken: string }>('/api/user/api-token', {
credentials: 'include'
})
apiToken.value = data.apiUploadToken ?? ''
} catch {
apiToken.value = ''
}
}
/** Token 模式下复制出的链接需要带上令牌 */
function linkUrl(item: FileItem): string {
// 转码完成后优先给出 m3u8 播放地址
const base = item.hlsUrl ?? item.url
if (accessMode.value !== 'token' || !apiToken.value) return base
const separator = base.includes('?') ? '&' : '?'
return `${base}${separator}token=${encodeURIComponent(apiToken.value)}`
}
/** 封面缩略图地址(同样按访问模式拼接) */
function thumbLink(item: FileItem): string {
const base = item.thumbUrl
if (!base) return ''
if (accessMode.value !== 'token' || !apiToken.value) return base
const separator = base.includes('?') ? '&' : '?'
return `${base}${separator}token=${encodeURIComponent(apiToken.value)}`
}
let statusTimer: ReturnType<typeof setInterval> | null = null
function stopStatusPolling() {
if (statusTimer) {
clearInterval(statusTimer)
statusTimer = null
}
}
function hasPendingTranscode(): boolean {
return sessionItems.value.some(
item => item.transcodeStatus === 'pending' || item.transcodeStatus === 'running'
)
}
/** 转码是异步的,轮询列表把状态与 m3u8 地址同步回来 */
async function refreshTranscodeStatus() {
if (!hasPendingTranscode()) {
stopStatusPolling()
return
}
try {
const [active, finished] = await Promise.all([
$fetch<FileListResponse>('/api/files', {
credentials: 'include',
query: { kind: 'video', limit: 100, processing: '1' }
}),
$fetch<FileListResponse>('/api/files', {
credentials: 'include',
query: { kind: 'video', limit: 100 }
})
])
const latest = new Map(
[...active.items, ...finished.items].map(item => [item.key, item])
)
sessionItems.value = sessionItems.value.map(item => latest.get(item.key) ?? item)
} catch {
// 轮询失败保持现状,下个周期重试
}
if (!hasPendingTranscode()) stopStatusPolling()
}
function startStatusPolling() {
if (kind !== 'video' || statusTimer) return
statusTimer = setInterval(() => {
void refreshTranscodeStatus()
}, 1000)
}
onUnmounted(stopStatusPolling)
/** 刷新或换页后仍要显示还在排队/转码中的视频 */
async function loadActiveTranscodes() {
if (kind !== 'video') return
try {
const response = await $fetch<FileListResponse>('/api/files', {
credentials: 'include',
query: { kind: 'video', limit: 100, processing: '1' }
})
if (!response.items.length) return
const known = new Set(sessionItems.value.map(item => item.key))
const missing = response.items.filter(item => !known.has(item.key))
const latest = new Map(response.items.map(item => [item.key, item]))
sessionItems.value = [
...missing,
...sessionItems.value.map(item => latest.get(item.key) ?? item)
]
startStatusPolling()
} catch {
// 拉取失败时保持现状
}
}
async function uploadFiles(files: File[]) {
if (!files.length || uploading.value) return
if (files.length > MAX_FILES) {
toast.add({ title: t('files.maxFiles', { n: MAX_FILES }), color: 'warning' })
return
}
uploading.value = true
progressItems.value = files.map(file => ({
name: file.name,
status: 'pending',
progress: 0
}))
try {
const formData = new FormData()
for (const file of files) {
formData.append('files', file, file.name)
}
if (kind === 'video' && transcodeToHls.value) {
formData.append('transcode', '1')
}
progressItems.value = progressItems.value.map(item => ({
...item,
status: 'uploading',
progress: 50
}))
const response = await $fetch<FileUploadResponse>(endpoint, {
method: 'POST',
body: formData
})
lastResult.value = response
accessMode.value = response.accessMode
if (response.accessMode === 'token' && !apiToken.value) {
await loadApiToken()
}
progressItems.value = files.map((file) => {
const failed = response.errors.find(error => error.name === file.name)
return {
name: file.name,
status: failed ? 'error' : 'success',
progress: 100,
error: failed?.error.message
}
})
if (response.items.length) {
const wantsTranscode = kind === 'video' && transcodeToHls.value
const uploaded = wantsTranscode
? response.items.map(item => ({ ...item, transcodeStatus: 'pending' as const }))
: response.items
sessionItems.value = [...uploaded, ...sessionItems.value]
if (wantsTranscode) startStatusPolling()
toast.add({
title: t('files.uploadSuccess', { n: response.items.length }),
color: 'success'
})
const first = response.items[0]
if (autoCopyMarkdown.value && first) {
const text = buildCopyText(first, copyFormat.value)
if (text && await copyToClipboard(text)) {
toast.add({ title: t('copy.copied'), color: 'success' })
}
}
}
for (const failure of response.errors.slice(0, 3)) {
toast.add({
title: `${failure.name}:${failure.error.message}`,
color: 'error'
})
}
return response
} catch (error: unknown) {
if (!isUnauthorizedError(error)) {
progressItems.value = progressItems.value.map(item => ({
...item,
status: 'error',
progress: 100,
error: t('files.uploadFailed')
}))
toast.add({ title: t('files.uploadFailed'), color: 'error' })
}
throw error
} finally {
uploading.value = false
}
}
return {
uploading,
progressItems,
lastResult,
sessionItems,
accessMode,
linkUrl,
thumbLink,
loadActiveTranscodes,
uploadFiles
}
}