Compare commits
51
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
51d3acfbb5 | ||
|
|
ed0f20b754 | ||
|
|
ccfdac2e1b | ||
|
|
dd0005b7ba | ||
|
|
366b8a4272 | ||
|
|
58424fe55d | ||
|
|
3759422222 | ||
|
|
885534378b | ||
|
|
8d3616391a | ||
|
|
b4535d6aea | ||
|
|
5d5fecde1b | ||
|
|
88e5707ab6 | ||
|
|
5e024f77a2 | ||
|
|
202a81d0a9 | ||
|
|
a4944a98da | ||
|
|
1d2d16e710 | ||
|
|
21f0dc2830 | ||
|
|
ee8772c1b7 | ||
|
|
a6e45e0cb1 | ||
|
|
813407de30 | ||
|
|
5c1f640a2b | ||
|
|
92aaf6fbb8 | ||
|
|
832261739f | ||
|
|
6494ad2918 | ||
|
|
9939943e31 | ||
|
|
d647453085 | ||
|
|
818c980dec | ||
|
|
a2289a564f | ||
|
|
76328fa058 | ||
|
|
7b2fae6335 | ||
|
|
fa7c8244b0 | ||
|
|
a1b4a63552 | ||
|
|
9cb8552a99 | ||
|
|
a64be50b73 | ||
|
|
9ebab8270c | ||
|
|
75a1ea5fbc | ||
|
|
ede8cb7031 | ||
|
|
89ea2fb25d | ||
|
|
05cc3895f1 | ||
|
|
424bfd9090 | ||
|
|
10baf9d489 | ||
|
|
cc19dc6435 | ||
|
|
4ed4692f5e | ||
|
|
6cc4f27f7d | ||
|
|
d0eb364645 | ||
|
|
91d71a1b40 | ||
|
|
737235acff | ||
|
|
f17d79b236 | ||
|
|
b05d572221 | ||
|
|
4789d19d06 | ||
|
|
430c4de0f4 |
No files matched your search
@@ -5,5 +5,12 @@ node_modules
|
||||
.github
|
||||
data
|
||||
dist
|
||||
dist-fpk
|
||||
dist-windows
|
||||
dist-docker
|
||||
packaging
|
||||
scripts
|
||||
.env
|
||||
*.md
|
||||
._*
|
||||
.DS_Store
|
||||
@@ -30,8 +30,23 @@
|
||||
# 服务端 WebP 压缩质量 1-100(默认 80;也可在设置页配置)
|
||||
# WEBP_QUALITY=80
|
||||
|
||||
# 上传限制(也可在设置 → 访问控制配置;环境变量优先级更高)
|
||||
# UPLOAD_IMAGE_MAX_FILE_SIZE_MB=10
|
||||
# UPLOAD_VIDEO_MAX_FILE_SIZE_MB=500
|
||||
# UPLOAD_FILE_MAX_FILE_SIZE_MB=100
|
||||
# ALLOWED_MIME_TYPES=image/jpeg,image/png,image/webp,image/gif,image/svg+xml,image/x-icon
|
||||
# UPLOAD_RATE_IP_MAX=60
|
||||
# UPLOAD_RATE_TOKEN_MAX=120
|
||||
# UPLOAD_RATE_WINDOW_MINUTES=15
|
||||
# LOGIN_RATE_MAX=10
|
||||
# LOGIN_RATE_WINDOW_MINUTES=15
|
||||
# PRESERVE_ORIGINAL_UPLOAD=false
|
||||
|
||||
# 自动删除超过 N 天的图片(0 表示关闭;也可在设置页配置)
|
||||
# AUTO_DELETE_DAYS=0
|
||||
|
||||
# 仅本地开发:设为 true 可绕过登录验证(跳过 /setup,一般无需开启)
|
||||
# DEV_BYPASS_ACCESS=false
|
||||
|
||||
# 登录人机验证(滑块 / Turnstile / Cap)在后台「设置 → 访问控制」配置,无环境变量。
|
||||
# 配置错误无法登录时:docker exec pichost slider(或 npm run slider)恢复为本地滑块。
|
||||
@@ -1,42 +0,0 @@
|
||||
name: ci
|
||||
|
||||
on: push
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
runs-on: ${{ matrix.os }}
|
||||
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest]
|
||||
node: [22]
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Install node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: ${{ matrix.node }}
|
||||
cache: npm
|
||||
|
||||
- name: Install npm 11 (lockfile generated with npm 11)
|
||||
run: |
|
||||
npm install -g npm@11.12.1
|
||||
npm --version
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Typecheck
|
||||
run: npm run typecheck
|
||||
|
||||
- name: Test
|
||||
run: npm run test
|
||||
|
||||
- name: Build docs
|
||||
run: npm run docs:build
|
||||
@@ -1,71 +0,0 @@
|
||||
name: GitHub Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: '要发布 Release 的标签(如 v1.0.1)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref }}
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
|
||||
- name: Install npm 11
|
||||
run: npm install -g npm@11.12.1
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Extract release notes from CHANGELOG
|
||||
id: notes
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
|
||||
TAG="${{ inputs.tag }}"
|
||||
else
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
fi
|
||||
VERSION="${TAG#v}"
|
||||
BODY_FILE="${RUNNER_TEMP}/release-notes.md"
|
||||
awk -v ver="$VERSION" '
|
||||
/^## \[/ {
|
||||
if (found) exit
|
||||
if ($0 ~ "\\[" ver "\\]") found = 1
|
||||
next
|
||||
}
|
||||
found { print }
|
||||
' CHANGELOG.md > "$BODY_FILE"
|
||||
if [ ! -s "$BODY_FILE" ]; then
|
||||
echo "未在 CHANGELOG.md 找到版本 ${VERSION},使用自动生成说明。" >&2
|
||||
echo "## PicHost ${TAG}" > "$BODY_FILE"
|
||||
fi
|
||||
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
|
||||
echo "body_path=${BODY_FILE}" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ steps.notes.outputs.tag }}
|
||||
name: PicHost ${{ steps.notes.outputs.tag }}
|
||||
body_path: ${{ steps.notes.outputs.body_path }}
|
||||
draft: false
|
||||
prerelease: false
|
||||
make_latest: true
|
||||
+3
-2
@@ -5,6 +5,7 @@
|
||||
.nitro
|
||||
.cache
|
||||
dist
|
||||
dist-windows
|
||||
|
||||
# Node dependencies
|
||||
node_modules
|
||||
@@ -37,9 +38,9 @@ data
|
||||
# 本地 Git hooks 模板(仅安装在 .git/hooks/,不进仓库)
|
||||
git-hooks/
|
||||
|
||||
# 本地维护脚本(assign-image-owner、fpk 打包等,不进仓库)
|
||||
scripts/
|
||||
# 打包输出目录
|
||||
dist-fpk/
|
||||
dist-docker/
|
||||
|
||||
# VitePress docs site
|
||||
docs-site/.vitepress/cache
|
||||
|
||||
+133
-1
@@ -4,6 +4,139 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.5.0] - 2026-10-17
|
||||
|
||||
### 新增
|
||||
|
||||
- 图库、视频库和文件库支持搜索与批量删除,列表管理体验进一步完善
|
||||
- 视频与文件 API 文档按新增上传、查询、批量删除和转码能力同步更新
|
||||
- 所有媒体上传统一使用可配置策略,包括文件大小、格式限制和上传限流
|
||||
- 新上传的图片、视频和文件默认保存到「本地磁盘」,支持切换默认存储后端
|
||||
- 存储页新增高危操作二次确认,可清空当前用户的媒体、任务和缓存且不影响其他用户
|
||||
- 低内存服务器在开启 HLS 转码时显示风险提示
|
||||
|
||||
### 改进
|
||||
|
||||
- 备份与恢复统一统计「媒体记录」和「存储对象」,提升迁移前后数据一致性
|
||||
- 视频上传入口仅允许 MP4、MOV、MKV、WebM 等完整容器格式,服务端增加扩展名与内容类型校验
|
||||
- 缩略图 FFmpeg 限制为单线程并增加 10 秒超时,降低低内存服务器卡死风险
|
||||
- m3u8 临时合并文件支持下载后清理、到期清理及启动兜底清理
|
||||
|
||||
### 修复
|
||||
|
||||
- 修复清空存储后最近任务残留并可继续下载的问题
|
||||
- 修复部分媒体相关文案和逻辑仍仅针对图片、遗漏视频与文件的问题
|
||||
- 修复关闭独立媒体域名时网站域名被误清空、生效地址回落到请求地址的问题
|
||||
- 修复站点同步异常后的兜底恢复流程
|
||||
|
||||
## [1.4.4] - 2026-10-10
|
||||
|
||||
### 修复
|
||||
|
||||
- Cap 登录验证支持新的 hashwx 挑战,旧的 SHA-256 site key 仍可使用
|
||||
- 求解用的 wasm 改由本站提供,不再依赖 jsDelivr
|
||||
|
||||
## [1.4.3] - 2026-10-09
|
||||
|
||||
### 新增
|
||||
|
||||
- **Telegram 存储后端**:用 Bot 把图片存入频道或群组(含私有);直链仍由 PicHost 代理,不暴露 Bot Token
|
||||
- 可选 HTTP/HTTPS API 代理,供服务器访问 Telegram
|
||||
- 群组升级为超级群组时自动改用新的 Chat ID
|
||||
|
||||
### 说明
|
||||
|
||||
- 单文件约 20MB,同一聊天约 20 条/分钟
|
||||
- 图库删除会尝试删除对应 Telegram 消息;备份包不含 Bot Token
|
||||
|
||||
## [1.4.2] - 2026-09-23
|
||||
|
||||
### 修复
|
||||
|
||||
- 图库批量打标:管理员/跨归属场景下标签解析与失败提示
|
||||
- 上传鉴权:`Auth-Token` 与表单 `token` 优先于会话;兼容全局 `API_UPLOAD_TOKEN`(上传归属首位管理员)
|
||||
|
||||
### 改进
|
||||
|
||||
- **API 页**:每账号单一 API Token,界面与文档统一
|
||||
- **上传 API**:仅支持 `tagNames`(按名创建或复用标签);Twikoo 兼容路由同步
|
||||
- **标签管理**:按图片数/最近使用排序;桌面列布局;窄屏卡片列表
|
||||
- **API 文档**:参数表列宽,避免 form-data 列异常换行
|
||||
|
||||
## [1.4.1] - 2026-09-16
|
||||
|
||||
### 新增
|
||||
|
||||
- **上传策略(设置 → 基础)**:单文件大小、允许格式、上传/登录限流、保留原图(关闭服务端 WebP 转换);支持 `.env` 覆盖
|
||||
- **上传 API**:可选 `tagNames`(名称不存在则创建,存在则复用);与 `tagIds` 可并用
|
||||
|
||||
### 改进
|
||||
|
||||
- 登录接口接入可配置的登录限流
|
||||
- 设置页将全站上传策略并入「上传偏好 / 图片处理」;访问控制保留登录限流
|
||||
- API 文档补充 `tagIds` / `tagNames` 参数说明
|
||||
|
||||
## [1.4.0] - 2026-09-09
|
||||
|
||||
### 新增
|
||||
|
||||
- **标签系统**:每用户独立标签与彩色标记;设置页管理(新建、改色、合并、删除)
|
||||
- **图片打标**:上传后单张/批量打标;图库按标签筛选(OR / AND)、批量打标与解标
|
||||
- **操作日志扩展**:记录登录、删除、设置变更、标签操作等;支持日期、用户、操作类型、来源与 IP 筛选
|
||||
- **API**:标签 CRUD、图片打标、`batch-tags`;上传支持 `tagIds`;列表/搜索/统计支持标签筛选
|
||||
|
||||
### 改进
|
||||
|
||||
- 操作日志页 UI 改版(操作/来源徽章、移除备注列)
|
||||
- 设置侧栏增加「标签管理」
|
||||
|
||||
### 文档
|
||||
|
||||
- README 与文档站截图更新(上传、图库、标签、操作日志等)
|
||||
|
||||
## [1.3.0] - 2026-09-07
|
||||
|
||||
### 新增
|
||||
|
||||
- **站点备份**:存储页导出 `.phost.tar.gz`(含 `pichost.db` 与全部图片),支持下载与任务进度
|
||||
- **站点恢复**:存储页或 setup 未初始化时从备份包恢复,支持预检与跳过/覆盖冲突
|
||||
- **跨后端同步**:在已配置存储后端之间拷贝图片并更新索引;后端卡片快捷「迁入 / 迁出」
|
||||
- **任务中心**:`backup_jobs` 记录最近导出/恢复/同步任务,失败可重试;列表分页
|
||||
- 运维 CLI:`backup-export`、`backup-restore`、`storage-sync`(`docker exec pichost …`)
|
||||
|
||||
### 移除
|
||||
|
||||
- 遗留目录迁移 CLI `migrate` / `migrate-to-single-images.mjs`(由启动索引同步与整站备份恢复替代)
|
||||
|
||||
### 文档
|
||||
|
||||
- [存储](./docs-site/guide/storage.md) 补充备份与迁移说明;更新截图;移除 v1.2 迁移专页
|
||||
|
||||
## [1.2.8] - 2026-09-04
|
||||
|
||||
### 改进
|
||||
|
||||
- 双域名:保存或初始化时弹出风险确认(说明可能锁死及 `clear-domains` 恢复方式),不再强制校验当前 Host
|
||||
|
||||
### 新增
|
||||
|
||||
- 运维 CLI `clear-domains`:清除数据库中的网站域 / 图片域配置(`docker exec pichost clear-domains`)
|
||||
|
||||
### 文档
|
||||
|
||||
- FAQ、双域名、反向代理文档补充锁死原因与恢复步骤
|
||||
|
||||
## [1.2.7] - 2026-09-03
|
||||
|
||||
### 新增
|
||||
|
||||
- 登录/注册人机验证:本地滑块、Cloudflare Turnstile、Cap;管理员在「设置 → 访问控制」中切换
|
||||
- 运维 CLI `slider`:将登录验证重置为本地滑块(`docker exec pichost slider`)
|
||||
|
||||
### 改进
|
||||
|
||||
- 登出后登录页验证码可正常重新加载
|
||||
|
||||
## [1.2.6] - 2026-09-01
|
||||
|
||||
### 新增
|
||||
@@ -94,7 +227,6 @@
|
||||
- CLI 迁移工具:`docker exec pichost migrate` / `migrate --apply`(`server/cli/migrate-to-single-images.mjs`)
|
||||
- 扫描 `data/` 下除 `images` 外所有顶层目录中的图片,输出 `data/mapping.json`
|
||||
- 启动时自动同步图片索引(扫描磁盘、归一化遗留 key、清理孤儿记录),并打印同步日志
|
||||
- 迁移文档:[文档站 · v1.2 迁移](https://o96u.github.io/PicHost/guide/migration)
|
||||
|
||||
### 改进
|
||||
|
||||
|
||||
+12
-1
@@ -18,13 +18,24 @@ FROM node:22-alpine
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# 视频床转码依赖 ffmpeg(单码率 HLS 切片)
|
||||
RUN apk add --no-cache ffmpeg
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
NITRO_PORT=6892 \
|
||||
DATA_DIR=/data
|
||||
|
||||
COPY --from=build /app/.output ./.output
|
||||
COPY --from=build /app/server/utils ./server/utils
|
||||
COPY --from=build /app/node_modules ./node_modules
|
||||
COPY --from=build /app/package.json ./package.json
|
||||
COPY server/cli/reset-password.mjs ./server/cli/reset-password.mjs
|
||||
COPY server/cli/migrate-to-single-images.mjs ./server/cli/migrate-to-single-images.mjs
|
||||
COPY server/cli/slider.mjs ./server/cli/slider.mjs
|
||||
COPY server/cli/clear-domains.mjs ./server/cli/clear-domains.mjs
|
||||
COPY server/cli/backup-cli-loader.mjs ./server/cli/backup-cli-loader.mjs
|
||||
COPY server/cli/backup-export.mjs ./server/cli/backup-export.mjs
|
||||
COPY server/cli/backup-restore.mjs ./server/cli/backup-restore.mjs
|
||||
COPY server/cli/storage-sync.mjs ./server/cli/storage-sync.mjs
|
||||
COPY docker-entrypoint.sh /docker-entrypoint.sh
|
||||
RUN chmod +x /docker-entrypoint.sh
|
||||
|
||||
|
||||
+166
-41
@@ -4,64 +4,114 @@
|
||||
|
||||
<h1 align="center">PicHost</h1>
|
||||
|
||||
<p align="center"><strong>Lightweight personal image hosting</strong> · Simple uploads, clean management</p>
|
||||
<p align="center"><strong>Self-hosted image, video, and file management platform</strong></p>
|
||||
|
||||
<p align="center">Self-hosted / Multi-user / Docker / API / Twikoo · Local disk or object storage</p>
|
||||
<p align="center">Multi-user · WebP compression · HLS video · File hosting · Tags · Multi-backend storage · Full backup and migration</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/O96u/PicHost/blob/main/package.json"><img src="https://img.shields.io/github/package-json/v/O96u/PicHost?style=flat-square&color=22c55e" alt="version" /></a>
|
||||
<a href="https://github.com/O96u/PicHost/actions/workflows/ci.yml"><img src="https://github.com/O96u/PicHost/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
|
||||
<a href="https://github.com/yeomaiyelove-cpu/PicHost/blob/main/package.json"><img src="https://img.shields.io/github/package-json/v/yeomaiyelove-cpu/PicHost?style=flat-square&color=22c55e" alt="version" /></a>
|
||||
<img src="https://img.shields.io/badge/Nuxt-4-00DC82?style=flat-square&logo=nuxt.js&logoColor=white" alt="Nuxt 4" />
|
||||
<a href="https://hub.docker.com/r/muxui/pichost"><img src="https://img.shields.io/badge/Docker-muxui%2Fpichost-2496ED?style=flat-square&logo=docker&logoColor=white" alt="Docker" /></a>
|
||||
<a href="https://hub.docker.com/r/yeomaiyelove/pichost"><img src="https://img.shields.io/badge/Docker-yeomaiyelove%2Fpichost-2496ED?style=flat-square&logo=docker&logoColor=white" alt="Docker" /></a>
|
||||
<img src="https://img.shields.io/badge/Windows-x64-0078D4?style=flat-square&logo=windows&logoColor=white" alt="Windows x64" />
|
||||
<img src="https://img.shields.io/badge/FnOS-x86-00A67E?style=flat-square" alt="FnOS x86" />
|
||||
<img src="https://img.shields.io/badge/license-GPL--3.0-blue?style=flat-square" alt="GPL-3.0" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://o96u.github.io/PicHost/en/">Docs</a> ·
|
||||
<a href="#screenshots">Screenshots</a> ·
|
||||
<a href="#features">Features</a> ·
|
||||
<a href="#tech-stack">Tech Stack</a> ·
|
||||
<a href="#quick-start">Quick Start</a> ·
|
||||
<a href="#deployment">Deployment</a> ·
|
||||
<a href="#development-and-packaging">Development</a> ·
|
||||
<a href="docs-site/en/">Documentation source</a> ·
|
||||
<a href="README.md">简体中文</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
PicHost is a media management platform for NAS devices, home servers, and small self-hosted deployments. It manages images, videos, and general-purpose files in one place, with multi-user access, tags, search, multiple storage backends, HLS video processing, full-site backup and restore, backend migration, and site-to-site synchronization.
|
||||
|
||||
The first visit opens a web setup wizard. Administrators can either create an account or restore an existing `.phost.tar.gz` backup.
|
||||
|
||||
## Screenshots
|
||||
|
||||
**main** has no public demo. **cloudflare** branch live demo: [pic.roven.cc](https://pic.roven.cc)
|
||||
| Upload | Gallery |
|
||||
| :----: | :-----: |
|
||||
|  |  |
|
||||
|
||||
| API | Gallery |
|
||||
| :--: | :-----: |
|
||||
|  |  |
|
||||
| API | Tag management |
|
||||
| :-: | :------------: |
|
||||
|  |  |
|
||||
|
||||
| Storage | Settings |
|
||||
| :-----: | :-------: |
|
||||
|  |  |
|
||||
|
||||
| First-time setup | Restore from backup |
|
||||
| :--------------: | :-----------------: |
|
||||
|  |  |
|
||||
|
||||
| Activity log |
|
||||
| :----------: |
|
||||
|  |
|
||||
|
||||
## Features
|
||||
|
||||
- **Drag, click, or Ctrl+V paste** — server-side WebP, Referer hotlink protection
|
||||
- **Multi-user** — login with slider captcha, optional registration; users see only their images
|
||||
- **Multi-backend storage** — local disk + S3-compatible (R2 / COS / OSS / AWS); hybrid `proxy` / `public` URLs
|
||||
- **Gallery** — browse, search, filter by storage/source, grid/list views, batch delete; stats overview and source breakdown
|
||||
- **API & Twikoo** — global / per-user tokens; `POST /api/index.php` compatible
|
||||
- **Zero-config Docker** — first-run web wizard, no secrets upfront
|
||||
### Images
|
||||
|
||||
## Tech Stack
|
||||
- Upload by drag and drop, file picker, or `Ctrl+V` paste, with configurable formats, size limits, batch limits, and rate limits.
|
||||
- Server-side Sharp-based WebP compression, with optional original preservation and optional browser-side WebP compression.
|
||||
- Search, pagination, storage/source/tag filters, grid or list layouts, detail views, multiple link formats, bulk tagging, and bulk deletion.
|
||||
- Media counts and source statistics, Referer hotlink protection, and configurable referrer allowlists.
|
||||
|
||||
| Layer | Technologies |
|
||||
| ----- | ------------ |
|
||||
| Frontend | [Nuxt 4](https://nuxt.com) · [Nuxt UI 4](https://ui.nuxt.com) · [Vue 3](https://vuejs.org) · [Tailwind CSS 4](https://tailwindcss.com) · TypeScript |
|
||||
| Backend | [Nitro](https://nitro.build) (`node-server`) · REST API |
|
||||
| Data | SQLite · local `data/pichost.db` |
|
||||
| Images | [sharp](https://sharp.pixelplumbing.com) (server-side WebP) |
|
||||
| Storage | Local disk · S3-compatible ([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS, etc.) |
|
||||
| i18n | [@nuxtjs/i18n](https://i18n.nuxtjs.org) (zh-CN / English) |
|
||||
| Quality & docs | [Vitest](https://vitest.dev) · [VitePress](https://vitepress.dev) docs site |
|
||||
| Deploy | Docker · Node.js 22 |
|
||||
### Video and HLS
|
||||
|
||||
## Quick Start
|
||||
- Dedicated video upload and library pages for MP4, M4V, WebM, MOV, MKV, AVI, FLV, WMV, MPG, and MPEG.
|
||||
- Automatic thumbnail generation and optional asynchronous HLS transcoding.
|
||||
- `copy`, `veryfast`, `medium`, `slow`, and `compress` presets, with configurable concurrency, CPU thread count, and target bitrate.
|
||||
- Transcode progress and failure reporting, with automatic cleanup of the source, thumbnail, playlist, and HLS segments.
|
||||
- Original, thumbnail, and HLS links, plus MP4 remux download for HLS videos.
|
||||
|
||||
### File Hosting
|
||||
|
||||
- A dedicated file library with uploads, search, pagination, tags, bulk deletion, direct links, and download links.
|
||||
- Configurable file-bed access policy, with separate domains supported for images, videos, and files.
|
||||
|
||||
### Users and Access Control
|
||||
|
||||
- Administrator and standard-user accounts; standard users only see and manage their own media.
|
||||
- Slider, Cloudflare Turnstile, and Cap verification, with optional public registration.
|
||||
- Profile and password management, administrator password reset, and account-system migration.
|
||||
- Per-user tags and automatic deletion policies.
|
||||
- Login and upload rate limits, global and personal API tokens, and activity logs.
|
||||
|
||||
### Storage
|
||||
|
||||
- Local disk, S3-compatible object storage, and Telegram channels or groups.
|
||||
- S3-compatible support includes R2, COS, OSS, AWS S3, and similar services, with `proxy` or `public` access modes.
|
||||
- Multiple backends, configurable default and enabled states, and per-backend capacity quotas.
|
||||
- Migration of images, videos, files, and indexes between configured backends, with an optional target backend switch after migration.
|
||||
|
||||
### Backup and Synchronization
|
||||
|
||||
- Complete `.phost.tar.gz` site backups containing the database, images, videos, files, thumbnails, HLS content, and tags.
|
||||
- Restore previews for file count, media size, new files, conflicts, and skip/overwrite conflict handling.
|
||||
- Streaming uploads for large backups without loading the complete archive into memory.
|
||||
- Restore directly from the first-run setup page; cloud storage secrets are excluded and must be re-entered after restore.
|
||||
- Push or pull synchronization between two PicHost sites, for all media or only images, videos, or files.
|
||||
- Resume support, conflict policies, and job progress; matching usernames must already exist on both sites.
|
||||
|
||||
### API and Compatibility
|
||||
|
||||
- APIs for images, videos, files, tags, search, bulk operations, backups, and system information.
|
||||
- Global and personal tokens, accepted through request headers or upload forms.
|
||||
- Twikoo / EasyImage-compatible uploads through `POST /api/index.php`.
|
||||
- Built-in API documentation and debugger with generated `curl` examples.
|
||||
|
||||
## Deployment
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
@@ -69,22 +119,97 @@ docker run -d \
|
||||
-p 6892:6892 \
|
||||
-v ./data:/data \
|
||||
--restart unless-stopped \
|
||||
muxui/pichost:latest
|
||||
yeomaiyelove/pichost:latest
|
||||
```
|
||||
|
||||
Open `http://<host>:6892` and complete the setup wizard.
|
||||
Open `http://<host>:6892` and complete the setup wizard. Data is stored in the host `./data` directory by default.
|
||||
|
||||
**Full guide** (env vars, upgrades, dual-domain setup, API, Twikoo, reverse proxy, local dev, etc.): **[Documentation](https://o96u.github.io/PicHost/en/)**.
|
||||
Docker Hub:
|
||||
|
||||
| Branch | Notes |
|
||||
| ------ | ----- |
|
||||
| [**main**](https://github.com/O96u/PicHost/tree/main) | Default: multi-backend, dual-domain, unified `images/` storage |
|
||||
| [**cloudflare**](https://github.com/O96u/PicHost/tree/cloudflare) | Cloudflare R2 only; live demo [pic.roven.cc](https://pic.roven.cc) |
|
||||
- `yeomaiyelove/pichost:latest`
|
||||
- `yeomaiyelove/pichost:<version>`
|
||||
|
||||
### Windows
|
||||
|
||||
The Windows x64 installer is self-contained:
|
||||
|
||||
- Node.js and FFmpeg are bundled; no runtime download is required on the target computer.
|
||||
- The first launch opens the web setup wizard.
|
||||
- Data is stored in the `data` directory under the installation directory.
|
||||
- Uninstall asks whether to delete the data directory. If preserved, the database, media, and backups remain on disk.
|
||||
|
||||
### FnOS
|
||||
|
||||
FnOS uses a dedicated x86 FPK package that runs the bundled Docker image:
|
||||
|
||||
1. Import the matching `yeomaiyelove/pichost:<version>` image into FnOS Docker.
|
||||
2. Confirm that the image appears locally.
|
||||
3. Install the FPK and choose account creation or backup restore in the wizard.
|
||||
|
||||
The FPK uses the local image and does not pull PicHost from the internet.
|
||||
|
||||
## Development and Packaging
|
||||
|
||||
### Local Development
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run dev
|
||||
```
|
||||
|
||||
The first visit opens `/setup`. Common verification commands:
|
||||
|
||||
```bash
|
||||
npm test
|
||||
npm run typecheck
|
||||
npm run lint
|
||||
npm run build
|
||||
```
|
||||
|
||||
### Release Artifacts
|
||||
|
||||
```bash
|
||||
npm run pack:docker
|
||||
npm run pack:fpk
|
||||
npm run pack:windows
|
||||
```
|
||||
|
||||
On Windows, all artifacts can be built at once:
|
||||
|
||||
```bash
|
||||
npm run pack:all
|
||||
```
|
||||
|
||||
Output directories:
|
||||
|
||||
- Docker image archive: `dist-docker/`
|
||||
- FnOS package: `dist-fpk/`
|
||||
- Windows installer: `dist-windows/release/`
|
||||
|
||||
See [packaging/README.md](packaging/README.md) for requirements and override options.
|
||||
|
||||
## Data Directory
|
||||
|
||||
- Docker uses `/data` by default and supports the `DATA_DIR` override.
|
||||
- Windows installs use the `data` directory under the installation path.
|
||||
- Local development uses `data` in the project root.
|
||||
|
||||
The database is stored as `pichost.db`. Create regular full-site backups and keep the `.phost.tar.gz` files on separate storage.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
| Layer | Technologies |
|
||||
| ----- | ------------ |
|
||||
| Frontend | Nuxt 4 · Nuxt UI 4 · Vue 3 · Tailwind CSS 4 · TypeScript |
|
||||
| Backend | Nitro `node-server` · REST API · H3 |
|
||||
| Database | SQLite |
|
||||
| Images | Sharp (WebP compression) |
|
||||
| Video | FFmpeg · HLS · hls.js |
|
||||
| Storage | Local disk · S3-compatible object storage · Telegram |
|
||||
| Internationalization | @nuxtjs/i18n (Simplified Chinese / English) |
|
||||
| Quality and documentation | Vitest · ESLint · vue-tsc · VitePress |
|
||||
| Deployment | Docker · Node.js 22 · Electron (Windows) · FnOS FPK |
|
||||
|
||||
## License
|
||||
|
||||
[GPL-3.0](LICENSE)
|
||||
|
||||
## Friend links
|
||||
|
||||
[LINUX DO](https://linux.do/)
|
||||
@@ -4,64 +4,115 @@
|
||||
|
||||
<h1 align="center">PicHost</h1>
|
||||
|
||||
<p align="center"><strong>个人轻量图床</strong> · 图片放好,管理也要顺手</p>
|
||||
<p align="center"><strong>自托管图片、视频与文件管理平台</strong></p>
|
||||
|
||||
<p align="center">自托管图床 / 多用户 / Docker / API / Twikoo · 本地磁盘或对象存储</p>
|
||||
<p align="center">多用户 · WebP 压缩 · HLS 视频 · 文件床 · 标签 · 多存储后端 · 整站备份与迁移</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/O96u/PicHost/blob/main/package.json"><img src="https://img.shields.io/github/package-json/v/O96u/PicHost?style=flat-square&color=22c55e" alt="version" /></a>
|
||||
<a href="https://github.com/O96u/PicHost/actions/workflows/ci.yml"><img src="https://github.com/O96u/PicHost/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
|
||||
<a href="https://github.com/yeomaiyelove-cpu/PicHost/blob/main/package.json"><img src="https://img.shields.io/github/package-json/v/yeomaiyelove-cpu/PicHost?style=flat-square&color=22c55e" alt="version" /></a>
|
||||
<img src="https://img.shields.io/badge/Nuxt-4-00DC82?style=flat-square&logo=nuxt.js&logoColor=white" alt="Nuxt 4" />
|
||||
<a href="https://hub.docker.com/r/muxui/pichost"><img src="https://img.shields.io/badge/Docker-muxui%2Fpichost-2496ED?style=flat-square&logo=docker&logoColor=white" alt="Docker" /></a>
|
||||
<a href="https://hub.docker.com/r/yeomaiyelove/pichost"><img src="https://img.shields.io/badge/Docker-yeomaiyelove%2Fpichost-2496ED?style=flat-square&logo=docker&logoColor=white" alt="Docker" /></a>
|
||||
<img src="https://img.shields.io/badge/Windows-x64-0078D4?style=flat-square&logo=windows&logoColor=white" alt="Windows x64" />
|
||||
<img src="https://img.shields.io/badge/%E9%A3%9E%E7%89%9B-x86-00A67E?style=flat-square" alt="飞牛 x86" />
|
||||
<img src="https://img.shields.io/badge/license-GPL--3.0-blue?style=flat-square" alt="GPL-3.0" />
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://o96u.github.io/PicHost/">文档</a> ·
|
||||
<a href="#界面预览">预览</a> ·
|
||||
<a href="#特性">特性</a> ·
|
||||
<a href="#技术栈">技术栈</a> ·
|
||||
<a href="#快速开始">快速开始</a> ·
|
||||
<a href="#核心功能">功能</a> ·
|
||||
<a href="#部署方式">部署</a> ·
|
||||
<a href="#开发与打包">开发与打包</a> ·
|
||||
<a href="docs-site/">文档源码</a> ·
|
||||
<a href="README.en.md">English</a>
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
## 项目简介
|
||||
|
||||
PicHost 是一个面向 NAS、家庭服务器和小型自托管场景的媒体管理平台,可统一管理图片、视频和普通文件。除上传与直链外,还提供多用户、标签、搜索、多存储后端、HLS 视频处理、整站备份恢复、跨后端迁移以及两站点同步。
|
||||
|
||||
首次启动通过 Web 向导创建管理员,也可以直接从 `.phost.tar.gz` 完整备份恢复。
|
||||
|
||||
## 界面预览
|
||||
|
||||
**main** 分支暂无公网演示;**cloudflare** 分支在线体验:[pic.roven.cc](https://pic.roven.cc)
|
||||
|
||||
| API | 图库 |
|
||||
| 上传 | 图库 |
|
||||
| :--: | :--: |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| API | 标签管理 |
|
||||
| :--: | :------: |
|
||||
|  |  |
|
||||
|
||||
| 存储 | 设置 |
|
||||
| :--: | :--: |
|
||||
|  |  |
|
||||
|
||||
## 特性
|
||||
| 首次设置 | 从备份恢复 |
|
||||
| :--: | :--: |
|
||||
|  |  |
|
||||
|
||||
- **拖拽 / 点击 / Ctrl+V 粘贴**上传;服务端 WebP 压缩、Referer 防盗链
|
||||
- **多用户**:账号密码登录(滑动验证)、可选开放注册;普通用户仅见自己的图片
|
||||
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public`
|
||||
- **图库**:浏览、搜索、按存储/来源筛选、网格/列表切换、批量删除;统计概览与来源分布
|
||||
- **API 与 Twikoo**:全局 / 个人 Token;`POST /api/index.php` 兼容
|
||||
- **Docker 零配置**:首次访问 Web 引导创建管理员
|
||||
| 操作日志 |
|
||||
| :------: |
|
||||
|  |
|
||||
|
||||
## 技术栈
|
||||
## 核心功能
|
||||
|
||||
| 层级 | 技术 |
|
||||
| ---- | ---- |
|
||||
| 前端 | [Nuxt 4](https://nuxt.com) · [Nuxt UI 4](https://ui.nuxt.com) · [Vue 3](https://vuejs.org) · [Tailwind CSS 4](https://tailwindcss.com) · TypeScript |
|
||||
| 后端 | [Nitro](https://nitro.build)(`node-server`)· REST API |
|
||||
| 数据 | SQLite · 本地 `data/pichost.db` |
|
||||
| 图片处理 | [sharp](https://sharp.pixelplumbing.com)(服务端 WebP 压缩) |
|
||||
| 存储 | 本地磁盘 · S3 兼容([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS 等) |
|
||||
| 国际化 | [@nuxtjs/i18n](https://i18n.nuxtjs.org)(简体中文 / English) |
|
||||
| 质量与文档 | [Vitest](https://vitest.dev) · [VitePress](https://vitepress.dev) 文档站 |
|
||||
| 部署 | Docker · Node.js 22 |
|
||||
### 图片管理
|
||||
|
||||
## 快速开始
|
||||
- 支持拖拽、文件选择和 `Ctrl+V` 粘贴上传,可配置格式、大小、批量数量和频率限制。
|
||||
- 服务端使用 Sharp 压缩为 WebP,也可保留原图;支持可选的浏览器端 WebP 压缩。
|
||||
- 图库支持搜索、分页、存储后端/上传来源/标签筛选,以及网格和列表视图。
|
||||
- 支持查看详情、复制多种链接格式、批量打标和批量删除,并提供媒体数量与来源统计。
|
||||
- 支持 Referer 防盗链和来源域名白名单。
|
||||
|
||||
### 视频库与 HLS
|
||||
|
||||
- 独立的视频上传、搜索和管理页面,支持 MP4、M4V、WebM、MOV、MKV、AVI、FLV、WMV、MPG、MPEG 等格式。
|
||||
- 上传后自动生成视频缩略图,并可根据设置异步转码为 HLS。
|
||||
- 支持 `copy`、`veryfast`、`medium`、`slow`、`compress` 等转码档位,可限制并发数、CPU 核心数和目标码率。
|
||||
- 管理转码进度与失败原因,支持删除时同步清理原视频、缩略图、播放列表和 HLS 分片。
|
||||
- 支持复制原视频、缩略图和 HLS 地址,并可将 HLS 视频重新封装下载为 MP4。
|
||||
|
||||
### 文件床
|
||||
|
||||
- 独立管理普通文件,提供上传、搜索、分页、标签、批量删除和直链/下载链接。
|
||||
- 文件床访问策略可在后台配置,文件、图片和视频可分别使用独立域名。
|
||||
|
||||
### 多用户与权限
|
||||
|
||||
- 管理员与普通用户账号体系,普通用户只能查看和管理自己的媒体。
|
||||
- 支持滑块、Cloudflare Turnstile 和 Cap 人机验证,可选择开放注册。
|
||||
- 支持修改资料、修改密码、管理员清空密码和迁移到账号密码登录。
|
||||
- 每个用户拥有独立标签和自动删除策略,可设置媒体保存天数。
|
||||
- 提供登录与上传频率限制、全局/个人 API Token 和操作日志。
|
||||
|
||||
### 存储与迁移
|
||||
|
||||
- 支持本地磁盘、S3 兼容对象存储和 Telegram 频道/群组。
|
||||
- S3 兼容 R2、COS、OSS、AWS S3 等服务,支持 `proxy` 和 `public` 两种访问方式。
|
||||
- 可配置多个存储后端、默认后端、启用状态和容量配额。
|
||||
- 支持在已配置后端之间迁移图片、视频、文件和索引,迁移后可将目标后端设为默认。
|
||||
|
||||
### 备份与站点同步
|
||||
|
||||
- 创建和恢复完整 `.phost.tar.gz` 站点备份,包含数据库、图片、视频、文件、缩略图、HLS 内容和标签。
|
||||
- 备份恢复前可预检文件数量、媒体大小、新增与冲突情况,并选择跳过或覆盖冲突。
|
||||
- 支持大体积备份流式上传,无需将整个压缩包读入内存。
|
||||
- 未初始化时可在首次设置页直接恢复备份;云存储密钥不会写入备份,恢复后需重新填写。
|
||||
- 支持两站点双向同步,可推送或拉取全部媒体,也可只同步图片、视频或文件。
|
||||
- 站点同步支持断点继续、冲突策略和任务进度;目标站点需要预先存在同名用户。
|
||||
|
||||
### API 与兼容性
|
||||
|
||||
- 提供图片、视频、文件、标签、搜索、批量操作、备份和系统接口。
|
||||
- 支持全局 Token 和个人 Token,可通过请求头或表单上传。
|
||||
- 兼容 Twikoo / EasyImage 的 `POST /api/index.php` 上传接口。
|
||||
- 前端内置 API 文档和调试界面,支持直接生成并复制 `curl` 示例。
|
||||
|
||||
## 部署方式
|
||||
|
||||
### Docker
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
@@ -69,22 +120,97 @@ docker run -d \
|
||||
-p 6892:6892 \
|
||||
-v ./data:/data \
|
||||
--restart unless-stopped \
|
||||
muxui/pichost:latest
|
||||
yeomaiyelove/pichost:latest
|
||||
```
|
||||
|
||||
浏览器打开 `http://<主机IP>:6892`,按引导完成设置即可。
|
||||
浏览器打开 `http://<主机IP>:6892`,按向导创建管理员即可。数据默认保存在宿主机的 `./data` 目录。
|
||||
|
||||
**详细说明**(环境变量、升级迁移、双域名、API、Twikoo、反向代理、本地开发等)见 **[用户文档](https://o96u.github.io/PicHost/)**。
|
||||
Docker Hub:
|
||||
|
||||
| 分支 | 说明 |
|
||||
- `yeomaiyelove/pichost:latest`
|
||||
- `yeomaiyelove/pichost:<版本号>`
|
||||
|
||||
### Windows
|
||||
|
||||
项目提供 Windows x64 一体安装包:
|
||||
|
||||
- 内置 Node.js 和 FFmpeg,不依赖目标电脑预装运行环境。
|
||||
- 首次启动后按 Web 向导完成设置。
|
||||
- 数据保存在安装目录下的 `data` 子目录。
|
||||
- 卸载时会询问是否删除数据;选择保留后,数据库、图片、视频和备份不会被删除。
|
||||
|
||||
### 飞牛 NAS
|
||||
|
||||
飞牛使用独立的 x86 FPK 安装包,FPK 以内置 Docker 镜像方式运行:
|
||||
|
||||
1. 在飞牛 Docker 中导入与 FPK 版本对应的镜像包。
|
||||
2. 确认镜像列表中存在 `yeomaiyelove/pichost:<版本号>`。
|
||||
3. 安装 FPK,并按向导选择创建管理员或从备份恢复。
|
||||
|
||||
FPK 使用本地镜像,不会自动联网拉取 PicHost 镜像。
|
||||
|
||||
## 开发与打包
|
||||
|
||||
### 本地开发
|
||||
|
||||
```bash
|
||||
npm ci
|
||||
npm run dev
|
||||
```
|
||||
|
||||
默认开发地址由 Nuxt 输出,首次访问会进入 `/setup`。常用检查命令:
|
||||
|
||||
```bash
|
||||
npm test
|
||||
npm run typecheck
|
||||
npm run lint
|
||||
npm run build
|
||||
```
|
||||
|
||||
### 构建安装产物
|
||||
|
||||
```bash
|
||||
npm run pack:docker
|
||||
npm run pack:fpk
|
||||
npm run pack:windows
|
||||
```
|
||||
|
||||
Windows 环境可以一次构建全部产物:
|
||||
|
||||
```bash
|
||||
npm run pack:all
|
||||
```
|
||||
|
||||
输出位置:
|
||||
|
||||
- Docker 离线镜像:`dist-docker/`
|
||||
- 飞牛安装包:`dist-fpk/`
|
||||
- Windows 安装程序:`dist-windows/release/`
|
||||
|
||||
详细环境要求和可覆盖参数见 [打包说明](packaging/README.md)。
|
||||
|
||||
## 数据目录
|
||||
|
||||
- Docker 默认使用 `/data`,通过 `DATA_DIR` 可覆盖。
|
||||
- Windows 安装版使用安装目录下的 `data`。
|
||||
- 本地开发默认使用项目根目录下的 `data`。
|
||||
|
||||
数据库文件为 `pichost.db`。建议定期在后台创建整站备份,并将 `.phost.tar.gz` 文件保存到其他磁盘。
|
||||
|
||||
## 技术栈
|
||||
|
||||
| 层级 | 技术 |
|
||||
| ---- | ---- |
|
||||
| [**main**](https://github.com/O96u/PicHost/tree/main) | 默认主线:多后端、双域名、统一 `images/` 存储 |
|
||||
| [**cloudflare**](https://github.com/O96u/PicHost/tree/cloudflare) | 仅 Cloudflare R2;在线演示 [pic.roven.cc](https://pic.roven.cc) |
|
||||
| 前端 | Nuxt 4 · Nuxt UI 4 · Vue 3 · Tailwind CSS 4 · TypeScript |
|
||||
| 后端 | Nitro `node-server` · REST API · H3 |
|
||||
| 数据库 | SQLite |
|
||||
| 图片处理 | Sharp(WebP 压缩) |
|
||||
| 视频处理 | FFmpeg · HLS · hls.js |
|
||||
| 存储 | 本地磁盘 · S3 兼容对象存储 · Telegram |
|
||||
| 国际化 | @nuxtjs/i18n(简体中文 / English) |
|
||||
| 测试与文档 | Vitest · ESLint · vue-tsc · VitePress |
|
||||
| 部署 | Docker · Node.js 22 · Electron(Windows)· 飞牛 FPK |
|
||||
|
||||
## License
|
||||
|
||||
[GPL-3.0](LICENSE)
|
||||
|
||||
## 友链
|
||||
|
||||
[LINUX DO](https://linux.do/)
|
||||
+24
-1
@@ -7,22 +7,44 @@
|
||||
|
||||
.upload-card-flip-inner {
|
||||
position: relative;
|
||||
transition: transform 0.55s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition:
|
||||
transform 0.55s cubic-bezier(0.4, 0, 0.2, 1),
|
||||
min-height 0.35s ease;
|
||||
transform-style: preserve-3d;
|
||||
}
|
||||
|
||||
.upload-card-flip.is-flipped .upload-card-flip-inner {
|
||||
min-height: min(40rem, calc(100vh - 11rem));
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
|
||||
.upload-card-flip--file.is-flipped .upload-card-flip-inner {
|
||||
min-height: min(27rem, calc(100vh - 11rem));
|
||||
}
|
||||
|
||||
.upload-card-flip.is-flipped .upload-card-face--front {
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.upload-card-flip.is-flipped .upload-settings-btn {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.upload-card-face {
|
||||
backface-visibility: hidden;
|
||||
-webkit-backface-visibility: hidden;
|
||||
}
|
||||
|
||||
.upload-card-face--front {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.upload-card-face--back {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
z-index: 2;
|
||||
transform: rotateY(180deg);
|
||||
}
|
||||
|
||||
@@ -33,6 +55,7 @@
|
||||
|
||||
.upload-card-flip.is-flipped .upload-card-flip-inner {
|
||||
transform: none;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.upload-card-flip .upload-card-face--back {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import logoLight from '~/assets/image/logo-light.png'
|
||||
import logoDark from '~/assets/image/logo-dark.png'
|
||||
import type { LoginVerificationPayload } from '~/types/auth'
|
||||
|
||||
const router = useRouter()
|
||||
const { login, fetchStatus, authStatus } = useAuth()
|
||||
@@ -11,45 +12,53 @@ const username = ref('')
|
||||
const password = ref('')
|
||||
const secret = ref('')
|
||||
const loading = ref(false)
|
||||
const captchaRef = ref<{ reset: () => Promise<void> } | null>(null)
|
||||
const captchaPayload = ref<{ captchaId: string, captchaPosition: number } | null>(null)
|
||||
const verificationRef = ref<{ reset: () => Promise<void> } | null>(null)
|
||||
const verificationPayload = ref<LoginVerificationPayload | null>(null)
|
||||
const verificationMountKey = ref(0)
|
||||
|
||||
const legacyMode = computed(() => authStatus.value?.legacyMode ?? false)
|
||||
const allowRegistration = computed(() => authStatus.value?.allowRegistration ?? false)
|
||||
const loginVerification = computed(() =>
|
||||
authStatus.value?.loginVerification ?? { method: 'slider' as const }
|
||||
)
|
||||
|
||||
const canSubmit = computed(() =>
|
||||
Boolean(captchaPayload.value)
|
||||
Boolean(verificationPayload.value)
|
||||
&& (legacyMode.value ? Boolean(secret.value) : Boolean(username.value && password.value))
|
||||
)
|
||||
|
||||
function onCaptchaVerified(payload: { id: string, positionPercent: number }) {
|
||||
captchaPayload.value = {
|
||||
captchaId: payload.id,
|
||||
captchaPosition: payload.positionPercent
|
||||
}
|
||||
function onVerificationVerified(payload: LoginVerificationPayload) {
|
||||
verificationPayload.value = payload
|
||||
}
|
||||
|
||||
async function resetCaptcha() {
|
||||
captchaPayload.value = null
|
||||
await captchaRef.value?.reset()
|
||||
function onVerificationCleared() {
|
||||
verificationPayload.value = null
|
||||
}
|
||||
|
||||
async function resetVerification() {
|
||||
verificationPayload.value = null
|
||||
await verificationRef.value?.reset()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
verificationPayload.value = null
|
||||
verificationMountKey.value += 1
|
||||
const status = await fetchStatus()
|
||||
if (!status.initialized && !status.legacyMode) {
|
||||
await router.replace('/setup')
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
if (!canSubmit.value || loading.value || !captchaPayload.value) return
|
||||
if (!canSubmit.value || loading.value || !verificationPayload.value) return
|
||||
loading.value = true
|
||||
|
||||
try {
|
||||
const captcha = captchaPayload.value
|
||||
const verification = verificationPayload.value
|
||||
const result = legacyMode.value
|
||||
? await login({ secret: secret.value }, captcha)
|
||||
: await login({ username: username.value.trim(), password: password.value }, captcha)
|
||||
? await login({ secret: secret.value }, verification)
|
||||
: await login({ username: username.value.trim(), password: password.value }, verification)
|
||||
|
||||
if (result.ok) {
|
||||
if (result.needsMigration) {
|
||||
@@ -59,10 +68,16 @@ async function submit() {
|
||||
username.value = ''
|
||||
password.value = ''
|
||||
secret.value = ''
|
||||
await resetCaptcha()
|
||||
await resetVerification()
|
||||
toast.add({ title: t('auth.loginSuccess'), color: 'success' })
|
||||
} else if (result.needsPasswordReset) {
|
||||
await resetVerification()
|
||||
await router.push({
|
||||
path: '/reset-password',
|
||||
query: { username: result.resetUsername ?? username.value.trim() }
|
||||
})
|
||||
} else {
|
||||
await resetCaptcha()
|
||||
await resetVerification()
|
||||
toast.add({
|
||||
title: result.error ?? (legacyMode.value ? t('auth.loginFailedSecret') : t('auth.loginFailedCredentials')),
|
||||
color: 'error'
|
||||
@@ -170,9 +185,14 @@ async function submit() {
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<SliderCaptcha
|
||||
ref="captchaRef"
|
||||
@verified="onCaptchaVerified"
|
||||
<LoginVerification
|
||||
:key="verificationMountKey"
|
||||
ref="verificationRef"
|
||||
:method="loginVerification.method"
|
||||
:turnstile-site-key="loginVerification.turnstileSiteKey"
|
||||
:cap-api-endpoint="loginVerification.capApiEndpoint"
|
||||
@verified="onVerificationVerified"
|
||||
@cleared="onVerificationCleared"
|
||||
/>
|
||||
|
||||
<UButton
|
||||
|
||||
@@ -13,16 +13,52 @@ const mobileUserOpen = ref(false)
|
||||
const navItems = computed(() => {
|
||||
const items = [
|
||||
{ label: t('nav.api'), to: '/api', icon: 'i-lucide-code-2' },
|
||||
{ label: t('nav.gallery'), to: '/gallery', icon: 'i-lucide-images' }
|
||||
{ label: t('nav.gallery'), to: '/gallery', icon: 'i-lucide-images' },
|
||||
{ label: t('nav.videoLibrary'), to: '/video-library', icon: 'i-lucide-film' },
|
||||
{ label: t('nav.fileLibrary'), to: '/file-library', icon: 'i-lucide-folder-open' }
|
||||
]
|
||||
if (isAdmin.value) {
|
||||
items.push({ label: t('nav.users'), to: '/users', icon: 'i-lucide-users' })
|
||||
items.push({ label: t('nav.storage'), to: '/storage', icon: 'i-lucide-hard-drive' })
|
||||
}
|
||||
items.push({ label: t('nav.settings'), to: '/settings', icon: 'i-lucide-settings' })
|
||||
return items
|
||||
})
|
||||
|
||||
/** 三个上传入口,与顶部 Logo 并列 */
|
||||
const hostItems = computed(() => [
|
||||
{
|
||||
label: t('host.image'),
|
||||
to: '/',
|
||||
icon: 'i-lucide-image',
|
||||
title: t('host.imageFull')
|
||||
},
|
||||
{
|
||||
label: t('host.video'),
|
||||
to: '/videos',
|
||||
icon: 'i-lucide-film',
|
||||
title: t('host.videoFull')
|
||||
},
|
||||
{
|
||||
label: t('host.file'),
|
||||
to: '/files',
|
||||
icon: 'i-lucide-folder-open',
|
||||
title: t('host.fileFull')
|
||||
}
|
||||
])
|
||||
|
||||
const mobileNavItems = computed(() => [...hostItems.value, ...navItems.value])
|
||||
|
||||
function isHostActive(to: string) {
|
||||
return route.path === to || route.path.startsWith(`${to}/`)
|
||||
}
|
||||
|
||||
const accountMenuItems = computed<DropdownMenuItem[]>(() => [
|
||||
{
|
||||
label: t('profile.title'),
|
||||
icon: 'i-lucide-user-round',
|
||||
to: '/account/profile'
|
||||
},
|
||||
{
|
||||
label: t('nav.changePassword'),
|
||||
icon: 'i-lucide-key-round',
|
||||
@@ -66,9 +102,10 @@ async function handleLogout() {
|
||||
<header class="sticky top-0 z-40 border-b border-default bg-default/80 backdrop-blur">
|
||||
<div class="mx-auto max-w-7xl px-4 py-2.5 sm:px-6">
|
||||
<div class="flex items-center justify-between gap-3">
|
||||
<div class="flex min-w-0 items-center gap-2 sm:gap-3">
|
||||
<NuxtLink
|
||||
to="/"
|
||||
:title="t('nav.backToUpload')"
|
||||
:title="t('host.imageFull')"
|
||||
class="group flex min-w-0 shrink items-center gap-2.5 transition-opacity hover:opacity-90 sm:gap-3"
|
||||
>
|
||||
<img
|
||||
@@ -95,6 +132,21 @@ async function handleLogout() {
|
||||
</div>
|
||||
</NuxtLink>
|
||||
|
||||
<nav class="hidden items-center gap-1 sm:flex">
|
||||
<UButton
|
||||
v-for="item in hostItems"
|
||||
:key="item.to"
|
||||
:to="item.to"
|
||||
:icon="item.icon"
|
||||
:label="item.label"
|
||||
:title="item.title"
|
||||
size="sm"
|
||||
:variant="isHostActive(item.to) ? 'soft' : 'ghost'"
|
||||
:color="isHostActive(item.to) ? 'primary' : 'neutral'"
|
||||
/>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<ClientOnly>
|
||||
<div class="flex shrink-0 items-center gap-0.5 sm:gap-1">
|
||||
<nav class="hidden items-center gap-1 sm:flex">
|
||||
@@ -124,7 +176,7 @@ async function handleLogout() {
|
||||
/>
|
||||
<MobileNavMenu
|
||||
v-model:open="mobileNavOpen"
|
||||
:items="navItems"
|
||||
:items="mobileNavItems"
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageTag } from '~/types/image'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
tags: ImageTag[]
|
||||
selectedCount: number
|
||||
mode?: 'add' | 'remove'
|
||||
/** 仅添加标签,隐藏添加/移除切换(首页批量打标) */
|
||||
addOnly?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'confirm': [tagIds: number[], action: 'add' | 'remove']
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const action = ref<'add' | 'remove'>(props.mode ?? 'add')
|
||||
const selectedTagIds = ref<number[]>([])
|
||||
const { loadRecentIds } = useRecentTags()
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) {
|
||||
action.value = props.mode ?? 'add'
|
||||
selectedTagIds.value = []
|
||||
loadRecentIds()
|
||||
}
|
||||
})
|
||||
|
||||
function submit() {
|
||||
if (!selectedTagIds.value.length) return
|
||||
emit('confirm', selectedTagIds.value, action.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UModal
|
||||
:open="open"
|
||||
:title="addOnly ? t('tags.batchAddTitle') : t('tags.batchTitle')"
|
||||
:description="addOnly
|
||||
? t('tags.batchAddSubtitle', { n: selectedCount })
|
||||
: t('tags.batchSubtitle', { n: selectedCount })"
|
||||
:ui="{ content: 'max-w-md' }"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<template #body>
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
v-if="!addOnly"
|
||||
class="flex gap-1 rounded-lg border border-default p-0.5"
|
||||
>
|
||||
<UButton
|
||||
type="button"
|
||||
size="xs"
|
||||
class="flex-1 justify-center"
|
||||
:variant="action === 'add' ? 'solid' : 'ghost'"
|
||||
:color="action === 'add' ? 'primary' : 'neutral'"
|
||||
:label="t('tags.batchAdd')"
|
||||
@click="() => { action = 'add' }"
|
||||
/>
|
||||
<UButton
|
||||
type="button"
|
||||
size="xs"
|
||||
class="flex-1 justify-center"
|
||||
:variant="action === 'remove' ? 'solid' : 'ghost'"
|
||||
:color="action === 'remove' ? 'primary' : 'neutral'"
|
||||
:label="t('tags.batchRemove')"
|
||||
@click="() => { action = 'remove' }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<TagAssignPanel
|
||||
v-model="selectedTagIds"
|
||||
:tags="tags"
|
||||
:allow-create="action === 'add'"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex w-full flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p
|
||||
v-if="addOnly"
|
||||
class="flex items-center gap-1.5 text-xs text-muted"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-info"
|
||||
class="size-3.5 shrink-0"
|
||||
/>
|
||||
{{ t('tags.classifyHint') }}
|
||||
</p>
|
||||
<div class="flex flex-1 justify-end gap-2">
|
||||
<UButton
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
</UButton>
|
||||
<UButton
|
||||
color="primary"
|
||||
:disabled="!selectedTagIds.length"
|
||||
@click="submit"
|
||||
>
|
||||
{{ t('common.save') }}
|
||||
</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</template>
|
||||
@@ -0,0 +1,62 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
apiEndpoint: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
verified: [payload: { capToken: string }]
|
||||
cleared: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const widgetRef = ref<HTMLElement | null>(null)
|
||||
const ready = ref(false)
|
||||
|
||||
onMounted(async () => {
|
||||
const capWindow = window as Window & {
|
||||
CAP_CUSTOM_WASM_URL?: string
|
||||
CAP_CUSTOM_HASHWX_URL?: string
|
||||
}
|
||||
// SHA-256 与 hashwx 的求解器都放在本站 /cap,避免组件去 jsDelivr 拉 wasm。
|
||||
capWindow.CAP_CUSTOM_WASM_URL = '/cap/cap_wasm_bg.wasm'
|
||||
capWindow.CAP_CUSTOM_HASHWX_URL = '/cap/hashwx.wasm'
|
||||
await import('cap-widget')
|
||||
ready.value = true
|
||||
})
|
||||
|
||||
function onSolve(event: Event) {
|
||||
const token = (event as CustomEvent<{ token: string }>).detail?.token
|
||||
if (token) {
|
||||
emit('verified', { capToken: token })
|
||||
}
|
||||
}
|
||||
|
||||
function onError() {
|
||||
emit('cleared')
|
||||
}
|
||||
|
||||
function reset() {
|
||||
const widget = widgetRef.value as (HTMLElement & { reset?: () => void }) | null
|
||||
widget?.reset?.()
|
||||
emit('cleared')
|
||||
}
|
||||
|
||||
defineExpose({ reset })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ClientOnly>
|
||||
<cap-widget
|
||||
v-if="ready"
|
||||
ref="widgetRef"
|
||||
:data-cap-api-endpoint="props.apiEndpoint"
|
||||
:data-cap-i18n-initial-state="t('auth.capInitialState')"
|
||||
:data-cap-i18n-verifying-label="t('auth.capVerifying')"
|
||||
:data-cap-i18n-solved-label="t('auth.capSolved')"
|
||||
:data-cap-i18n-error-label="t('auth.capError')"
|
||||
@solve="onSolve"
|
||||
@error="onError"
|
||||
/>
|
||||
</ClientOnly>
|
||||
</template>
|
||||
@@ -0,0 +1,159 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'cleared': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
const step = ref<'warning' | 'confirm'>('warning')
|
||||
const confirmation = ref('')
|
||||
const clearing = ref(false)
|
||||
|
||||
const canConfirm = computed(() =>
|
||||
!clearing.value && confirmation.value.trim() === t('storage.clearStoragePhrase')
|
||||
)
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) {
|
||||
step.value = 'warning'
|
||||
confirmation.value = ''
|
||||
clearing.value = false
|
||||
}
|
||||
})
|
||||
|
||||
function close() {
|
||||
if (clearing.value) return
|
||||
emit('update:open', false)
|
||||
}
|
||||
|
||||
function goToConfirm() {
|
||||
step.value = 'confirm'
|
||||
}
|
||||
|
||||
function clearBrowserCache() {
|
||||
const keys = [
|
||||
'pichost.upload-preferences',
|
||||
'pichost.upload-preferences.video',
|
||||
'pichost.upload-preferences.file',
|
||||
'pichost.recent-tag-ids',
|
||||
'pichost.library-view.image',
|
||||
'pichost.library-view.video',
|
||||
'pichost.library-view.file'
|
||||
]
|
||||
for (const key of keys) localStorage.removeItem(key)
|
||||
}
|
||||
|
||||
async function confirmClear() {
|
||||
if (!canConfirm.value) return
|
||||
clearing.value = true
|
||||
try {
|
||||
const result = await $fetch<{
|
||||
deletedMedia: number
|
||||
deletedObjects: number
|
||||
clearedCacheDirs: number
|
||||
failed: Array<{ key: string }>
|
||||
}>('/api/user/storage/purge', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { confirmation: confirmation.value.trim() }
|
||||
})
|
||||
|
||||
clearBrowserCache()
|
||||
emit('cleared')
|
||||
|
||||
if (result.failed.length) {
|
||||
toast.add({
|
||||
title: t('storage.clearStoragePartial', {
|
||||
failed: result.failed.length,
|
||||
total: result.deletedMedia + result.failed.length
|
||||
}),
|
||||
color: 'warning'
|
||||
})
|
||||
} else {
|
||||
toast.add({
|
||||
title: t('storage.clearStorageSuccess', {
|
||||
files: result.deletedObjects,
|
||||
cache: result.clearedCacheDirs
|
||||
}),
|
||||
color: 'success'
|
||||
})
|
||||
}
|
||||
emit('update:open', false)
|
||||
} catch (error: unknown) {
|
||||
const message = error && typeof error === 'object' && 'data' in error
|
||||
? (error as { data?: { error?: { message?: string } } }).data?.error?.message
|
||||
: undefined
|
||||
toast.add({
|
||||
title: message || t('storage.clearStorageFailed'),
|
||||
color: 'error'
|
||||
})
|
||||
} finally {
|
||||
clearing.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UModal
|
||||
:open="open"
|
||||
:title="step === 'warning' ? t('storage.clearStorageTitle') : t('storage.clearStorageFinalTitle')"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<template #body>
|
||||
<template v-if="step === 'warning'">
|
||||
<UAlert
|
||||
color="error"
|
||||
variant="subtle"
|
||||
icon="i-lucide-octagon-alert"
|
||||
:description="t('storage.clearStorageWarning')"
|
||||
/>
|
||||
<p class="mt-3 text-sm text-muted">
|
||||
{{ t('storage.clearStorageScope') }}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<p class="text-sm leading-6 text-muted">
|
||||
{{ t('storage.clearStorageInstruction') }}
|
||||
</p>
|
||||
<UInput
|
||||
v-model="confirmation"
|
||||
class="mt-3 w-full"
|
||||
:placeholder="t('storage.clearStoragePlaceholder')"
|
||||
autofocus
|
||||
/>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex w-full justify-end gap-2">
|
||||
<UButton
|
||||
:label="t('common.cancel')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
:disabled="clearing"
|
||||
@click="close"
|
||||
/>
|
||||
<UButton
|
||||
v-if="step === 'warning'"
|
||||
:label="t('common.continue')"
|
||||
color="error"
|
||||
@click="goToConfirm"
|
||||
/>
|
||||
<UButton
|
||||
v-else
|
||||
:label="t('storage.clearStorageConfirm')"
|
||||
color="error"
|
||||
:loading="clearing"
|
||||
:disabled="!canConfirm"
|
||||
@click="confirmClear"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</template>
|
||||
@@ -1,10 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import type { MediaType } from '~/types/media'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
count: number
|
||||
loading?: boolean
|
||||
/** 删除对象的类型,决定确认文案 */
|
||||
kind?: MediaType
|
||||
}>()
|
||||
|
||||
const kind = computed<MediaType>(() => props.kind ?? 'image')
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'confirm': []
|
||||
@@ -12,7 +18,16 @@ const emit = defineEmits<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const description = computed(() => t('delete.confirmDesc', { count: props.count }))
|
||||
const description = computed(() => {
|
||||
switch (kind.value) {
|
||||
case 'video':
|
||||
return t('delete.confirmDescVideo', { count: props.count })
|
||||
case 'file':
|
||||
return t('delete.confirmDescFile', { count: props.count })
|
||||
default:
|
||||
return t('delete.confirmDesc', { count: props.count })
|
||||
}
|
||||
})
|
||||
|
||||
function close() {
|
||||
emit('update:open', false)
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem } from '~/types/file'
|
||||
import { formatFileSize as formatSize } from '~/composables/useFileSize'
|
||||
|
||||
const props = defineProps<{
|
||||
item: FileItem
|
||||
link: string
|
||||
downloadLink: string
|
||||
selected?: boolean
|
||||
selectable?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'delete': []
|
||||
'update:selected': [value: boolean]
|
||||
}>()
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
|
||||
const uploadedLabel = computed(() => {
|
||||
try {
|
||||
return new Date(props.item.uploadedAt).toLocaleString(locale.value, { hour12: false })
|
||||
} catch {
|
||||
return props.item.uploadedAt
|
||||
}
|
||||
})
|
||||
|
||||
function fileIcon(item: FileItem): string {
|
||||
const type = item.contentType.toLowerCase()
|
||||
if (type.startsWith('image/')) return 'i-lucide-image'
|
||||
if (type.startsWith('video/')) return 'i-lucide-film'
|
||||
if (type.startsWith('audio/')) return 'i-lucide-music'
|
||||
if (type.includes('pdf')) return 'i-lucide-file-text'
|
||||
if (
|
||||
type.includes('zip')
|
||||
|| type.includes('rar')
|
||||
|| type.includes('7z')
|
||||
|| type.includes('tar')
|
||||
|| type.includes('gzip')
|
||||
) {
|
||||
return 'i-lucide-file-archive'
|
||||
}
|
||||
return 'i-lucide-file'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col overflow-hidden rounded-xl border border-default bg-elevated">
|
||||
<div class="relative flex aspect-[4/3] shrink-0 items-center justify-center bg-muted">
|
||||
<UIcon
|
||||
:name="fileIcon(item)"
|
||||
class="size-12 text-dimmed"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="selectable"
|
||||
class="absolute top-2 left-2 z-10"
|
||||
@click.stop
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="selected"
|
||||
@update:model-value="emit('update:selected', $event === true)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 flex-col gap-1.5 p-3">
|
||||
<p
|
||||
class="truncate text-sm font-semibold"
|
||||
:title="item.originalName"
|
||||
>
|
||||
{{ item.originalName }}
|
||||
</p>
|
||||
<p class="truncate text-xs text-muted">
|
||||
{{ uploadedLabel }} · {{ formatSize(item.size) }}
|
||||
</p>
|
||||
<TagBadgeList :tags="item.tags" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-around border-t border-default px-2 py-2">
|
||||
<CopyButton
|
||||
icon-only
|
||||
icon="i-lucide-link"
|
||||
:label="t('files.copyLink')"
|
||||
:value="link"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
icon="i-lucide-download"
|
||||
:to="downloadLink"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
:aria-label="t('files.download')"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
icon="i-lucide-trash-2"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="emit('delete')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,727 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem, FileListResponse } from '~/types/file'
|
||||
import type { LibraryStatsData } from '~/types/media'
|
||||
import { formatFileSize } from '~/composables/useFileSize'
|
||||
import SiteSyncSelectedDialog from '~/components/storage/SiteSyncSelectedDialog.vue'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
/** 文件库(file)与视频库结构一致,保留参数以便复用 */
|
||||
kind?: 'file' | 'video'
|
||||
}>(), {
|
||||
kind: 'file'
|
||||
})
|
||||
|
||||
const { isAuthenticated, handleAuthError } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t, locale } = useI18n()
|
||||
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
|
||||
|
||||
const items = ref<FileItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const totalPages = ref(1)
|
||||
const loading = ref(false)
|
||||
const stats = ref<LibraryStatsData | null>(null)
|
||||
const searchQuery = ref('')
|
||||
const activeSearch = ref('')
|
||||
const accessMode = ref<'public' | 'token'>('public')
|
||||
const apiToken = ref('')
|
||||
|
||||
const selectedKeys = ref<Set<string>>(new Set())
|
||||
const deleteModalOpen = ref(false)
|
||||
const deleteTargetKeys = ref<string[]>([])
|
||||
const deleting = ref(false)
|
||||
const batchTagOpen = ref(false)
|
||||
const syncOpen = ref(false)
|
||||
|
||||
const currentBackend = ref('all')
|
||||
const currentSource = ref('all')
|
||||
const backendOptions = ref<Array<{ id: string, name: string }>>([])
|
||||
const activeTagIds = ref<number[]>([])
|
||||
const activeTagMode = ref<'or' | 'and'>('or')
|
||||
const activeUntaggedOnly = ref(false)
|
||||
const { viewMode } = useLibraryView(props.kind)
|
||||
|
||||
const selectedCount = computed(() => selectedKeys.value.size)
|
||||
const syncKeys = computed(() => [...selectedKeys.value])
|
||||
|
||||
const pageText = computed(() => props.kind === 'video'
|
||||
? {
|
||||
title: t('library.video.title'),
|
||||
subtitle: t('library.video.subtitle'),
|
||||
empty: t('library.video.empty')
|
||||
}
|
||||
: {
|
||||
title: t('library.file.title'),
|
||||
subtitle: t('library.file.subtitle'),
|
||||
empty: t('library.file.empty')
|
||||
})
|
||||
|
||||
const allSelected = computed(() =>
|
||||
items.value.length > 0 && items.value.every(item => selectedKeys.value.has(item.key))
|
||||
)
|
||||
|
||||
const backendItems = computed(() => [
|
||||
{ label: t('stats.filterStorageAll'), value: 'all' },
|
||||
...backendOptions.value.map(backend => ({ label: backend.name, value: backend.id }))
|
||||
])
|
||||
|
||||
const sourceItems = computed(() => [
|
||||
{ label: t('stats.filterSourceAll'), value: 'all' },
|
||||
{ label: t('stats.sourceWeb'), value: 'web' },
|
||||
{ label: t('stats.sourceApi'), value: 'api' }
|
||||
])
|
||||
|
||||
function withToken(raw: string | undefined): string {
|
||||
if (!raw) return ''
|
||||
if (accessMode.value !== 'token' || !apiToken.value) return raw
|
||||
const separator = raw.includes('?') ? '&' : '?'
|
||||
return `${raw}${separator}token=${encodeURIComponent(apiToken.value)}`
|
||||
}
|
||||
|
||||
function fileLink(item: FileItem): string {
|
||||
return withToken(item.url)
|
||||
}
|
||||
|
||||
function displayName(item: FileItem): string {
|
||||
return item.originalName
|
||||
}
|
||||
|
||||
function uploadedLabel(item: FileItem): string {
|
||||
try {
|
||||
return new Date(item.uploadedAt).toLocaleString(locale.value, { hour12: false })
|
||||
} catch {
|
||||
return item.uploadedAt
|
||||
}
|
||||
}
|
||||
|
||||
function fileIcon(item: FileItem): string {
|
||||
const type = item.contentType.toLowerCase()
|
||||
if (type.startsWith('image/')) return 'i-lucide-image'
|
||||
if (type.startsWith('video/')) return 'i-lucide-film'
|
||||
if (type.startsWith('audio/')) return 'i-lucide-music'
|
||||
if (type.includes('pdf')) return 'i-lucide-file-text'
|
||||
if (
|
||||
type.includes('zip')
|
||||
|| type.includes('rar')
|
||||
|| type.includes('7z')
|
||||
|| type.includes('tar')
|
||||
|| type.includes('gzip')
|
||||
) {
|
||||
return 'i-lucide-file-archive'
|
||||
}
|
||||
return 'i-lucide-file'
|
||||
}
|
||||
|
||||
async function loadApiToken() {
|
||||
try {
|
||||
const data = await $fetch<{ apiUploadToken: string }>('/api/user/api-token', {
|
||||
credentials: 'include'
|
||||
})
|
||||
apiToken.value = data.apiUploadToken ?? ''
|
||||
} catch {
|
||||
apiToken.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBackendOptions() {
|
||||
try {
|
||||
const data = await $fetch<{ backends: Array<{ id: string, name: string }> }>(
|
||||
'/api/storage-backends',
|
||||
{ credentials: 'include' }
|
||||
)
|
||||
backendOptions.value = data.backends ?? []
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchStats() {
|
||||
if (!isAuthenticated.value) return
|
||||
try {
|
||||
stats.value = await $fetch<LibraryStatsData>('/api/library/stats', {
|
||||
credentials: 'include',
|
||||
query: { kind: props.kind }
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchList(targetPage = page.value) {
|
||||
if (!isAuthenticated.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await $fetch<FileListResponse>('/api/files', {
|
||||
credentials: 'include',
|
||||
query: {
|
||||
limit: pageSize.value,
|
||||
page: targetPage,
|
||||
kind: props.kind,
|
||||
...(activeSearch.value ? { q: activeSearch.value } : {}),
|
||||
...(currentBackend.value !== 'all' ? { backendId: currentBackend.value } : {}),
|
||||
...(currentSource.value !== 'all' ? { uploadSource: currentSource.value } : {}),
|
||||
...(activeTagIds.value.length ? { tagIds: activeTagIds.value.join(',') } : {}),
|
||||
...(activeUntaggedOnly.value ? { untagged: '1' } : {}),
|
||||
...(activeTagMode.value === 'and' ? { tagMode: 'and' } : {})
|
||||
}
|
||||
})
|
||||
|
||||
items.value = response.items
|
||||
total.value = response.total
|
||||
page.value = response.page
|
||||
totalPages.value = response.totalPages
|
||||
accessMode.value = response.accessMode
|
||||
|
||||
const visible = new Set(response.items.map(item => item.key))
|
||||
selectedKeys.value = new Set([...selectedKeys.value].filter(key => visible.has(key)))
|
||||
|
||||
if (response.accessMode === 'token' && !apiToken.value) {
|
||||
await loadApiToken()
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('files.loadFailed'), color: 'error' })
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await Promise.all([fetchList(1), fetchStats(), fetchTags()])
|
||||
}
|
||||
|
||||
async function submitSearch() {
|
||||
if (!isAuthenticated.value) return
|
||||
activeSearch.value = searchQuery.value.trim()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleBackendChange(value: string) {
|
||||
currentBackend.value = value
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleSourceChange(value: string) {
|
||||
currentSource.value = value
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleTagIdsChange(tagIds: number[]) {
|
||||
activeTagIds.value = tagIds
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleTagModeChange(tagMode: 'or' | 'and') {
|
||||
activeTagMode.value = tagMode
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleUntaggedChange(untaggedOnly: boolean) {
|
||||
activeUntaggedOnly.value = untaggedOnly
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function resetFilters() {
|
||||
searchQuery.value = ''
|
||||
activeSearch.value = ''
|
||||
currentBackend.value = 'all'
|
||||
currentSource.value = 'all'
|
||||
activeTagIds.value = []
|
||||
activeTagMode.value = 'or'
|
||||
activeUntaggedOnly.value = false
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
function toggleSelected(key: string, value: boolean) {
|
||||
const next = new Set(selectedKeys.value)
|
||||
if (value) next.add(key)
|
||||
else next.delete(key)
|
||||
selectedKeys.value = next
|
||||
}
|
||||
|
||||
function toggleSelectAll() {
|
||||
selectedKeys.value = allSelected.value
|
||||
? new Set()
|
||||
: new Set(items.value.map(item => item.key))
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedKeys.value = new Set()
|
||||
}
|
||||
|
||||
function setViewMode(mode: 'grid' | 'list') {
|
||||
viewMode.value = mode
|
||||
}
|
||||
|
||||
function openBatchTags() {
|
||||
batchTagOpen.value = true
|
||||
}
|
||||
|
||||
function openSync() {
|
||||
syncOpen.value = true
|
||||
}
|
||||
|
||||
function requestDelete(item: FileItem) {
|
||||
if (!isAuthenticated.value) return
|
||||
deleteTargetKeys.value = [item.key]
|
||||
deleteModalOpen.value = true
|
||||
}
|
||||
|
||||
function requestBatchDelete() {
|
||||
if (!isAuthenticated.value || !selectedCount.value) return
|
||||
deleteTargetKeys.value = [...selectedKeys.value]
|
||||
deleteModalOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
const keys = [...deleteTargetKeys.value]
|
||||
if (!keys.length || !isAuthenticated.value) return
|
||||
|
||||
deleting.value = true
|
||||
try {
|
||||
if (keys.length === 1) {
|
||||
await $fetch('/api/files', {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
query: { key: keys[0] }
|
||||
})
|
||||
} else {
|
||||
const response = await $fetch<{ deleted: string[], failed: unknown[] }>(
|
||||
'/api/files/batch-delete',
|
||||
{ method: 'POST', credentials: 'include', body: { keys } }
|
||||
)
|
||||
if (response.failed.length) {
|
||||
toast.add({
|
||||
title: t('library.deletePartialFail', { n: response.failed.length }),
|
||||
color: 'warning'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
toast.add({ title: t('library.fileDeleted', { n: keys.length }), color: 'success' })
|
||||
deleteModalOpen.value = false
|
||||
deleteTargetKeys.value = []
|
||||
selectedKeys.value = new Set()
|
||||
await refresh()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('files.deleteFailed'), color: 'error' })
|
||||
}
|
||||
} finally {
|
||||
deleting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmBatchTags(tagIds: number[], action: 'add' | 'remove') {
|
||||
const keys = [...selectedKeys.value]
|
||||
if (!keys.length || !tagIds.length) return
|
||||
|
||||
try {
|
||||
await batchUpdateTags(keys, tagIds, action)
|
||||
batchTagOpen.value = false
|
||||
selectedKeys.value = new Set()
|
||||
toast.add({ title: t('tags.batchSuccess'), color: 'success' })
|
||||
await Promise.all([fetchList(1), fetchStats(), fetchTags(true)])
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
toast.add({ title: t('tags.batchFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePageChange(targetPage: number) {
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(targetPage)
|
||||
}
|
||||
|
||||
async function handlePageSizeChange(size: number) {
|
||||
pageSize.value = size
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadBackendOptions()
|
||||
})
|
||||
|
||||
defineExpose({ refresh })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-2xl font-semibold tracking-tight">
|
||||
{{ pageText.title }}
|
||||
</h1>
|
||||
<p class="text-sm text-muted">
|
||||
{{ pageText.subtitle }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<UButton
|
||||
icon="i-lucide-refresh-cw"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
class="mt-0.5 shrink-0"
|
||||
:aria-label="t('common.refresh')"
|
||||
:loading="loading"
|
||||
@click="refresh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<LibraryStatsPanel
|
||||
:kind="props.kind"
|
||||
:stats="stats"
|
||||
:loading="loading"
|
||||
/>
|
||||
|
||||
<section class="space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<UCheckbox
|
||||
:model-value="allSelected"
|
||||
:disabled="!items.length"
|
||||
@update:model-value="toggleSelectAll"
|
||||
/>
|
||||
<span class="text-muted">
|
||||
{{ t('library.selectedCount', { n: selectedCount }) }}
|
||||
</span>
|
||||
<UButton
|
||||
v-if="selectedCount > 0"
|
||||
variant="link"
|
||||
color="primary"
|
||||
size="xs"
|
||||
:label="t('library.clearSelection')"
|
||||
@click="clearSelection"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<UInput
|
||||
v-model="searchQuery"
|
||||
icon="i-lucide-search"
|
||||
:placeholder="t('library.searchPlaceholder')"
|
||||
size="sm"
|
||||
class="w-44"
|
||||
@keydown.enter.prevent="submitSearch"
|
||||
/>
|
||||
<USelect
|
||||
:model-value="currentBackend"
|
||||
:items="backendItems"
|
||||
value-key="value"
|
||||
size="sm"
|
||||
class="w-32"
|
||||
:aria-label="t('stats.filterStorageAll')"
|
||||
@update:model-value="handleBackendChange"
|
||||
/>
|
||||
<USelect
|
||||
:model-value="currentSource"
|
||||
:items="sourceItems"
|
||||
value-key="value"
|
||||
size="sm"
|
||||
class="w-28"
|
||||
:aria-label="t('stats.filterSourceAll')"
|
||||
@update:model-value="handleSourceChange"
|
||||
/>
|
||||
<TagFilterSelect
|
||||
:model-value="activeTagIds"
|
||||
:tag-mode="activeTagMode"
|
||||
:untagged-only="activeUntaggedOnly"
|
||||
:tags="tagItems"
|
||||
:disabled="loading"
|
||||
@update:model-value="handleTagIdsChange"
|
||||
@update:tag-mode="handleTagModeChange"
|
||||
@update:untagged-only="handleUntaggedChange"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-search"
|
||||
size="sm"
|
||||
:label="t('common.search')"
|
||||
:loading="loading"
|
||||
@click="submitSearch"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-rotate-ccw"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
:label="t('library.reset')"
|
||||
@click="resetFilters"
|
||||
/>
|
||||
<UButton
|
||||
v-if="selectedCount > 0"
|
||||
icon="i-lucide-tags"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
size="sm"
|
||||
:disabled="!selectedCount || loading"
|
||||
:label="t('tags.batchAdd')"
|
||||
@click="openBatchTags"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-trash-2"
|
||||
variant="outline"
|
||||
color="error"
|
||||
size="sm"
|
||||
:disabled="!selectedCount || loading"
|
||||
:label="t('library.batchDelete')"
|
||||
@click="requestBatchDelete"
|
||||
/>
|
||||
<UButton
|
||||
v-if="selectedCount > 0"
|
||||
icon="i-lucide-cloud-upload"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
:disabled="!selectedCount || loading"
|
||||
:label="t('storage.backup.syncSelectedAction')"
|
||||
@click="openSync"
|
||||
/>
|
||||
<div class="flex gap-0.5 rounded-lg border border-default p-0.5">
|
||||
<UButton
|
||||
icon="i-lucide-layout-grid"
|
||||
size="xs"
|
||||
:variant="viewMode === 'grid' ? 'solid' : 'ghost'"
|
||||
:color="viewMode === 'grid' ? 'primary' : 'neutral'"
|
||||
:aria-label="t('stats.viewGrid')"
|
||||
@click="setViewMode('grid')"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-list"
|
||||
size="xs"
|
||||
:variant="viewMode === 'list' ? 'solid' : 'ghost'"
|
||||
:color="viewMode === 'list' ? 'primary' : 'neutral'"
|
||||
:aria-label="t('stats.viewList')"
|
||||
@click="setViewMode('list')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="loading && !items.length"
|
||||
class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
|
||||
>
|
||||
<USkeleton
|
||||
v-for="n in 8"
|
||||
:key="n"
|
||||
class="aspect-[4/3] rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-else-if="!items.length"
|
||||
class="rounded-lg border border-default py-10 text-center text-sm text-muted"
|
||||
>
|
||||
{{ activeSearch ? t('library.searchEmpty') : pageText.empty }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-else-if="viewMode === 'grid'"
|
||||
class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
|
||||
>
|
||||
<FileCard
|
||||
v-for="item in items"
|
||||
:key="item.key"
|
||||
:item="item"
|
||||
:link="fileLink(item)"
|
||||
:download-link="fileLink(item)"
|
||||
selectable
|
||||
:selected="selectedKeys.has(item.key)"
|
||||
@update:selected="toggleSelected(item.key, $event)"
|
||||
@delete="requestDelete(item)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="overflow-hidden rounded-xl border border-default bg-default"
|
||||
>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="min-w-full text-xs">
|
||||
<thead class="border-b border-default bg-elevated/40 text-muted">
|
||||
<tr>
|
||||
<th class="w-10 px-3 py-2.5 text-left font-medium">
|
||||
<UCheckbox
|
||||
:model-value="allSelected"
|
||||
:aria-label="t('stats.selectAll')"
|
||||
@update:model-value="toggleSelectAll"
|
||||
/>
|
||||
</th>
|
||||
<th class="min-w-[14rem] px-3 py-2.5 text-left font-medium">
|
||||
{{ t('stats.colFilename') }}
|
||||
</th>
|
||||
<th class="hidden w-24 px-3 py-2.5 text-left font-medium sm:table-cell">
|
||||
{{ t('stats.colSource') }}
|
||||
</th>
|
||||
<th class="w-20 px-3 py-2.5 text-left font-medium">
|
||||
{{ t('stats.colSize') }}
|
||||
</th>
|
||||
<th class="hidden w-28 px-3 py-2.5 text-left font-medium md:table-cell">
|
||||
{{ t('stats.colType') }}
|
||||
</th>
|
||||
<th class="hidden w-40 px-3 py-2.5 text-left font-medium lg:table-cell">
|
||||
{{ t('stats.colUploadedAt') }}
|
||||
</th>
|
||||
<th class="hidden min-w-[9rem] px-3 py-2.5 text-left font-medium md:table-cell">
|
||||
{{ t('tags.column') }}
|
||||
</th>
|
||||
<th class="w-24 px-3 py-2.5 text-right font-medium">
|
||||
{{ t('stats.colActions') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-default">
|
||||
<tr
|
||||
v-for="item in items"
|
||||
:key="item.key"
|
||||
class="transition-colors hover:bg-elevated/50"
|
||||
:class="selectedKeys.has(item.key) ? 'bg-primary/5' : ''"
|
||||
>
|
||||
<td class="px-3 py-2">
|
||||
<UCheckbox
|
||||
:model-value="selectedKeys.has(item.key)"
|
||||
@update:model-value="toggleSelected(item.key, $event === true)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-3 py-2.5">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<span class="flex size-10 shrink-0 items-center justify-center rounded-md border border-default bg-muted">
|
||||
<UIcon
|
||||
:name="fileIcon(item)"
|
||||
class="size-4 text-dimmed"
|
||||
/>
|
||||
</span>
|
||||
<p
|
||||
class="min-w-0 flex-1 truncate text-highlighted"
|
||||
:title="displayName(item)"
|
||||
>
|
||||
{{ displayName(item) }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 sm:table-cell">
|
||||
<span
|
||||
v-if="item.uploadSource"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-default px-1.5 py-0.5 text-[11px] leading-4 text-muted"
|
||||
>
|
||||
<UIcon
|
||||
:name="item.uploadSource === 'api' ? 'i-lucide-code-xml' : 'i-lucide-globe'"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ item.uploadSource === 'api' ? t('stats.tagApi') : t('stats.tagWeb') }}
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted"
|
||||
>—</span>
|
||||
</td>
|
||||
<td class="px-3 py-2 tabular-nums text-muted">
|
||||
{{ formatFileSize(item.size) }}
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 md:table-cell">
|
||||
<span
|
||||
v-if="item.storage"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-default px-1.5 py-0.5 text-[11px] leading-4 text-muted"
|
||||
>
|
||||
<UIcon
|
||||
:name="item.storage.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ item.storage.name }}
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted"
|
||||
>—</span>
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 text-muted lg:table-cell">
|
||||
{{ uploadedLabel(item) }}
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 md:table-cell">
|
||||
<TagBadgeList
|
||||
:tags="item.tags"
|
||||
compact
|
||||
:empty-label="t('tags.unlabeled')"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex items-center justify-end gap-1">
|
||||
<CopyButton
|
||||
icon-only
|
||||
icon="i-lucide-link"
|
||||
:label="t('files.copyLink')"
|
||||
:value="fileLink(item)"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
icon="i-lucide-download"
|
||||
:to="fileLink(item)"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
:aria-label="t('files.download')"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
icon="i-lucide-trash-2"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="requestDelete(item)"
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
v-if="!loading && total > 0"
|
||||
:page="page"
|
||||
:total-pages="totalPages"
|
||||
:total="total"
|
||||
:page-size="pageSize"
|
||||
unit=""
|
||||
:loading="loading"
|
||||
@update:page="handlePageChange"
|
||||
@update:page-size="handlePageSizeChange"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<DeleteConfirmModal
|
||||
v-model:open="deleteModalOpen"
|
||||
:count="deleteTargetKeys.length"
|
||||
:loading="deleting"
|
||||
:kind="props.kind"
|
||||
@confirm="confirmDelete"
|
||||
/>
|
||||
|
||||
<BatchTagModal
|
||||
v-model:open="batchTagOpen"
|
||||
:tags="tagItems"
|
||||
:selected-count="selectedCount"
|
||||
@confirm="confirmBatchTags"
|
||||
/>
|
||||
|
||||
<SiteSyncSelectedDialog
|
||||
v-model:open="syncOpen"
|
||||
:keys="syncKeys"
|
||||
scope="file"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,100 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem } from '~/types/file'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
item: FileItem | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
const downloading = ref(false)
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (!open) downloading.value = false
|
||||
})
|
||||
|
||||
async function confirmDownload() {
|
||||
const item = props.item
|
||||
if (!item?.hlsKey || downloading.value) return
|
||||
|
||||
downloading.value = true
|
||||
try {
|
||||
const response = await fetch('/api/files/hls-mp4', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ key: item.key })
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const payload = await response.json().catch(() => null) as {
|
||||
error?: { message?: string }
|
||||
} | null
|
||||
throw new Error(payload?.error?.message || t('library.video.downloadMp4Failed'))
|
||||
}
|
||||
|
||||
const blob = await response.blob()
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
const dot = item.originalName.lastIndexOf('.')
|
||||
const filename = `${dot > 0 ? item.originalName.slice(0, dot) : item.originalName}.mp4`
|
||||
const link = document.createElement('a')
|
||||
link.href = objectUrl
|
||||
link.download = filename
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
setTimeout(() => URL.revokeObjectURL(objectUrl), 0)
|
||||
emit('update:open', false)
|
||||
} catch (error) {
|
||||
toast.add({
|
||||
title: error instanceof Error ? error.message : t('library.video.downloadMp4Failed'),
|
||||
color: 'error'
|
||||
})
|
||||
} finally {
|
||||
downloading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UModal
|
||||
:open="open && !!item"
|
||||
:title="t('library.video.downloadMp4Title')"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<template #body>
|
||||
<p class="text-sm leading-6 text-muted">
|
||||
{{ t('library.video.downloadMp4Confirm') }}
|
||||
</p>
|
||||
<p
|
||||
v-if="downloading"
|
||||
class="mt-3 text-sm text-primary"
|
||||
>
|
||||
{{ t('library.video.downloadMp4Working') }}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex w-full justify-end gap-2">
|
||||
<UButton
|
||||
:label="t('common.cancel')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
:disabled="downloading"
|
||||
@click="emit('update:open', false)"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('common.continue')"
|
||||
color="primary"
|
||||
:loading="downloading"
|
||||
@click="confirmDownload"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</template>
|
||||
+153
-10
@@ -1,6 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageItem } from '~/types/image'
|
||||
import type { CopyFormat } from '~/composables/useUploadPreferences'
|
||||
import { buildImageBbcode } from '~/utils/image-display'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
image: ImageItem
|
||||
@@ -10,18 +11,27 @@ const props = withDefaults(defineProps<{
|
||||
showStorage?: boolean
|
||||
compact?: boolean
|
||||
gallery?: boolean
|
||||
allowDelete?: boolean
|
||||
showTags?: boolean
|
||||
showTagAction?: boolean
|
||||
}>(), {
|
||||
selectable: true,
|
||||
showKey: true,
|
||||
showStorage: false,
|
||||
compact: false,
|
||||
gallery: false
|
||||
gallery: false,
|
||||
allowDelete: true,
|
||||
showTags: false,
|
||||
showTagAction: false
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:selected': [value: boolean]
|
||||
'preview': []
|
||||
'delete': []
|
||||
'tag-click': [tagId: number]
|
||||
'untagged-click': []
|
||||
'edit-tags': []
|
||||
}>()
|
||||
|
||||
const { formatFileSize } = useFileSize()
|
||||
@@ -77,7 +87,8 @@ onUnmounted(clearRetryTimer)
|
||||
const copyFormatItems = computed(() => [
|
||||
{ label: t('copy.url'), value: 'url' as const },
|
||||
{ label: t('copy.markdown'), value: 'markdown' as const },
|
||||
{ label: t('copy.html'), value: 'html' as const }
|
||||
{ label: t('copy.html'), value: 'html' as const },
|
||||
{ label: t('copy.bbcode'), value: 'bbcode' as const }
|
||||
])
|
||||
|
||||
const uploadedLabel = computed(() => {
|
||||
@@ -94,6 +105,8 @@ const previewValue = computed(() => {
|
||||
return props.image.markdown
|
||||
case 'html':
|
||||
return props.image.html
|
||||
case 'bbcode':
|
||||
return buildImageBbcode(props.image.url)
|
||||
default:
|
||||
return props.image.url
|
||||
}
|
||||
@@ -105,6 +118,8 @@ const copySuccessTitle = computed(() => {
|
||||
return t('copy.copiedMarkdown')
|
||||
case 'html':
|
||||
return t('copy.copiedHtml')
|
||||
case 'bbcode':
|
||||
return t('copy.copiedBbcode')
|
||||
default:
|
||||
return t('copy.copiedUrl')
|
||||
}
|
||||
@@ -125,6 +140,34 @@ const uploadSourceLabel = computed(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const uploadSourceIcon = computed(() => {
|
||||
switch (props.image.uploadSource) {
|
||||
case 'web':
|
||||
return 'i-lucide-globe'
|
||||
case 'api':
|
||||
return 'i-lucide-code-xml'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
const GALLERY_INLINE_TAG_LIMIT = 3
|
||||
|
||||
const galleryTagDisplay = computed(() => {
|
||||
const tags = props.image.tags ?? []
|
||||
if (tags.length <= GALLERY_INLINE_TAG_LIMIT) {
|
||||
return { visible: tags, hidden: [] as typeof tags }
|
||||
}
|
||||
return {
|
||||
visible: tags.slice(0, GALLERY_INLINE_TAG_LIMIT),
|
||||
hidden: tags.slice(GALLERY_INLINE_TAG_LIMIT)
|
||||
}
|
||||
})
|
||||
const sessionVisibleTags = computed(() => props.image.tags ?? [])
|
||||
const sessionTagActionLabel = computed(() =>
|
||||
props.image.tags?.length ? t('tags.addTag') : t('tags.untagged')
|
||||
)
|
||||
|
||||
function toggleSelected(value: boolean | 'indeterminate') {
|
||||
emit('update:selected', value === true)
|
||||
}
|
||||
@@ -208,16 +251,61 @@ async function copyGalleryUrl() {
|
||||
<p class="truncate text-xs text-muted">
|
||||
{{ uploadedLabel }} · {{ formatFileSize(image.size) }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-if="showTags"
|
||||
class="flex flex-wrap items-center gap-1.5"
|
||||
>
|
||||
<template v-if="image.tags?.length">
|
||||
<TagBadge
|
||||
v-for="tag in galleryTagDisplay.visible"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
clickable
|
||||
@click="emit('tag-click', tag.id)"
|
||||
/>
|
||||
<UPopover
|
||||
v-if="galleryTagDisplay.hidden.length"
|
||||
:content="{ side: 'bottom', align: 'start' }"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex rounded-md border border-default px-2 py-0.5 text-xs text-muted transition-colors hover:border-primary/40 hover:text-primary"
|
||||
:aria-label="t('tags.moreTags', { n: galleryTagDisplay.hidden.length })"
|
||||
@click.stop
|
||||
>
|
||||
+{{ galleryTagDisplay.hidden.length }}
|
||||
</button>
|
||||
<template #content>
|
||||
<div
|
||||
class="flex max-w-56 flex-wrap gap-1.5 p-2"
|
||||
@click.stop
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in galleryTagDisplay.hidden"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
clickable
|
||||
@click="emit('tag-click', tag.id)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UPopover>
|
||||
</template>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="inline-flex rounded-md border border-dashed border-default px-2 py-0.5 text-xs text-muted transition-colors hover:border-primary/40 hover:text-primary"
|
||||
@click.stop="emit('untagged-click')"
|
||||
>
|
||||
{{ t('tags.unlabeled') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="uploadSourceLabel || (showStorage && image.storage)"
|
||||
class="flex flex-wrap gap-1.5"
|
||||
class="flex flex-wrap items-center gap-1.5"
|
||||
>
|
||||
<span
|
||||
v-if="uploadSourceLabel"
|
||||
class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary"
|
||||
>
|
||||
{{ uploadSourceLabel }}
|
||||
</span>
|
||||
<span
|
||||
v-if="showStorage && image.storage"
|
||||
class="inline-flex max-w-full items-center gap-1 rounded-md border border-default px-2 py-0.5 text-xs text-muted"
|
||||
@@ -229,6 +317,16 @@ async function copyGalleryUrl() {
|
||||
/>
|
||||
<span class="truncate">{{ image.storage.name }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-if="uploadSourceLabel && uploadSourceIcon"
|
||||
class="inline-flex max-w-full items-center gap-1 rounded-md border border-default px-2 py-0.5 text-xs text-muted"
|
||||
>
|
||||
<UIcon
|
||||
:name="uploadSourceIcon"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ uploadSourceLabel }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -251,6 +349,7 @@ async function copyGalleryUrl() {
|
||||
@click="emit('preview')"
|
||||
/>
|
||||
<UButton
|
||||
v-if="allowDelete"
|
||||
icon="i-lucide-trash-2"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
@@ -299,6 +398,21 @@ async function copyGalleryUrl() {
|
||||
@update:model-value="toggleSelected"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="allowDelete && showTagAction"
|
||||
class="absolute top-2 right-2"
|
||||
@click.stop
|
||||
>
|
||||
<UButton
|
||||
icon="i-lucide-trash-2"
|
||||
variant="solid"
|
||||
color="neutral"
|
||||
size="xs"
|
||||
class="bg-black/55 text-white hover:bg-black/70"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="emit('delete')"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
v-if="image.owner"
|
||||
class="absolute bottom-2 left-2 max-w-[calc(50%-0.5rem)]"
|
||||
@@ -368,6 +482,20 @@ async function copyGalleryUrl() {
|
||||
>
|
||||
{{ image.originalName }}
|
||||
</p>
|
||||
|
||||
<button
|
||||
v-if="showTagAction && image.tags?.length"
|
||||
type="button"
|
||||
class="flex flex-wrap items-center gap-1.5 text-left"
|
||||
@click.stop="emit('edit-tags')"
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in sessionVisibleTags"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
/>
|
||||
</button>
|
||||
|
||||
<p class="text-xs text-muted">
|
||||
{{ uploadedLabel }} · {{ formatFileSize(image.size) }}
|
||||
</p>
|
||||
@@ -393,13 +521,28 @@ async function copyGalleryUrl() {
|
||||
class="min-w-0 flex-1 font-mono text-xs"
|
||||
/>
|
||||
<CopyButton
|
||||
icon="i-lucide-copy"
|
||||
:label="t('common.copy')"
|
||||
:variant="showTagAction ? 'solid' : 'soft'"
|
||||
:color="showTagAction ? 'primary' : undefined"
|
||||
:icon="showTagAction ? undefined : 'i-lucide-copy'"
|
||||
:value="previewValue"
|
||||
:success-title="copySuccessTitle"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="showTagAction"
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 self-start text-xs text-muted transition-colors hover:text-primary"
|
||||
@click.stop="emit('edit-tags')"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-plus"
|
||||
class="size-3"
|
||||
/>
|
||||
{{ sessionTagActionLabel }}
|
||||
</button>
|
||||
|
||||
<p
|
||||
v-if="showKey"
|
||||
class="truncate text-xs text-dimmed"
|
||||
|
||||
@@ -12,13 +12,19 @@ const props = withDefaults(defineProps<{
|
||||
compact?: boolean
|
||||
/** 图库:5 列 × 2 行,缩略图略扁 */
|
||||
gallery?: boolean
|
||||
allowDelete?: boolean
|
||||
showTags?: boolean
|
||||
showTagAction?: boolean
|
||||
}>(), {
|
||||
selectable: true,
|
||||
showKey: true,
|
||||
showStorage: false,
|
||||
dense: false,
|
||||
compact: false,
|
||||
gallery: false
|
||||
gallery: false,
|
||||
allowDelete: true,
|
||||
showTags: false,
|
||||
showTagAction: false
|
||||
})
|
||||
|
||||
const gridClass = computed(() => {
|
||||
@@ -35,6 +41,9 @@ const emit = defineEmits<{
|
||||
'update:selectedKeys': [value: Set<string>]
|
||||
'preview': [image: ImageItem]
|
||||
'delete': [image: ImageItem]
|
||||
'tag-click': [tagId: number]
|
||||
'untagged-click': []
|
||||
'edit-tags': [image: ImageItem]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
@@ -65,9 +74,15 @@ function updateSelection(key: string, selected: boolean) {
|
||||
:show-storage="showStorage"
|
||||
:compact="compact"
|
||||
:gallery="gallery"
|
||||
:allow-delete="allowDelete"
|
||||
:show-tags="showTags"
|
||||
:show-tag-action="showTagAction"
|
||||
@update:selected="updateSelection(image.key, $event)"
|
||||
@preview="emit('preview', image)"
|
||||
@delete="emit('delete', image)"
|
||||
@tag-click="emit('tag-click', $event)"
|
||||
@untagged-click="emit('untagged-click')"
|
||||
@edit-tags="emit('edit-tags', image)"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageItem } from '~/types/image'
|
||||
import type { CopyFormat } from '~/composables/useUploadPreferences'
|
||||
import { formatImageDimensions } from '~/utils/image-display'
|
||||
|
||||
type EmbedFormat = CopyFormat | 'bbcode'
|
||||
import { buildImageBbcode, formatImageDimensions } from '~/utils/image-display'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
open: boolean
|
||||
image: ImageItem | null
|
||||
showStorage?: boolean
|
||||
showTags?: boolean
|
||||
deleting?: boolean
|
||||
allowDelete?: boolean
|
||||
}>(), {
|
||||
showStorage: false
|
||||
showStorage: false,
|
||||
showTags: false,
|
||||
allowDelete: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -20,6 +22,7 @@ const emit = defineEmits<{
|
||||
}>()
|
||||
|
||||
const toast = useToast()
|
||||
|
||||
const { formatFileSize } = useFileSize()
|
||||
const { t, locale } = useI18n()
|
||||
const { copyFormat } = useUploadPreferences()
|
||||
@@ -28,7 +31,7 @@ const naturalWidth = ref<number | null>(null)
|
||||
const naturalHeight = ref<number | null>(null)
|
||||
const dimensionsLoaded = ref(false)
|
||||
const copyingUrl = ref(false)
|
||||
const embedFormat = ref<EmbedFormat>('url')
|
||||
const embedFormat = ref<CopyFormat>('url')
|
||||
|
||||
const embedFormatItems = computed(() => [
|
||||
{ label: t('copy.url'), value: 'url' as const },
|
||||
@@ -63,7 +66,7 @@ const sizeLabel = computed(() => {
|
||||
|
||||
const bbcodeValue = computed(() => {
|
||||
if (!props.image) return ''
|
||||
return `[img]${props.image.url}[/img]`
|
||||
return buildImageBbcode(props.image.url)
|
||||
})
|
||||
|
||||
const previewValue = computed(() => {
|
||||
@@ -108,6 +111,17 @@ const uploadSourceTag = computed(() => {
|
||||
}
|
||||
})
|
||||
|
||||
const uploadSourceIcon = computed(() => {
|
||||
switch (props.image?.uploadSource) {
|
||||
case 'web':
|
||||
return 'i-lucide-globe'
|
||||
case 'api':
|
||||
return 'i-lucide-code-xml'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
const dimensionsLabel = computed(() => {
|
||||
const formatted = formatImageDimensions(naturalWidth.value, naturalHeight.value)
|
||||
if (formatted) return formatted
|
||||
@@ -126,11 +140,9 @@ watch(() => props.open, (open) => {
|
||||
}
|
||||
})
|
||||
|
||||
function selectEmbedFormat(value: EmbedFormat) {
|
||||
function selectEmbedFormat(value: CopyFormat) {
|
||||
embedFormat.value = value
|
||||
if (value !== 'bbcode') {
|
||||
copyFormat.value = value
|
||||
}
|
||||
}
|
||||
|
||||
async function copyText(text: string, successTitle: string) {
|
||||
@@ -286,6 +298,32 @@ function onImageLoad(event: Event) {
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div
|
||||
v-if="showTags"
|
||||
class="flex gap-4 py-2.5"
|
||||
>
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('tags.column') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
<div
|
||||
v-if="image.tags?.length"
|
||||
class="flex flex-wrap gap-1.5"
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in image.tags"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex rounded-md border border-dashed border-default px-2 py-0.5 text-xs text-muted"
|
||||
>
|
||||
{{ t('tags.unlabeled') }}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div
|
||||
v-if="uploadSourceTag"
|
||||
class="flex gap-4 py-2.5"
|
||||
@@ -294,7 +332,14 @@ function onImageLoad(event: Event) {
|
||||
{{ t('image.previewUploadSource') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
<span class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
|
||||
<span
|
||||
v-if="uploadSourceIcon"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-default px-2 py-0.5 text-xs text-muted"
|
||||
>
|
||||
<UIcon
|
||||
:name="uploadSourceIcon"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ uploadSourceTag }}
|
||||
</span>
|
||||
</dd>
|
||||
@@ -396,6 +441,7 @@ function onImageLoad(event: Event) {
|
||||
@click="copyLink"
|
||||
/>
|
||||
<UButton
|
||||
v-if="allowDelete"
|
||||
:label="t('common.delete')"
|
||||
icon="i-lucide-trash-2"
|
||||
color="error"
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageItem, ImageTag } from '~/types/image'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
image: ImageItem | null
|
||||
tags: ImageTag[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'saved': [tags: ImageTag[]]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
const { setImageTags, fetchTags } = useTags()
|
||||
const { recordRecent, loadRecentIds } = useRecentTags()
|
||||
|
||||
const selectedTagIds = ref<number[]>([])
|
||||
const saving = ref(false)
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) {
|
||||
selectedTagIds.value = props.image?.tags?.map(tag => tag.id) ?? []
|
||||
loadRecentIds()
|
||||
void fetchTags(true)
|
||||
}
|
||||
})
|
||||
|
||||
async function save() {
|
||||
if (!props.image || saving.value) return
|
||||
|
||||
saving.value = true
|
||||
try {
|
||||
const tags = await setImageTags(props.image.key, selectedTagIds.value)
|
||||
recordRecent(selectedTagIds.value)
|
||||
emit('saved', tags)
|
||||
emit('update:open', false)
|
||||
toast.add({ title: t('tags.saved'), color: 'success' })
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : t('tags.saveFailed')
|
||||
toast.add({ title: message, color: 'error' })
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function onTagCreated(tag: ImageTag) {
|
||||
if (!selectedTagIds.value.includes(tag.id)) {
|
||||
selectedTagIds.value = [...selectedTagIds.value, tag.id]
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UModal
|
||||
:open="open"
|
||||
:title="t('tags.manageImageTitle')"
|
||||
:description="image?.originalName"
|
||||
:ui="{ content: 'max-w-md' }"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<template #body>
|
||||
<TagAssignPanel
|
||||
v-model="selectedTagIds"
|
||||
:tags="tags"
|
||||
:disabled="saving"
|
||||
@created="onTagCreated"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex w-full flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p class="flex items-center gap-1.5 text-xs text-muted">
|
||||
<UIcon
|
||||
name="i-lucide-info"
|
||||
class="size-3.5 shrink-0"
|
||||
/>
|
||||
{{ t('tags.classifyHint') }}
|
||||
</p>
|
||||
<div class="flex justify-end gap-2">
|
||||
<UButton
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
:disabled="saving"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
</UButton>
|
||||
<UButton
|
||||
color="primary"
|
||||
:loading="saving"
|
||||
@click="save"
|
||||
>
|
||||
{{ t('common.save') }}
|
||||
</UButton>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</template>
|
||||
+20
-22
@@ -1,33 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
export interface GalleryStatsData {
|
||||
uploadToday: number
|
||||
uploadYesterday: number
|
||||
uploadMonth: number
|
||||
uploadLastMonth: number
|
||||
uploadTotal: number
|
||||
storedCount: number
|
||||
uploadBytesTotal: number
|
||||
bySource: {
|
||||
web: number
|
||||
api: number
|
||||
}
|
||||
storageUsage: {
|
||||
usedBytes: number
|
||||
totalBytes: number | null
|
||||
percent: number | null
|
||||
}
|
||||
}
|
||||
import type { LibraryStatsData, MediaType } from '~/types/media'
|
||||
|
||||
const props = defineProps<{
|
||||
stats: GalleryStatsData | null
|
||||
const props = withDefaults(defineProps<{
|
||||
stats: LibraryStatsData | null
|
||||
/** 统计口径:图片 / 视频 / 文件各自独立 */
|
||||
kind?: MediaType
|
||||
loading?: boolean
|
||||
}>()
|
||||
}>(), {
|
||||
kind: 'image'
|
||||
})
|
||||
|
||||
const { t } = useI18n()
|
||||
const { formatFileSize } = useFileSize()
|
||||
|
||||
const SOURCE_COLORS = ['var(--ui-primary)', '#10b981'] as const
|
||||
|
||||
const totalHint = computed(() => {
|
||||
switch (props.kind) {
|
||||
case 'video':
|
||||
return t('library.statsTotalHintVideo')
|
||||
case 'file':
|
||||
return t('library.statsTotalHintFile')
|
||||
default:
|
||||
return t('library.statsTotalHintImage')
|
||||
}
|
||||
})
|
||||
|
||||
const sourceItems = computed(() => {
|
||||
const bySource = props.stats?.bySource
|
||||
if (!bySource) return []
|
||||
@@ -147,7 +145,7 @@ function displayValue(value: number | undefined) {
|
||||
{{ displayValue(stats?.uploadTotal) }}
|
||||
</p>
|
||||
<p class="mt-2 text-xs text-muted">
|
||||
{{ t('stats.totalFiles') }}
|
||||
{{ totalHint }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
<script setup lang="ts">
|
||||
import type {
|
||||
LoginVerificationMethod,
|
||||
LoginVerificationPayload
|
||||
} from '~/types/auth'
|
||||
|
||||
const props = defineProps<{
|
||||
method: LoginVerificationMethod
|
||||
turnstileSiteKey?: string
|
||||
capApiEndpoint?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
verified: [payload: LoginVerificationPayload]
|
||||
cleared: []
|
||||
}>()
|
||||
|
||||
const sliderRef = ref<{ reset: () => Promise<void> } | null>(null)
|
||||
const turnstileRef = ref<{ reset: () => void } | null>(null)
|
||||
const capRef = ref<{ reset: () => void } | null>(null)
|
||||
|
||||
function onSliderVerified(payload: { id: string, positionPercent: number }) {
|
||||
emit('verified', {
|
||||
method: 'slider',
|
||||
captchaId: payload.id,
|
||||
captchaPosition: payload.positionPercent
|
||||
})
|
||||
}
|
||||
|
||||
function onTurnstileVerified(payload: { turnstileToken: string }) {
|
||||
emit('verified', {
|
||||
method: 'turnstile',
|
||||
turnstileToken: payload.turnstileToken
|
||||
})
|
||||
}
|
||||
|
||||
function onCapVerified(payload: { capToken: string }) {
|
||||
emit('verified', {
|
||||
method: 'cap',
|
||||
capToken: payload.capToken
|
||||
})
|
||||
}
|
||||
|
||||
function onCleared() {
|
||||
emit('cleared')
|
||||
}
|
||||
|
||||
async function reset() {
|
||||
emit('cleared')
|
||||
if (props.method === 'slider') {
|
||||
await sliderRef.value?.reset()
|
||||
return
|
||||
}
|
||||
if (props.method === 'turnstile') {
|
||||
turnstileRef.value?.reset()
|
||||
return
|
||||
}
|
||||
capRef.value?.reset()
|
||||
}
|
||||
|
||||
defineExpose({ reset })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SliderCaptcha
|
||||
v-if="method === 'slider'"
|
||||
ref="sliderRef"
|
||||
@verified="onSliderVerified"
|
||||
/>
|
||||
<TurnstileCaptcha
|
||||
v-else-if="method === 'turnstile' && turnstileSiteKey"
|
||||
ref="turnstileRef"
|
||||
:site-key="turnstileSiteKey"
|
||||
@verified="onTurnstileVerified"
|
||||
@cleared="onCleared"
|
||||
/>
|
||||
<CapCaptcha
|
||||
v-else-if="method === 'cap' && capApiEndpoint"
|
||||
ref="capRef"
|
||||
:api-endpoint="capApiEndpoint"
|
||||
@verified="onCapVerified"
|
||||
@cleared="onCleared"
|
||||
/>
|
||||
<p
|
||||
v-else
|
||||
class="rounded-lg border border-warning/25 bg-warning/5 px-3 py-2 text-xs text-warning"
|
||||
>
|
||||
{{ $t('auth.verificationMisconfigured') }}
|
||||
</p>
|
||||
</template>
|
||||
@@ -0,0 +1,287 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem } from '~/types/file'
|
||||
import type { CopyFormat, UploadMediaKind } from '~/composables/useUploadPreferences'
|
||||
|
||||
const props = defineProps<{
|
||||
item: FileItem
|
||||
kind: UploadMediaKind
|
||||
/** 已按访问模式拼接好的直链 */
|
||||
link: string
|
||||
/** 封面缩略图地址 */
|
||||
thumbLink?: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
delete: []
|
||||
}>()
|
||||
|
||||
const { formatFileSize } = useFileSize()
|
||||
const { t, locale } = useI18n()
|
||||
const transcodeFailureLabel = useTranscodeFailureLabel()
|
||||
const { copyFormat } = useUploadPreferences(props.kind)
|
||||
|
||||
const copyFormatItems = computed(() => [
|
||||
{ label: t('copy.url'), value: 'url' as const },
|
||||
{ label: t('copy.markdown'), value: 'markdown' as const },
|
||||
{ label: t('copy.html'), value: 'html' as const },
|
||||
{ label: t('copy.bbcode'), value: 'bbcode' as const }
|
||||
])
|
||||
|
||||
const uploadedLabel = computed(() => {
|
||||
try {
|
||||
return new Date(props.item.uploadedAt).toLocaleString(locale.value, { hour12: false })
|
||||
} catch {
|
||||
return props.item.uploadedAt
|
||||
}
|
||||
})
|
||||
|
||||
const previewValue = computed(() => {
|
||||
switch (copyFormat.value) {
|
||||
case 'markdown':
|
||||
return `[${props.item.originalName}](${props.link})`
|
||||
case 'html':
|
||||
return `<a href="${props.link}">${props.item.originalName}</a>`
|
||||
case 'bbcode':
|
||||
return `[url=${props.link}]${props.item.originalName}[/url]`
|
||||
default:
|
||||
return props.link
|
||||
}
|
||||
})
|
||||
|
||||
const copySuccessTitle = computed(() => {
|
||||
switch (copyFormat.value) {
|
||||
case 'markdown':
|
||||
return t('copy.copiedMarkdown')
|
||||
case 'html':
|
||||
return t('copy.copiedHtml')
|
||||
case 'bbcode':
|
||||
return t('copy.copiedBbcode')
|
||||
default:
|
||||
return t('copy.copiedUrl')
|
||||
}
|
||||
})
|
||||
|
||||
function selectCopyFormat(value: CopyFormat) {
|
||||
copyFormat.value = value
|
||||
}
|
||||
|
||||
const pending = computed(() => props.item.transcodeStatus === 'pending')
|
||||
const running = computed(() => props.item.transcodeStatus === 'running')
|
||||
/** 转码中源文件只是临时文件,链接还不能对外使用 */
|
||||
const transcoding = computed(() => pending.value || running.value)
|
||||
|
||||
/** 转码完成后按 HLS 播放列表展示 */
|
||||
const displayName = computed(() => {
|
||||
if (!props.item.hlsUrl) return props.item.originalName
|
||||
const dot = props.item.originalName.lastIndexOf('.')
|
||||
const base = dot > 0 ? props.item.originalName.slice(0, dot) : props.item.originalName
|
||||
return `${base}.m3u8`
|
||||
})
|
||||
|
||||
/** 该视频使用的转码档位(等待/转码中时展示) */
|
||||
const presetLabel = computed(() => {
|
||||
const [name, value] = (props.item.transcodePreset ?? '').split(':')
|
||||
switch (name) {
|
||||
case 'copy':
|
||||
return t('preferences.presetCopy')
|
||||
case 'veryfast':
|
||||
return t('preferences.presetSpeed')
|
||||
case 'medium':
|
||||
return t('preferences.presetBalanced')
|
||||
case 'slow':
|
||||
return t('preferences.presetQuality')
|
||||
case 'compress':
|
||||
return value
|
||||
? `${t('preferences.presetCompress')} ${value}%`
|
||||
: t('preferences.presetCompress')
|
||||
default:
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
function formatDuration(seconds: number): string {
|
||||
const days = Math.floor(seconds / 86_400)
|
||||
const hours = Math.floor((seconds % 86_400) / 3_600)
|
||||
const minutes = Math.floor((seconds % 3_600) / 60)
|
||||
const secs = seconds % 60
|
||||
|
||||
if (days > 0) return `${days} d ${hours} h ${minutes} min ${secs} s`
|
||||
if (hours > 0) return `${hours} h ${minutes} min ${secs} s`
|
||||
if (minutes > 0) return `${minutes} min ${secs} s`
|
||||
return `${secs} s`
|
||||
}
|
||||
|
||||
/** 转码进行中:已耗时(轮询每秒刷新一次) */
|
||||
const elapsedLabel = computed(() => {
|
||||
if (!running.value || !props.item.transcodeStartedAt) return null
|
||||
const started = new Date(props.item.transcodeStartedAt).getTime()
|
||||
if (!Number.isFinite(started)) return null
|
||||
return formatDuration(Math.max(0, Math.floor((Date.now() - started) / 1000)))
|
||||
})
|
||||
|
||||
/** 转码结束(成功或失败):固定显示总耗时 */
|
||||
const totalLabel = computed(() => {
|
||||
if (running.value || typeof props.item.transcodeDurationMs !== 'number') return null
|
||||
return formatDuration(Math.floor(props.item.transcodeDurationMs / 1000))
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col overflow-hidden rounded-xl border border-default bg-elevated shadow-sm">
|
||||
<div class="relative aspect-video shrink-0 overflow-hidden bg-muted">
|
||||
<VideoThumbnail
|
||||
v-if="kind === 'video'"
|
||||
:src="thumbLink"
|
||||
:alt="item.originalName"
|
||||
/>
|
||||
<div
|
||||
v-else
|
||||
class="flex size-full items-center justify-center"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-file"
|
||||
class="size-10 text-dimmed"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="absolute top-2 right-2">
|
||||
<UButton
|
||||
icon="i-lucide-trash-2"
|
||||
variant="solid"
|
||||
color="neutral"
|
||||
size="xs"
|
||||
class="bg-black/55 text-white hover:bg-black/70"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="emit('delete')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 flex-col gap-2 p-3">
|
||||
<p
|
||||
class="truncate text-sm font-medium"
|
||||
:title="displayName"
|
||||
>
|
||||
{{ displayName }}
|
||||
</p>
|
||||
|
||||
<p class="flex items-center gap-2 text-xs text-muted">
|
||||
<span class="truncate">{{ uploadedLabel }} · {{ formatFileSize(item.size) }}</span>
|
||||
<UBadge
|
||||
v-if="pending"
|
||||
color="neutral"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ t('library.transcodePending') }}
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-else-if="running"
|
||||
color="primary"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="shrink-0"
|
||||
>
|
||||
{{ t('library.transcoding') }} {{ item.transcodeProgress ?? 0 }}%
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-else-if="item.transcodeStatus === 'failed'"
|
||||
color="error"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="max-w-48 shrink-0 truncate"
|
||||
:title="transcodeFailureLabel(item.transcodeError)"
|
||||
>
|
||||
{{ transcodeFailureLabel(item.transcodeError) }}
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-else-if="item.hlsUrl"
|
||||
color="success"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="shrink-0"
|
||||
>
|
||||
m3u8
|
||||
</UBadge>
|
||||
</p>
|
||||
|
||||
<TagBadgeList
|
||||
:tags="item.tags"
|
||||
compact
|
||||
/>
|
||||
|
||||
<UProgress
|
||||
v-if="running"
|
||||
:model-value="item.transcodeProgress ?? 0"
|
||||
size="xs"
|
||||
color="primary"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="!transcoding"
|
||||
class="flex gap-1 rounded-lg border border-default p-0.5"
|
||||
>
|
||||
<UButton
|
||||
v-for="option in copyFormatItems"
|
||||
:key="option.value"
|
||||
size="xs"
|
||||
class="flex-1 justify-center"
|
||||
:variant="copyFormat === option.value ? 'solid' : 'ghost'"
|
||||
:color="copyFormat === option.value ? 'primary' : 'neutral'"
|
||||
:label="option.label"
|
||||
@click="selectCopyFormat(option.value)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!transcoding"
|
||||
class="flex items-center gap-1"
|
||||
>
|
||||
<UInput
|
||||
:model-value="previewValue"
|
||||
readonly
|
||||
size="xs"
|
||||
class="min-w-0 flex-1 font-mono text-xs"
|
||||
/>
|
||||
<CopyButton
|
||||
:label="t('common.copy')"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
:value="previewValue"
|
||||
:success-title="copySuccessTitle"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p
|
||||
class="flex flex-wrap items-center gap-1.5"
|
||||
>
|
||||
<UBadge
|
||||
v-if="presetLabel"
|
||||
color="primary"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ presetLabel }}
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-if="elapsedLabel"
|
||||
color="success"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="!text-white"
|
||||
>
|
||||
{{ t('library.transcodeElapsed') }} {{ elapsedLabel }}
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-if="totalLabel"
|
||||
color="success"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ t('library.transcodeTotal') }} {{ totalLabel }}
|
||||
</UBadge>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,176 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem } from '~/types/file'
|
||||
|
||||
const props = defineProps<{
|
||||
/** 视频床或文件床的上传页 */
|
||||
kind: 'video' | 'file'
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
const {
|
||||
policy: uploadPolicy,
|
||||
load: loadUploadPolicy
|
||||
} = useUploadPolicy()
|
||||
const {
|
||||
uploading,
|
||||
progressItems,
|
||||
sessionItems,
|
||||
linkUrl,
|
||||
thumbLink,
|
||||
loadActiveTranscodes,
|
||||
uploadFiles
|
||||
} = useMediaUpload(props.kind)
|
||||
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
|
||||
const { recordRecent } = useRecentTags()
|
||||
const batchTagOpen = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
void Promise.all([
|
||||
loadActiveTranscodes(),
|
||||
loadUploadPolicy().catch(() => {}),
|
||||
fetchTags()
|
||||
])
|
||||
})
|
||||
|
||||
const text = computed(() => {
|
||||
const allowedVideos = uploadPolicy.value?.allowedVideoExtensions ?? []
|
||||
const forbiddenFiles = uploadPolicy.value?.forbiddenFileExtensions ?? []
|
||||
const videoMaxFileSizeMb = uploadPolicy.value?.videoMaxFileSizeMb ?? 500
|
||||
const fileMaxFileSizeMb = uploadPolicy.value?.fileMaxFileSizeMb ?? 100
|
||||
return props.kind === 'video'
|
||||
? {
|
||||
uploadTitle: t('library.video.uploadTitle'),
|
||||
uploadHint: t('library.video.uploadHint'),
|
||||
uploadFormats: allowedVideos.length
|
||||
? t('library.video.uploadFormatsAllowed', {
|
||||
formats: allowedVideos.map(item => item.toUpperCase()).join(' / '),
|
||||
size: videoMaxFileSizeMb
|
||||
})
|
||||
: t('library.video.uploadFormats', { size: videoMaxFileSizeMb })
|
||||
}
|
||||
: {
|
||||
uploadTitle: t('library.file.uploadTitle'),
|
||||
uploadHint: t('library.file.uploadHint'),
|
||||
uploadFormats: forbiddenFiles.length
|
||||
? t('library.file.uploadFormatsBlocked', {
|
||||
formats: forbiddenFiles.map(item => item.toUpperCase()).join(' / '),
|
||||
size: fileMaxFileSizeMb
|
||||
})
|
||||
: t('library.file.uploadFormatsUnrestricted', { size: fileMaxFileSizeMb })
|
||||
}
|
||||
})
|
||||
|
||||
const accept = computed(() => {
|
||||
if (props.kind !== 'video') return undefined
|
||||
const extensions = uploadPolicy.value?.allowedVideoExtensions ?? []
|
||||
if (!extensions.length) return undefined
|
||||
return extensions
|
||||
.map(extension => `.${extension}`)
|
||||
.join(',')
|
||||
})
|
||||
|
||||
const showProgress = computed(() =>
|
||||
uploading.value
|
||||
|| progressItems.value.some(
|
||||
item =>
|
||||
item.status === 'pending'
|
||||
|| item.status === 'uploading'
|
||||
|| item.status === 'error'
|
||||
)
|
||||
)
|
||||
|
||||
async function removeItem(item: FileItem) {
|
||||
try {
|
||||
await $fetch('/api/files', {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
query: { key: item.key }
|
||||
})
|
||||
sessionItems.value = sessionItems.value.filter(entry => entry.key !== item.key)
|
||||
toast.add({ title: t('files.deleted'), color: 'success' })
|
||||
} catch {
|
||||
toast.add({ title: t('files.deleteFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmBatchTags(tagIds: number[]) {
|
||||
const keys = sessionItems.value.map(item => item.key)
|
||||
if (!keys.length || !tagIds.length) return
|
||||
|
||||
try {
|
||||
await batchUpdateTags(keys, tagIds, 'add')
|
||||
batchTagOpen.value = false
|
||||
recordRecent(tagIds)
|
||||
await fetchTags(true)
|
||||
const addedTags = tagItems.value.filter(tag => tagIds.includes(tag.id))
|
||||
sessionItems.value = sessionItems.value.map((item) => {
|
||||
const merged = new Map((item.tags ?? []).map(tag => [tag.id, tag]))
|
||||
for (const tag of addedTags) merged.set(tag.id, tag)
|
||||
return { ...item, tags: [...merged.values()] }
|
||||
})
|
||||
toast.add({ title: t('tags.batchSuccess'), color: 'success' })
|
||||
} catch {
|
||||
toast.add({ title: t('tags.batchFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<UploadFlipCard
|
||||
:kind="kind"
|
||||
:title="text.uploadTitle"
|
||||
:hint="text.uploadHint"
|
||||
:formats="text.uploadFormats"
|
||||
:accept="accept"
|
||||
:disabled="uploading"
|
||||
@upload="uploadFiles"
|
||||
/>
|
||||
|
||||
<UploadResult
|
||||
v-if="showProgress"
|
||||
:items="progressItems"
|
||||
/>
|
||||
|
||||
<section
|
||||
v-if="sessionItems.length"
|
||||
class="space-y-4"
|
||||
>
|
||||
<div class="flex w-full items-center justify-between gap-2">
|
||||
<h2 class="text-lg font-medium">
|
||||
{{ t('upload.sessionTitle') }}
|
||||
<span class="ml-1 text-sm font-normal text-muted">({{ sessionItems.length }})</span>
|
||||
</h2>
|
||||
<UButton
|
||||
icon="i-lucide-tags"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
size="sm"
|
||||
:label="t('tags.batchTagAll')"
|
||||
@click="() => { batchTagOpen = true }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
|
||||
<MediaSessionCard
|
||||
v-for="item in sessionItems"
|
||||
:key="item.key"
|
||||
:item="item"
|
||||
:kind="kind"
|
||||
:link="linkUrl(item)"
|
||||
:thumb-link="thumbLink(item)"
|
||||
@delete="removeItem(item)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<BatchTagModal
|
||||
v-model:open="batchTagOpen"
|
||||
:tags="tagItems"
|
||||
:selected-count="sessionItems.length"
|
||||
add-only
|
||||
@confirm="confirmBatchTags"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,296 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageTag } from '~/types/image'
|
||||
import { pickRandomUnusedTagColor, tagPillStyle } from '~/utils/tag-colors'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: number[]
|
||||
tags: ImageTag[]
|
||||
disabled?: boolean
|
||||
allowCreate?: boolean
|
||||
}>(), {
|
||||
disabled: false,
|
||||
allowCreate: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: number[]]
|
||||
'created': [tag: ImageTag]
|
||||
}>()
|
||||
|
||||
const COMMON_LIMIT = 10
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
const { createTag } = useTags()
|
||||
const { recentIds, loadRecentIds } = useRecentTags()
|
||||
|
||||
const query = ref('')
|
||||
const creating = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
loadRecentIds()
|
||||
})
|
||||
|
||||
const isSearching = computed(() => query.value.trim().length > 0)
|
||||
|
||||
const selectedTags = computed(() =>
|
||||
props.tags.filter(tag => props.modelValue.includes(tag.id))
|
||||
)
|
||||
|
||||
const commonTags = computed(() =>
|
||||
[...props.tags]
|
||||
.sort((a, b) => (b.imageCount ?? 0) - (a.imageCount ?? 0))
|
||||
.slice(0, COMMON_LIMIT)
|
||||
)
|
||||
|
||||
const recentTags = computed(() =>
|
||||
recentIds.value
|
||||
.map(id => props.tags.find(tag => tag.id === id))
|
||||
.filter((tag): tag is ImageTag => Boolean(tag))
|
||||
)
|
||||
|
||||
const existingTags = computed(() => {
|
||||
const q = query.value.trim().toLowerCase()
|
||||
if (!q) return props.tags
|
||||
return props.tags.filter(tag => tag.name.toLowerCase().includes(q))
|
||||
})
|
||||
|
||||
const showCreateOption = computed(() => {
|
||||
if (!props.allowCreate) return false
|
||||
const q = query.value.trim()
|
||||
if (!q) return false
|
||||
return !props.tags.some(tag => tag.name === q)
|
||||
})
|
||||
|
||||
const allExistingSelected = computed(() =>
|
||||
existingTags.value.length > 0
|
||||
&& existingTags.value.every(tag => props.modelValue.includes(tag.id))
|
||||
)
|
||||
|
||||
function isSelected(tagId: number) {
|
||||
return props.modelValue.includes(tagId)
|
||||
}
|
||||
|
||||
function toggleTag(tagId: number) {
|
||||
if (props.disabled) return
|
||||
const next = new Set(props.modelValue)
|
||||
if (next.has(tagId)) next.delete(tagId)
|
||||
else next.add(tagId)
|
||||
emit('update:modelValue', [...next])
|
||||
}
|
||||
|
||||
function removeTag(tagId: number) {
|
||||
if (props.disabled) return
|
||||
emit('update:modelValue', props.modelValue.filter(id => id !== tagId))
|
||||
}
|
||||
|
||||
function clearSelected() {
|
||||
if (props.disabled) return
|
||||
emit('update:modelValue', [])
|
||||
}
|
||||
|
||||
function toggleSelectAllExisting() {
|
||||
if (props.disabled) return
|
||||
const visibleIds = existingTags.value.map(tag => tag.id)
|
||||
if (allExistingSelected.value) {
|
||||
emit('update:modelValue', props.modelValue.filter(id => !visibleIds.includes(id)))
|
||||
return
|
||||
}
|
||||
emit('update:modelValue', [...new Set([...props.modelValue, ...visibleIds])])
|
||||
}
|
||||
|
||||
async function createFromQuery() {
|
||||
const name = query.value.trim()
|
||||
if (!name || creating.value) return
|
||||
|
||||
creating.value = true
|
||||
try {
|
||||
const color = pickRandomUnusedTagColor(props.tags.map(tag => tag.color))
|
||||
const tag = await createTag(name, color)
|
||||
emit('created', tag)
|
||||
emit('update:modelValue', [...new Set([...props.modelValue, tag.id])])
|
||||
query.value = ''
|
||||
toast.add({ title: t('tags.created', { name: tag.name }), color: 'success' })
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : t('tags.createFailed')
|
||||
toast.add({ title: message, color: 'error' })
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
defineExpose({ reloadRecent: loadRecentIds })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-4">
|
||||
<UInput
|
||||
v-model="query"
|
||||
size="md"
|
||||
icon="i-lucide-search"
|
||||
:placeholder="t('tags.searchOrCreate')"
|
||||
:disabled="disabled"
|
||||
@keydown.enter.prevent="showCreateOption ? createFromQuery() : undefined"
|
||||
/>
|
||||
|
||||
<button
|
||||
v-if="showCreateOption"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-1.5 rounded-lg px-1 py-1 text-left text-sm text-primary hover:bg-primary/5"
|
||||
:disabled="disabled || creating"
|
||||
@click="createFromQuery"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-plus"
|
||||
class="size-4 shrink-0"
|
||||
/>
|
||||
{{ t('tags.createNamed', { name: query.trim() }) }}
|
||||
</button>
|
||||
|
||||
<div
|
||||
v-if="isSearching && existingTags.length"
|
||||
class="space-y-2"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('tags.existingLabel', { n: existingTags.length }) }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-muted transition-colors hover:text-highlighted"
|
||||
:disabled="disabled"
|
||||
@click="toggleSelectAllExisting"
|
||||
>
|
||||
{{ allExistingSelected ? t('tags.deselectAll') : t('tags.selectAll') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-3 gap-2">
|
||||
<button
|
||||
v-for="tag in existingTags"
|
||||
:key="`existing-${tag.id}`"
|
||||
type="button"
|
||||
class="inline-flex min-w-0 items-center justify-center gap-1 rounded-full border px-2.5 py-1.5 text-xs font-medium transition-opacity hover:opacity-90"
|
||||
:style="tagPillStyle(tag.color, isSelected(tag.id))"
|
||||
:disabled="disabled"
|
||||
@click="toggleTag(tag.id)"
|
||||
>
|
||||
<UIcon
|
||||
v-if="isSelected(tag.id)"
|
||||
name="i-lucide-check"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ tag.name }}</span>
|
||||
<UIcon
|
||||
v-if="isSelected(tag.id)"
|
||||
name="i-lucide-x"
|
||||
class="size-3 shrink-0 opacity-80"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-else>
|
||||
<div
|
||||
v-if="selectedTags.length"
|
||||
class="space-y-2"
|
||||
>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('tags.selectedLabel', { n: selectedTags.length }) }}
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
class="text-xs text-muted transition-colors hover:text-highlighted"
|
||||
:disabled="disabled"
|
||||
@click="clearSelected"
|
||||
>
|
||||
{{ t('tags.clearSelected') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="tag in selectedTags"
|
||||
:key="tag.id"
|
||||
type="button"
|
||||
class="inline-flex max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-opacity hover:opacity-90"
|
||||
:style="tagPillStyle(tag.color, true)"
|
||||
:disabled="disabled"
|
||||
@click="removeTag(tag.id)"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-check"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ tag.name }}</span>
|
||||
<UIcon
|
||||
name="i-lucide-x"
|
||||
class="size-3 shrink-0 opacity-80"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="commonTags.length"
|
||||
class="space-y-2"
|
||||
>
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('tags.commonTags') }}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="tag in commonTags"
|
||||
:key="tag.id"
|
||||
type="button"
|
||||
class="inline-flex max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-opacity hover:opacity-90"
|
||||
:style="tagPillStyle(tag.color, isSelected(tag.id))"
|
||||
:disabled="disabled"
|
||||
@click="toggleTag(tag.id)"
|
||||
>
|
||||
<UIcon
|
||||
v-if="isSelected(tag.id)"
|
||||
name="i-lucide-check"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ tag.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="recentTags.length"
|
||||
class="space-y-2"
|
||||
>
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('tags.recentTags') }}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<button
|
||||
v-for="tag in recentTags"
|
||||
:key="`recent-${tag.id}`"
|
||||
type="button"
|
||||
class="inline-flex max-w-full items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-opacity hover:opacity-90"
|
||||
:style="tagPillStyle(tag.color, isSelected(tag.id))"
|
||||
:disabled="disabled"
|
||||
@click="toggleTag(tag.id)"
|
||||
>
|
||||
<UIcon
|
||||
v-if="isSelected(tag.id)"
|
||||
name="i-lucide-check"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ tag.name }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<p
|
||||
v-if="!tags.length && !showCreateOption"
|
||||
class="py-6 text-center text-sm text-muted"
|
||||
>
|
||||
{{ t('tags.emptyHint') }}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageTag } from '~/types/image'
|
||||
import { defaultTagColor, resolveTagHexColor, tagPillStyle } from '~/utils/tag-colors'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
tag: ImageTag
|
||||
removable?: boolean
|
||||
clickable?: boolean
|
||||
size?: 'xs' | 'sm'
|
||||
}>(), {
|
||||
removable: false,
|
||||
clickable: false,
|
||||
size: 'xs'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
remove: []
|
||||
click: []
|
||||
}>()
|
||||
|
||||
const displayColor = computed(() =>
|
||||
resolveTagHexColor(props.tag.color, defaultTagColor(props.tag.id))
|
||||
)
|
||||
|
||||
const pillStyle = computed(() => tagPillStyle(displayColor.value))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span
|
||||
class="inline-flex max-w-full items-center gap-1 rounded-md border px-2 py-0.5 font-medium"
|
||||
:class="[
|
||||
size === 'sm' ? 'text-sm' : 'text-xs',
|
||||
clickable ? 'cursor-pointer hover:opacity-90' : ''
|
||||
]"
|
||||
:style="pillStyle"
|
||||
:role="clickable ? 'button' : undefined"
|
||||
:tabindex="clickable ? 0 : undefined"
|
||||
@click="clickable ? emit('click') : undefined"
|
||||
@keydown.enter.prevent="clickable ? emit('click') : undefined"
|
||||
@keydown.space.prevent="clickable ? emit('click') : undefined"
|
||||
>
|
||||
<span
|
||||
class="size-1.5 shrink-0 rounded-full"
|
||||
:style="{ backgroundColor: displayColor }"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span class="truncate">{{ tag.name }}</span>
|
||||
<button
|
||||
v-if="removable"
|
||||
type="button"
|
||||
class="inline-flex shrink-0 rounded p-0.5 opacity-70 hover:opacity-100"
|
||||
:aria-label="`Remove ${tag.name}`"
|
||||
@click.stop="emit('remove')"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-x"
|
||||
class="size-3"
|
||||
/>
|
||||
</button>
|
||||
</span>
|
||||
</template>
|
||||
@@ -0,0 +1,70 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageTag } from '~/types/image'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
tags?: ImageTag[]
|
||||
max?: number
|
||||
compact?: boolean
|
||||
emptyLabel?: string
|
||||
}>(), {
|
||||
tags: () => [],
|
||||
max: 3,
|
||||
compact: false,
|
||||
emptyLabel: ''
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'tag-click': [tagId: number]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const visibleTags = computed(() => props.tags.slice(0, props.max))
|
||||
const hiddenTags = computed(() => props.tags.slice(props.max))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="tags.length"
|
||||
class="flex flex-wrap items-center"
|
||||
:class="compact ? 'gap-1' : 'gap-1.5'"
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in visibleTags"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
@click="emit('tag-click', tag.id)"
|
||||
/>
|
||||
<UPopover
|
||||
v-if="hiddenTags.length"
|
||||
:content="{ side: 'bottom', align: 'start' }"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex rounded-md border border-default text-muted transition-colors hover:border-primary/40 hover:text-primary"
|
||||
:class="compact ? 'px-1.5 py-0.5 text-[11px]' : 'px-2 py-0.5 text-xs'"
|
||||
:aria-label="t('tags.moreTags', { n: hiddenTags.length })"
|
||||
>
|
||||
+{{ hiddenTags.length }}
|
||||
</button>
|
||||
<template #content>
|
||||
<div
|
||||
class="flex max-w-56 flex-wrap gap-1.5 p-2"
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in hiddenTags"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
@click="emit('tag-click', tag.id)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UPopover>
|
||||
</div>
|
||||
<span
|
||||
v-else-if="emptyLabel"
|
||||
class="text-muted"
|
||||
>
|
||||
{{ emptyLabel }}
|
||||
</span>
|
||||
</template>
|
||||
@@ -0,0 +1,127 @@
|
||||
<script setup lang="ts">
|
||||
import { TAG_COLOR_PRESETS, visibleTagColorPresets } from '~/utils/tag-colors'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: string
|
||||
/** 已被其他标签占用的预设色,选择器中优先展示未占用颜色 */
|
||||
usedColors?: (string | null | undefined)[]
|
||||
/** 固定展示的备选色(新增 8 个 / 编辑 3 个) */
|
||||
candidates?: string[]
|
||||
/** 紧凑模式:不显示标题 */
|
||||
compact?: boolean
|
||||
}>(), {
|
||||
compact: false
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: string]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const colorInput = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const normalizedValue = computed(() => normalizeHex(props.modelValue))
|
||||
|
||||
const presetColors = computed(() => {
|
||||
if (props.candidates?.length) {
|
||||
const seen = new Set<string>()
|
||||
const items: string[] = []
|
||||
for (const color of props.candidates) {
|
||||
const lower = color.toLowerCase()
|
||||
if (!seen.has(lower)) {
|
||||
seen.add(lower)
|
||||
items.push(lower)
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
if (!props.usedColors?.length) return TAG_COLOR_PRESETS
|
||||
return visibleTagColorPresets(props.usedColors, props.modelValue)
|
||||
})
|
||||
|
||||
const isPreset = computed(() =>
|
||||
TAG_COLOR_PRESETS.some(color => color.toLowerCase() === normalizedValue.value.toLowerCase())
|
||||
)
|
||||
|
||||
const isCustomSelected = computed(() => {
|
||||
if (props.candidates?.length) {
|
||||
return !presetColors.value.includes(normalizedValue.value)
|
||||
}
|
||||
return !isPreset.value
|
||||
})
|
||||
|
||||
function normalizeHex(value: string) {
|
||||
const trimmed = value.trim()
|
||||
if (/^#[0-9A-Fa-f]{6}$/.test(trimmed)) return trimmed.toLowerCase()
|
||||
return '#22c55e'
|
||||
}
|
||||
|
||||
function selectColor(color: string) {
|
||||
emit('update:modelValue', color.toLowerCase())
|
||||
}
|
||||
|
||||
function onNativeColorInput(event: Event) {
|
||||
const value = (event.target as HTMLInputElement).value
|
||||
if (value) emit('update:modelValue', value.toLowerCase())
|
||||
}
|
||||
|
||||
function openNativePicker() {
|
||||
colorInput.value?.click()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="compact ? '' : 'space-y-2'">
|
||||
<p
|
||||
v-if="!compact"
|
||||
class="text-xs font-medium text-muted"
|
||||
>
|
||||
{{ t('tags.pickColor') }}
|
||||
</p>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<button
|
||||
v-for="color in presetColors"
|
||||
:key="color"
|
||||
type="button"
|
||||
class="size-7 shrink-0 rounded-full border-2 transition-all hover:scale-110"
|
||||
:class="normalizedValue === color
|
||||
? 'border-highlighted ring-2 ring-primary/25 scale-110'
|
||||
: 'border-transparent'"
|
||||
:style="{ backgroundColor: color }"
|
||||
:aria-label="color"
|
||||
:title="color"
|
||||
@click="selectColor(color)"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="relative size-7 shrink-0 overflow-hidden rounded-full border-2 transition-all hover:scale-110"
|
||||
:class="isCustomSelected
|
||||
? 'border-highlighted ring-2 ring-primary/25 scale-110'
|
||||
: 'border-dashed border-default'"
|
||||
:style="isCustomSelected ? { backgroundColor: normalizedValue } : undefined"
|
||||
:aria-label="t('tags.customColor')"
|
||||
:title="t('tags.customColor')"
|
||||
@click="openNativePicker"
|
||||
>
|
||||
<span
|
||||
v-if="!isCustomSelected"
|
||||
class="flex size-full items-center justify-center bg-muted/40"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-pipette"
|
||||
class="size-3.5 text-muted"
|
||||
/>
|
||||
</span>
|
||||
<input
|
||||
ref="colorInput"
|
||||
type="color"
|
||||
class="pointer-events-none absolute inset-0 size-full opacity-0"
|
||||
:value="normalizedValue"
|
||||
@input="onNativeColorInput"
|
||||
>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,158 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageTag } from '~/types/image'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: number[]
|
||||
tagMode: 'or' | 'and'
|
||||
untaggedOnly: boolean
|
||||
tags: ImageTag[]
|
||||
disabled?: boolean
|
||||
}>(), {
|
||||
disabled: false
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: number[]]
|
||||
'update:tagMode': [value: 'or' | 'and']
|
||||
'update:untaggedOnly': [value: boolean]
|
||||
'manage': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const selectedTags = computed(() =>
|
||||
props.tags.filter(tag => props.modelValue.includes(tag.id))
|
||||
)
|
||||
|
||||
const buttonLabel = computed(() => {
|
||||
if (props.untaggedOnly) return t('tags.untagged')
|
||||
if (!selectedTags.value.length) return t('tags.filterAll')
|
||||
if (selectedTags.value.length === 1) return selectedTags.value[0]!.name
|
||||
return t('tags.filterSelected', { n: selectedTags.value.length })
|
||||
})
|
||||
|
||||
const tagItems = computed(() =>
|
||||
props.tags.map(tag => ({
|
||||
label: tag.name,
|
||||
value: tag.id
|
||||
}))
|
||||
)
|
||||
|
||||
const selectValue = computed({
|
||||
get: () => (props.untaggedOnly ? [] : props.modelValue),
|
||||
set: (value: number[]) => {
|
||||
emit('update:untaggedOnly', false)
|
||||
emit('update:modelValue', value)
|
||||
}
|
||||
})
|
||||
|
||||
function findTag(tagId: number) {
|
||||
return props.tags.find(tag => tag.id === tagId)
|
||||
}
|
||||
|
||||
function selectUntagged() {
|
||||
emit('update:modelValue', [])
|
||||
emit('update:untaggedOnly', true)
|
||||
}
|
||||
|
||||
function clearFilter() {
|
||||
emit('update:modelValue', [])
|
||||
emit('update:untaggedOnly', false)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<USelect
|
||||
v-model="selectValue"
|
||||
multiple
|
||||
:items="tagItems"
|
||||
class="w-28 shrink-0"
|
||||
size="sm"
|
||||
:disabled="disabled"
|
||||
value-key="value"
|
||||
:content="{ align: 'start', sideOffset: 4 }"
|
||||
:ui="{
|
||||
content: 'w-72 max-w-[calc(100vw-2rem)]',
|
||||
viewport: 'max-h-44 overflow-y-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden',
|
||||
item: 'text-xs',
|
||||
itemLabel: 'text-xs',
|
||||
itemTrailingIcon: 'size-3.5 text-primary',
|
||||
placeholder: 'truncate pointer-events-none text-highlighted',
|
||||
value: 'truncate pointer-events-none text-highlighted'
|
||||
}"
|
||||
>
|
||||
<template #default>
|
||||
{{ buttonLabel }}
|
||||
</template>
|
||||
|
||||
<template #content-top>
|
||||
<div class="space-y-1.5 border-b border-default p-2 text-xs">
|
||||
<div class="flex items-center justify-between gap-2 px-0.5">
|
||||
<span class="font-medium text-highlighted">{{ t('tags.filterTitle') }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="text-primary hover:underline"
|
||||
@click="emit('manage')"
|
||||
>
|
||||
{{ t('tags.manage') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="modelValue.length > 1"
|
||||
class="flex gap-1 rounded-md border border-default p-0.5"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 rounded px-2 py-1 text-center transition-colors"
|
||||
:class="tagMode === 'or' ? 'bg-primary text-white' : 'text-muted hover:bg-elevated'"
|
||||
@click="emit('update:tagMode', 'or')"
|
||||
>
|
||||
{{ t('tags.modeOr') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 rounded px-2 py-1 text-center transition-colors"
|
||||
:class="tagMode === 'and' ? 'bg-primary text-white' : 'text-muted hover:bg-elevated'"
|
||||
@click="emit('update:tagMode', 'and')"
|
||||
>
|
||||
{{ t('tags.modeAnd') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="space-y-0.5">
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center rounded-md px-2 py-1 text-left hover:bg-elevated"
|
||||
:class="!untaggedOnly && !modelValue.length ? 'bg-primary/10 text-primary' : ''"
|
||||
@click="clearFilter"
|
||||
>
|
||||
{{ t('tags.filterAll') }}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full items-center rounded-md px-2 py-1 text-left hover:bg-elevated"
|
||||
:class="untaggedOnly ? 'bg-primary/10 text-primary' : ''"
|
||||
@click="selectUntagged"
|
||||
>
|
||||
{{ t('tags.untagged') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #item-leading="{ item }">
|
||||
<span
|
||||
class="size-2 shrink-0 rounded-full"
|
||||
:style="{ backgroundColor: findTag(item.value)?.color }"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #item-trailing="{ item }">
|
||||
<span class="text-[11px] tabular-nums text-muted">
|
||||
{{ findTag(item.value)?.imageCount ?? 0 }}
|
||||
</span>
|
||||
</template>
|
||||
</USelect>
|
||||
</template>
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageTag } from '~/types/image'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
tags: ImageTag[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'changed': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const { fetchTags } = useTags()
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) void fetchTags(true)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UModal
|
||||
:open="open"
|
||||
:title="t('tags.manageTitle')"
|
||||
:description="t('tags.manageSubtitle')"
|
||||
:ui="{ content: 'max-w-5xl' }"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<template #body>
|
||||
<TagManagePanel
|
||||
:tags="tags"
|
||||
@changed="emit('changed')"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex w-full justify-end">
|
||||
<UButton
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
@click="emit('update:open', false)"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
</UButton>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,233 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageTag } from '~/types/image'
|
||||
import { pickRandomUnusedTagColor } from '~/utils/tag-colors'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
modelValue: number[]
|
||||
tags: ImageTag[]
|
||||
disabled?: boolean
|
||||
placeholder?: string
|
||||
allowCreate?: boolean
|
||||
/** 在 Modal 内使用内联列表,避免 Popover 被遮罩挡住 */
|
||||
inline?: boolean
|
||||
/** 内联列表使用复选框样式 */
|
||||
checkbox?: boolean
|
||||
/** 隐藏已选标签徽章(弹窗内用复选框列表即可) */
|
||||
hideSelectedChips?: boolean
|
||||
}>(), {
|
||||
disabled: false,
|
||||
allowCreate: true,
|
||||
inline: false,
|
||||
checkbox: false,
|
||||
hideSelectedChips: false
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [value: number[]]
|
||||
'created': [tag: ImageTag]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
const { createTag } = useTags()
|
||||
|
||||
const open = ref(false)
|
||||
const query = ref('')
|
||||
const creating = ref(false)
|
||||
|
||||
const selectedTags = computed(() =>
|
||||
props.tags.filter(tag => props.modelValue.includes(tag.id))
|
||||
)
|
||||
|
||||
const filteredTags = computed(() => {
|
||||
const q = query.value.trim().toLowerCase()
|
||||
if (!q) return props.tags
|
||||
return props.tags.filter(tag => tag.name.toLowerCase().includes(q))
|
||||
})
|
||||
|
||||
const showCreateOption = computed(() => {
|
||||
if (!props.allowCreate) return false
|
||||
const q = query.value.trim()
|
||||
if (!q) return false
|
||||
return !props.tags.some(tag => tag.name === q)
|
||||
})
|
||||
|
||||
function toggleTag(tagId: number) {
|
||||
const next = new Set(props.modelValue)
|
||||
if (next.has(tagId)) {
|
||||
next.delete(tagId)
|
||||
} else {
|
||||
next.add(tagId)
|
||||
}
|
||||
emit('update:modelValue', [...next])
|
||||
}
|
||||
|
||||
function removeTag(tagId: number) {
|
||||
emit('update:modelValue', props.modelValue.filter(id => id !== tagId))
|
||||
}
|
||||
|
||||
async function createFromQuery() {
|
||||
const name = query.value.trim()
|
||||
if (!name || creating.value) return
|
||||
|
||||
creating.value = true
|
||||
try {
|
||||
const color = pickRandomUnusedTagColor(props.tags.map(tag => tag.color))
|
||||
const tag = await createTag(name, color)
|
||||
emit('created', tag)
|
||||
emit('update:modelValue', [...new Set([...props.modelValue, tag.id])])
|
||||
query.value = ''
|
||||
toast.add({ title: t('tags.created', { name: tag.name }), color: 'success' })
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : t('tags.createFailed')
|
||||
toast.add({ title: message, color: 'error' })
|
||||
} finally {
|
||||
creating.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-2">
|
||||
<div
|
||||
v-if="selectedTags.length && !hideSelectedChips"
|
||||
class="flex flex-wrap gap-1.5"
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in selectedTags"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
removable
|
||||
@remove="removeTag(tag.id)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="inline"
|
||||
class="space-y-2 rounded-lg border border-default p-2"
|
||||
>
|
||||
<UInput
|
||||
v-model="query"
|
||||
size="sm"
|
||||
icon="i-lucide-search"
|
||||
:placeholder="checkbox ? t('tags.search') : t('tags.searchOrCreate')"
|
||||
:disabled="disabled"
|
||||
@keydown.enter.prevent="showCreateOption ? createFromQuery() : undefined"
|
||||
/>
|
||||
|
||||
<div class="max-h-48 space-y-1 overflow-y-auto">
|
||||
<button
|
||||
v-for="tag in filteredTags"
|
||||
:key="tag.id"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-elevated"
|
||||
:class="modelValue.includes(tag.id) ? 'bg-primary/10' : ''"
|
||||
@click="toggleTag(tag.id)"
|
||||
>
|
||||
<UCheckbox
|
||||
v-if="checkbox"
|
||||
:model-value="modelValue.includes(tag.id)"
|
||||
class="pointer-events-none"
|
||||
@click.stop
|
||||
/>
|
||||
<span
|
||||
class="size-2 shrink-0 rounded-full"
|
||||
:style="{ backgroundColor: tag.color }"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">{{ tag.name }}</span>
|
||||
<UIcon
|
||||
v-if="!checkbox && modelValue.includes(tag.id)"
|
||||
name="i-lucide-check"
|
||||
class="size-4 text-primary"
|
||||
/>
|
||||
</button>
|
||||
|
||||
<p
|
||||
v-if="!filteredTags.length && !showCreateOption"
|
||||
class="px-2 py-3 text-center text-xs text-muted"
|
||||
>
|
||||
{{ tags.length ? t('tags.noMatch') : t('tags.emptyHint') }}
|
||||
</p>
|
||||
|
||||
<button
|
||||
v-if="showCreateOption"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-primary hover:bg-elevated"
|
||||
:disabled="creating"
|
||||
@click="createFromQuery"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-plus"
|
||||
class="size-4"
|
||||
/>
|
||||
{{ t('tags.createNamed', { name: query.trim() }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UPopover
|
||||
v-else
|
||||
v-model:open="open"
|
||||
>
|
||||
<UButton
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
icon="i-lucide-plus"
|
||||
:disabled="disabled"
|
||||
>
|
||||
{{ placeholder ?? t('tags.addTag') }}
|
||||
</UButton>
|
||||
|
||||
<template #content>
|
||||
<div class="w-64 space-y-2 p-2">
|
||||
<UInput
|
||||
v-model="query"
|
||||
size="sm"
|
||||
icon="i-lucide-search"
|
||||
:placeholder="checkbox ? t('tags.search') : t('tags.searchOrCreate')"
|
||||
:disabled="disabled"
|
||||
@keydown.enter.prevent="showCreateOption ? createFromQuery() : undefined"
|
||||
/>
|
||||
|
||||
<div class="max-h-48 space-y-1 overflow-y-auto">
|
||||
<button
|
||||
v-for="tag in filteredTags"
|
||||
:key="tag.id"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-elevated"
|
||||
:class="modelValue.includes(tag.id) ? 'bg-primary/10' : ''"
|
||||
@click="toggleTag(tag.id)"
|
||||
>
|
||||
<span
|
||||
class="size-2 shrink-0 rounded-full"
|
||||
:style="{ backgroundColor: tag.color }"
|
||||
/>
|
||||
<span class="min-w-0 flex-1 truncate">{{ tag.name }}</span>
|
||||
<UIcon
|
||||
v-if="modelValue.includes(tag.id)"
|
||||
name="i-lucide-check"
|
||||
class="size-4 text-primary"
|
||||
/>
|
||||
</button>
|
||||
|
||||
<button
|
||||
v-if="showCreateOption"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm text-primary hover:bg-elevated"
|
||||
:disabled="creating"
|
||||
@click="createFromQuery"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-plus"
|
||||
class="size-4"
|
||||
/>
|
||||
{{ t('tags.createNamed', { name: query.trim() }) }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</UPopover>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,106 @@
|
||||
<script setup lang="ts">
|
||||
const { t } = useI18n()
|
||||
const { isAdmin } = useAuth()
|
||||
const {
|
||||
concurrency,
|
||||
threads,
|
||||
maxConcurrency,
|
||||
maxThreads,
|
||||
preset,
|
||||
bitratePercent,
|
||||
minBitratePercent,
|
||||
maxBitratePercent,
|
||||
load
|
||||
} = useTranscodeSettings()
|
||||
|
||||
const presetItems = computed(() => [
|
||||
{ value: 'copy', label: t('preferences.presetCopy') },
|
||||
{ value: 'veryfast', label: t('preferences.presetSpeed') },
|
||||
{ value: 'medium', label: t('preferences.presetBalanced') },
|
||||
{ value: 'slow', label: t('preferences.presetQuality') },
|
||||
{ value: 'compress', label: t('preferences.presetCompress') }
|
||||
])
|
||||
|
||||
function onBitrateInput(event: Event) {
|
||||
const value = Number((event.target as HTMLInputElement).value)
|
||||
bitratePercent.value = Number.isFinite(value) ? value : 80
|
||||
}
|
||||
|
||||
function selectPreset(value: string) {
|
||||
preset.value = value
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-3">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<span class="shrink-0">{{ t('preferences.transcodeConcurrency') }}</span>
|
||||
<UInput
|
||||
v-model.number="concurrency"
|
||||
type="number"
|
||||
min="1"
|
||||
:max="maxConcurrency"
|
||||
size="xs"
|
||||
class="w-16 tabular-nums"
|
||||
:disabled="!isAdmin"
|
||||
/>
|
||||
<span class="text-muted">{{ t('preferences.unitCount') }}</span>
|
||||
<span class="text-xs text-muted">{{ t('preferences.concurrentHint') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<span class="shrink-0">{{ t('preferences.transcodeThreads') }}</span>
|
||||
<UInput
|
||||
v-model.number="threads"
|
||||
type="number"
|
||||
min="1"
|
||||
:max="maxThreads"
|
||||
size="xs"
|
||||
class="w-16 tabular-nums"
|
||||
:disabled="!isAdmin"
|
||||
/>
|
||||
<span class="text-muted">{{ t('preferences.unitCount') }}</span>
|
||||
<span class="text-xs text-muted">{{ t('preferences.threadsHint') }}</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2 text-sm">
|
||||
<span class="shrink-0">{{ t('preferences.transcodeQuality') }}</span>
|
||||
<div class="flex gap-1 rounded-lg border border-default p-0.5">
|
||||
<UButton
|
||||
v-for="item in presetItems"
|
||||
:key="item.value"
|
||||
size="xs"
|
||||
class="flex-1 justify-center"
|
||||
:variant="preset === item.value ? 'solid' : 'ghost'"
|
||||
:color="preset === item.value ? 'primary' : 'neutral'"
|
||||
:label="item.label"
|
||||
:disabled="!isAdmin"
|
||||
@click="selectPreset(item.value)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="flex items-center gap-2 text-sm"
|
||||
:class="preset === 'compress' ? '' : 'opacity-40'"
|
||||
>
|
||||
<span class="shrink-0">{{ t('preferences.compressBitrate') }}</span>
|
||||
<input
|
||||
type="range"
|
||||
:min="minBitratePercent"
|
||||
:max="maxBitratePercent"
|
||||
:value="bitratePercent"
|
||||
:disabled="!isAdmin || preset !== 'compress'"
|
||||
class="h-2 min-w-24 flex-1 cursor-pointer appearance-none rounded-full bg-default accent-primary disabled:opacity-40"
|
||||
@input="onBitrateInput"
|
||||
>
|
||||
<span class="w-12 shrink-0 text-right tabular-nums text-muted">
|
||||
{{ bitratePercent }}%
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,120 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
siteKey: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
verified: [payload: { turnstileToken: string }]
|
||||
cleared: []
|
||||
}>()
|
||||
|
||||
interface TurnstileRenderOptions {
|
||||
'sitekey': string
|
||||
'action'?: string
|
||||
'callback'?: (token: string) => void
|
||||
'expired-callback'?: () => void
|
||||
'error-callback'?: () => void
|
||||
}
|
||||
|
||||
interface TurnstileApi {
|
||||
render: (container: HTMLElement, options: TurnstileRenderOptions) => string
|
||||
reset: (widgetId?: string) => void
|
||||
remove: (widgetId: string) => void
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
turnstile?: TurnstileApi
|
||||
onTurnstileLoad?: () => void
|
||||
}
|
||||
}
|
||||
|
||||
const containerRef = ref<HTMLElement | null>(null)
|
||||
const widgetId = ref<string | null>(null)
|
||||
const scriptLoaded = ref(false)
|
||||
|
||||
function onVerified(token: string) {
|
||||
if (token) {
|
||||
emit('verified', { turnstileToken: token })
|
||||
}
|
||||
}
|
||||
|
||||
function onCleared() {
|
||||
emit('cleared')
|
||||
}
|
||||
|
||||
function renderWidget() {
|
||||
if (!containerRef.value || !window.turnstile || !props.siteKey) return
|
||||
if (widgetId.value) {
|
||||
window.turnstile.remove(widgetId.value)
|
||||
widgetId.value = null
|
||||
}
|
||||
widgetId.value = window.turnstile.render(containerRef.value, {
|
||||
'sitekey': props.siteKey,
|
||||
'action': 'login',
|
||||
'callback': onVerified,
|
||||
'expired-callback': onCleared,
|
||||
'error-callback': onCleared
|
||||
})
|
||||
}
|
||||
|
||||
function tryRenderWidget() {
|
||||
if (scriptLoaded.value) {
|
||||
renderWidget()
|
||||
}
|
||||
}
|
||||
|
||||
function loadScript() {
|
||||
if (window.turnstile) {
|
||||
scriptLoaded.value = true
|
||||
tryRenderWidget()
|
||||
return
|
||||
}
|
||||
window.onTurnstileLoad = () => {
|
||||
scriptLoaded.value = true
|
||||
tryRenderWidget()
|
||||
}
|
||||
const existing = document.querySelector('script[data-turnstile]')
|
||||
if (existing) {
|
||||
if (window.turnstile) {
|
||||
scriptLoaded.value = true
|
||||
tryRenderWidget()
|
||||
}
|
||||
return
|
||||
}
|
||||
const script = document.createElement('script')
|
||||
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onTurnstileLoad'
|
||||
script.async = true
|
||||
script.defer = true
|
||||
script.dataset.turnstile = 'true'
|
||||
document.head.appendChild(script)
|
||||
}
|
||||
|
||||
function reset() {
|
||||
if (window.turnstile && widgetId.value) {
|
||||
window.turnstile.reset(widgetId.value)
|
||||
}
|
||||
onCleared()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
loadScript()
|
||||
await nextTick()
|
||||
tryRenderWidget()
|
||||
})
|
||||
|
||||
watch([containerRef, () => props.siteKey, scriptLoaded], () => {
|
||||
tryRenderWidget()
|
||||
}, { flush: 'post' })
|
||||
|
||||
defineExpose({ reset })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ClientOnly>
|
||||
<div
|
||||
ref="containerRef"
|
||||
class="flex min-h-16 items-center justify-center"
|
||||
/>
|
||||
</ClientOnly>
|
||||
</template>
|
||||
@@ -2,9 +2,24 @@
|
||||
import uploadCardBg from '~/assets/image/upload-card-bg.webp'
|
||||
import uploadCardHero from '~/assets/image/upload-card-hero.webp'
|
||||
|
||||
const props = defineProps<{
|
||||
const props = withDefaults(defineProps<{
|
||||
disabled?: boolean
|
||||
}>()
|
||||
title?: string
|
||||
hint?: string
|
||||
formats?: string
|
||||
accept?: string
|
||||
heroImage?: string
|
||||
backgroundImage?: string
|
||||
showSettings?: boolean
|
||||
pasteEnabled?: boolean
|
||||
/** 拖拽/选择时的类型限制;图片页与视频页各自限定,文件页放开 */
|
||||
mediaKind?: 'image' | 'video' | 'any'
|
||||
}>(), {
|
||||
accept: 'image/jpeg,image/png,image/webp,image/gif,image/svg+xml,image/x-icon,.svg,.ico',
|
||||
showSettings: true,
|
||||
pasteEnabled: true,
|
||||
mediaKind: 'image'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'upload': [files: File[]]
|
||||
@@ -18,9 +33,22 @@ const { t } = useI18n()
|
||||
const { bindPaste } = useClipboardImage(ref(null))
|
||||
|
||||
bindPaste((files) => {
|
||||
if (!props.disabled) emit('upload', files)
|
||||
if (props.disabled || !props.pasteEnabled) return
|
||||
emit('upload', files)
|
||||
})
|
||||
|
||||
const heroSource = computed(() => props.heroImage ?? uploadCardHero)
|
||||
const backgroundSource = computed(() => props.backgroundImage ?? uploadCardBg)
|
||||
const titleText = computed(() => props.title ?? t('upload.title'))
|
||||
const hintText = computed(() => props.hint ?? t('upload.hint', { ctrl: 'Ctrl', v: 'V' }))
|
||||
const formatsText = computed(() => props.formats ?? t('upload.formats'))
|
||||
|
||||
function matchesMediaKind(file: File): boolean {
|
||||
if (props.mediaKind === 'any') return true
|
||||
if (!file.type) return true
|
||||
return file.type.startsWith(`${props.mediaKind}/`)
|
||||
}
|
||||
|
||||
function openFilePicker() {
|
||||
if (props.disabled) return
|
||||
fileInput.value?.click()
|
||||
@@ -38,8 +66,7 @@ function onDrop(event: DragEvent) {
|
||||
dragging.value = false
|
||||
if (props.disabled) return
|
||||
|
||||
const files = Array.from(event.dataTransfer?.files ?? [])
|
||||
.filter(file => file.type.startsWith('image/'))
|
||||
const files = Array.from(event.dataTransfer?.files ?? []).filter(matchesMediaKind)
|
||||
if (files.length) emit('upload', files)
|
||||
}
|
||||
|
||||
@@ -83,7 +110,7 @@ function onKeydown(event: KeyboardEvent) {
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/webp,image/gif,image/svg+xml,image/x-icon,.svg,.ico"
|
||||
:accept="accept"
|
||||
multiple
|
||||
class="hidden"
|
||||
:disabled="disabled"
|
||||
@@ -91,7 +118,7 @@ function onKeydown(event: KeyboardEvent) {
|
||||
>
|
||||
|
||||
<img
|
||||
:src="uploadCardBg"
|
||||
:src="backgroundSource"
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
class="pointer-events-none absolute inset-0 size-full object-cover opacity-100 dark:opacity-[0.12]"
|
||||
@@ -99,7 +126,10 @@ function onKeydown(event: KeyboardEvent) {
|
||||
draggable="false"
|
||||
>
|
||||
|
||||
<div class="absolute top-3 right-3 z-20">
|
||||
<div
|
||||
v-if="showSettings"
|
||||
class="absolute top-3 right-3 z-20"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="upload-settings-btn inline-flex size-8 items-center justify-center rounded-md bg-default/70 text-muted backdrop-blur-sm transition-colors hover:bg-elevated hover:text-highlighted disabled:pointer-events-none disabled:opacity-40"
|
||||
@@ -117,7 +147,7 @@ function onKeydown(event: KeyboardEvent) {
|
||||
<div class="relative z-10 mx-auto flex max-w-lg flex-col items-center">
|
||||
<div class="flex flex-col items-center">
|
||||
<img
|
||||
:src="uploadCardHero"
|
||||
:src="heroSource"
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
class="h-24 w-auto -mb-3 select-none transition-transform duration-200 ease-[cubic-bezier(0.4,0,0.2,1)] sm:-mb-4 sm:h-28 md:h-32"
|
||||
@@ -128,16 +158,16 @@ function onKeydown(event: KeyboardEvent) {
|
||||
|
||||
<div class="space-y-2">
|
||||
<p class="text-xl font-semibold tracking-tight text-highlighted sm:text-2xl">
|
||||
{{ t('upload.title') }}
|
||||
{{ titleText }}
|
||||
</p>
|
||||
<p class="text-sm text-muted sm:text-base">
|
||||
{{ t('upload.hint', { ctrl: 'Ctrl', v: 'V' }) }}
|
||||
{{ hintText }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="mt-4 max-w-md text-xs leading-relaxed text-dimmed sm:text-sm">
|
||||
{{ t('upload.formats') }}
|
||||
{{ formatsText }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,7 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
import type { UploadMediaKind } from '~/composables/useUploadPreferences'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
disabled?: boolean
|
||||
}>()
|
||||
/** 上传页类型:决定默认可选文件类型、粘贴支持与偏好面板内容 */
|
||||
kind?: UploadMediaKind
|
||||
title?: string
|
||||
hint?: string
|
||||
formats?: string
|
||||
accept?: string
|
||||
heroImage?: string
|
||||
backgroundImage?: string
|
||||
pasteEnabled?: boolean
|
||||
}>(), {
|
||||
kind: 'image'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
upload: [files: File[]]
|
||||
@@ -9,6 +22,15 @@ const emit = defineEmits<{
|
||||
|
||||
const flipped = ref(false)
|
||||
|
||||
const mediaKind = computed(() => (props.kind === 'file' ? 'any' : props.kind))
|
||||
const pasteEnabled = computed(() => props.pasteEnabled ?? props.kind === 'image')
|
||||
const defaultAccept = computed(() => {
|
||||
if (props.kind === 'video') return 'video/*,.mp4,.webm,.mov,.mkv,.avi,.m4v'
|
||||
if (props.kind === 'file') return ''
|
||||
return undefined
|
||||
})
|
||||
const accept = computed(() => props.accept ?? defaultAccept.value)
|
||||
|
||||
function onOpenSettings() {
|
||||
flipped.value = true
|
||||
}
|
||||
@@ -21,18 +43,29 @@ function onBack() {
|
||||
<template>
|
||||
<div
|
||||
class="upload-card-flip"
|
||||
:class="{ 'is-flipped': flipped }"
|
||||
:class="[`upload-card-flip--${kind}`, { 'is-flipped': flipped }]"
|
||||
>
|
||||
<div class="upload-card-flip-inner">
|
||||
<div class="upload-card-face upload-card-face--front">
|
||||
<ImageUploader
|
||||
<UploadCard
|
||||
:disabled="disabled"
|
||||
:title="title"
|
||||
:hint="hint"
|
||||
:formats="formats"
|
||||
:accept="accept"
|
||||
:hero-image="heroImage"
|
||||
:background-image="backgroundImage"
|
||||
:media-kind="mediaKind"
|
||||
:paste-enabled="pasteEnabled"
|
||||
@upload="emit('upload', $event)"
|
||||
@open-settings="onOpenSettings"
|
||||
/>
|
||||
</div>
|
||||
<div class="upload-card-face upload-card-face--back">
|
||||
<UploadPreferencesPanel @back="onBack" />
|
||||
<UploadPreferencesPanel
|
||||
:kind="kind"
|
||||
@back="onBack"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,4 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
normalizeUploadTagNames,
|
||||
type UploadMediaKind
|
||||
} from '~/composables/useUploadPreferences'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
/** 每个上传页各自一份偏好 */
|
||||
kind?: UploadMediaKind
|
||||
}>(), {
|
||||
kind: 'image'
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
back: []
|
||||
}>()
|
||||
@@ -8,10 +20,43 @@ const {
|
||||
autoCopyMarkdown,
|
||||
copyFormat,
|
||||
clientWebpQuality,
|
||||
uploadTagNames,
|
||||
transcodeToHls,
|
||||
loadPreferences
|
||||
} = useUploadPreferences()
|
||||
} = useUploadPreferences(props.kind)
|
||||
const uploadTagDraft = ref('')
|
||||
|
||||
/** 视频床 / 文件床没有图片压缩相关选项 */
|
||||
const isImageKind = computed(() => props.kind === 'image')
|
||||
const isVideoKind = computed(() => props.kind === 'video')
|
||||
const processingGridClass = computed(() => {
|
||||
if (isImageKind.value || isVideoKind.value) return 'md:col-start-1 md:row-start-1'
|
||||
return ''
|
||||
})
|
||||
const qualityGridClass = computed(() => {
|
||||
if (isImageKind.value) return 'md:col-start-1 md:row-start-2'
|
||||
return ''
|
||||
})
|
||||
const convenienceGridClass = computed(() => {
|
||||
if (isImageKind.value) return 'md:col-start-2 md:row-start-1'
|
||||
if (isVideoKind.value) return 'md:col-start-1 md:row-start-2'
|
||||
return ''
|
||||
})
|
||||
const tagsGridClass = computed(() => {
|
||||
if (isImageKind.value) return 'md:col-start-2 md:row-start-2'
|
||||
if (isVideoKind.value) return 'md:col-start-2 md:row-start-1 md:row-span-2'
|
||||
return ''
|
||||
})
|
||||
const tagsLayoutClass = computed(() => [
|
||||
tagsGridClass.value
|
||||
])
|
||||
|
||||
const { t } = useI18n()
|
||||
const {
|
||||
lowMemory,
|
||||
memoryBytes,
|
||||
load: loadTranscodeSettings
|
||||
} = useTranscodeSettings()
|
||||
|
||||
const {
|
||||
userSettings,
|
||||
@@ -23,7 +68,8 @@ const {
|
||||
const copyFormatItems = computed(() => [
|
||||
{ label: t('copy.url'), value: 'url' as const },
|
||||
{ label: t('copy.markdown'), value: 'markdown' as const },
|
||||
{ label: t('copy.html'), value: 'html' as const }
|
||||
{ label: t('copy.html'), value: 'html' as const },
|
||||
{ label: t('copy.bbcode'), value: 'bbcode' as const }
|
||||
])
|
||||
|
||||
const clientQualityLevel = computed(() => {
|
||||
@@ -32,7 +78,13 @@ const clientQualityLevel = computed(() => {
|
||||
return t('preferences.qualityLow')
|
||||
})
|
||||
|
||||
function setCopyFormat(value: 'url' | 'markdown' | 'html') {
|
||||
const memoryGb = computed(() => (
|
||||
memoryBytes.value > 0
|
||||
? (memoryBytes.value / (1024 * 1024 * 1024)).toFixed(1)
|
||||
: '—'
|
||||
))
|
||||
|
||||
function setCopyFormat(value: 'url' | 'markdown' | 'html' | 'bbcode') {
|
||||
copyFormat.value = value
|
||||
}
|
||||
|
||||
@@ -41,9 +93,39 @@ function onClientQualityInput(event: Event) {
|
||||
clientWebpQuality.value = Number.isFinite(value) ? value : 80
|
||||
}
|
||||
|
||||
function commitUploadTags() {
|
||||
const names = normalizeUploadTagNames(uploadTagDraft.value)
|
||||
if (!names.length) return
|
||||
uploadTagNames.value = normalizeUploadTagNames([
|
||||
...uploadTagNames.value,
|
||||
...names
|
||||
])
|
||||
uploadTagDraft.value = ''
|
||||
}
|
||||
|
||||
function onUploadTagKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Enter' || event.key === ',' || event.key === ',') {
|
||||
event.preventDefault()
|
||||
commitUploadTags()
|
||||
return
|
||||
}
|
||||
if (
|
||||
event.key === 'Backspace'
|
||||
&& !uploadTagDraft.value
|
||||
&& uploadTagNames.value.length
|
||||
) {
|
||||
uploadTagNames.value = uploadTagNames.value.slice(0, -1)
|
||||
}
|
||||
}
|
||||
|
||||
function removeUploadTag(name: string) {
|
||||
uploadTagNames.value = uploadTagNames.value.filter(item => item !== name)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadPreferences()
|
||||
void loadUserSettings()
|
||||
void loadTranscodeSettings()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -76,9 +158,15 @@ onMounted(() => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 flex-col justify-center p-5 sm:p-6">
|
||||
<div class="grid gap-5 sm:grid-cols-3 sm:gap-6">
|
||||
<div class="space-y-4">
|
||||
<div class="flex flex-1 flex-col justify-start overflow-y-auto p-5 sm:p-6">
|
||||
<div
|
||||
class="grid gap-5 md:grid-cols-2 md:gap-6"
|
||||
>
|
||||
<div
|
||||
v-if="isImageKind"
|
||||
class="space-y-4 rounded-xl border border-default/70 bg-muted/10 p-4"
|
||||
:class="processingGridClass"
|
||||
>
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ t('preferences.processing') }}
|
||||
</h3>
|
||||
@@ -136,7 +224,50 @@ onMounted(() => {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
v-if="isVideoKind"
|
||||
class="space-y-4 rounded-xl border border-default/70 bg-muted/10 p-4"
|
||||
:class="processingGridClass"
|
||||
>
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ t('preferences.videoProcessing') }}
|
||||
</h3>
|
||||
|
||||
<UAlert
|
||||
v-if="lowMemory"
|
||||
color="warning"
|
||||
variant="subtle"
|
||||
icon="i-lucide-triangle-alert"
|
||||
:title="t('preferences.lowMemoryTranscodeTitle')"
|
||||
:description="t('preferences.lowMemoryTranscodeHint', { memory: memoryGb })"
|
||||
/>
|
||||
|
||||
<label class="flex cursor-pointer items-start gap-2.5">
|
||||
<UCheckbox
|
||||
v-model="transcodeToHls"
|
||||
class="mt-0.5"
|
||||
/>
|
||||
<span>
|
||||
<span class="block text-sm">{{ t('preferences.transcodeToHls') }}</span>
|
||||
<span class="mt-1 block text-xs leading-relaxed text-muted">
|
||||
{{ t('preferences.transcodeToHlsHint') }}
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<div
|
||||
v-if="transcodeToHls"
|
||||
class="ml-7 space-y-3 border-t border-default pt-4"
|
||||
>
|
||||
<TranscodeSettingsControls />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="isImageKind"
|
||||
class="space-y-4 rounded-xl border border-default/70 bg-muted/10 p-4"
|
||||
:class="qualityGridClass"
|
||||
>
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ t('preferences.webpQuality') }}
|
||||
</h3>
|
||||
@@ -157,7 +288,10 @@ onMounted(() => {
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div
|
||||
class="space-y-4 rounded-xl border border-default/70 bg-muted/10 p-4"
|
||||
:class="convenienceGridClass"
|
||||
>
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ t('preferences.convenience') }}
|
||||
</h3>
|
||||
@@ -189,6 +323,57 @@ onMounted(() => {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="space-y-3 rounded-xl border border-default/70 bg-muted/10 p-4"
|
||||
:class="tagsLayoutClass"
|
||||
>
|
||||
<div class="space-y-3">
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ t('preferences.uploadTags') }}
|
||||
</h3>
|
||||
<p class="text-xs leading-relaxed text-muted">
|
||||
{{ t('preferences.uploadTagsHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<UInput
|
||||
v-model="uploadTagDraft"
|
||||
size="md"
|
||||
icon="i-lucide-tags"
|
||||
maxlength="32"
|
||||
:placeholder="t('preferences.uploadTagsPlaceholder')"
|
||||
@keydown="onUploadTagKeydown"
|
||||
@blur="commitUploadTags"
|
||||
/>
|
||||
<div
|
||||
v-if="uploadTagNames.length"
|
||||
class="space-y-2 pt-1"
|
||||
>
|
||||
<p class="text-xs font-medium text-muted">
|
||||
{{ t('preferences.uploadTagsPending', { n: uploadTagNames.length }) }}
|
||||
</p>
|
||||
<div class="flex flex-wrap gap-2.5">
|
||||
<span
|
||||
v-for="name in uploadTagNames"
|
||||
:key="name"
|
||||
class="relative inline-flex max-w-full items-center rounded-full border border-primary/35 bg-primary/10 px-3 py-1 text-xs font-medium text-primary"
|
||||
>
|
||||
<span class="truncate">{{ name }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="absolute -top-1.5 -right-1.5 inline-flex size-4 items-center justify-center rounded-full border border-primary/40 bg-elevated text-primary shadow-sm transition-colors hover:bg-primary hover:text-inverted"
|
||||
:aria-label="t('preferences.uploadTagsRemove', { name })"
|
||||
@click="removeUploadTag(name)"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-x"
|
||||
class="size-2.5"
|
||||
/>
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem } from '~/types/file'
|
||||
|
||||
const props = defineProps<{
|
||||
item: FileItem
|
||||
/** 已按访问模式拼接好的视频直链 */
|
||||
link: string
|
||||
/** 缩略图直链 */
|
||||
thumbLink: string
|
||||
/** 原始视频下载地址 */
|
||||
downloadLink: string
|
||||
selected?: boolean
|
||||
selectable?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'play': []
|
||||
'delete': []
|
||||
'download': []
|
||||
'update:selected': [value: boolean]
|
||||
}>()
|
||||
|
||||
const { formatFileSize } = useFileSize()
|
||||
const { t, locale } = useI18n()
|
||||
const transcodeFailureLabel = useTranscodeFailureLabel()
|
||||
|
||||
/** 转码完成后按 HLS 播放列表展示 */
|
||||
const displayName = computed(() => {
|
||||
if (!props.item.hlsUrl) return props.item.originalName
|
||||
const dot = props.item.originalName.lastIndexOf('.')
|
||||
const base = dot > 0 ? props.item.originalName.slice(0, dot) : props.item.originalName
|
||||
return `${base}.m3u8`
|
||||
})
|
||||
|
||||
const uploadedLabel = computed(() => {
|
||||
try {
|
||||
return new Date(props.item.uploadedAt).toLocaleString(locale.value, { hour12: false })
|
||||
} catch {
|
||||
return props.item.uploadedAt
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col overflow-hidden rounded-xl border border-default bg-elevated">
|
||||
<div class="relative aspect-video shrink-0 overflow-hidden bg-muted">
|
||||
<VideoThumbnail
|
||||
:src="thumbLink"
|
||||
:alt="displayName"
|
||||
/>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="absolute inset-0 flex items-center justify-center transition-colors hover:bg-black/20"
|
||||
:aria-label="t('library.play')"
|
||||
@click="emit('play')"
|
||||
>
|
||||
<span class="rounded-full bg-black/55 p-3 text-white backdrop-blur-sm">
|
||||
<UIcon
|
||||
name="i-lucide-play"
|
||||
class="size-6"
|
||||
/>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div
|
||||
v-if="selectable"
|
||||
class="absolute top-2 left-2 z-10"
|
||||
@click.stop
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="selected"
|
||||
@update:model-value="emit('update:selected', $event === true)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
class="absolute top-2 right-2 z-10"
|
||||
@click.stop
|
||||
>
|
||||
<UBadge
|
||||
v-if="item.hlsUrl"
|
||||
color="success"
|
||||
variant="solid"
|
||||
size="xs"
|
||||
>
|
||||
m3u8
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-else-if="item.transcodeStatus === 'failed'"
|
||||
color="error"
|
||||
variant="solid"
|
||||
size="xs"
|
||||
class="max-w-48 truncate"
|
||||
:title="transcodeFailureLabel(item.transcodeError)"
|
||||
>
|
||||
{{ transcodeFailureLabel(item.transcodeError) }}
|
||||
</UBadge>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-1 flex-col gap-1.5 p-3">
|
||||
<p
|
||||
class="truncate text-sm font-semibold"
|
||||
:title="displayName"
|
||||
>
|
||||
{{ displayName }}
|
||||
</p>
|
||||
<p class="truncate text-xs text-muted">
|
||||
{{ uploadedLabel }} · {{ formatFileSize(item.size) }}
|
||||
</p>
|
||||
<TagBadgeList :tags="item.tags" />
|
||||
</div>
|
||||
|
||||
<div class="flex items-center justify-around border-t border-default px-2 py-2">
|
||||
<CopyButton
|
||||
icon="i-lucide-link"
|
||||
icon-only
|
||||
:label="t('library.copyVideoLink')"
|
||||
:value="link"
|
||||
:success-title="t('copy.copiedUrl')"
|
||||
/>
|
||||
<CopyButton
|
||||
icon="i-lucide-image"
|
||||
icon-only
|
||||
:label="t('library.copyThumbLink')"
|
||||
:value="thumbLink"
|
||||
:success-title="t('copy.copiedUrl')"
|
||||
/>
|
||||
<UButton
|
||||
v-if="!item.sourceDeleted"
|
||||
icon="i-lucide-download"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
:to="downloadLink"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
:aria-label="t('files.download')"
|
||||
/>
|
||||
<UButton
|
||||
v-else-if="item.hlsUrl"
|
||||
icon="i-lucide-download"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
:aria-label="t('library.video.downloadMp4')"
|
||||
@click="emit('download')"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-trash-2"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="emit('delete')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,785 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem, FileListResponse } from '~/types/file'
|
||||
import type { LibraryStatsData } from '~/types/media'
|
||||
import { formatFileSize } from '~/composables/useFileSize'
|
||||
import SiteSyncSelectedDialog from '~/components/storage/SiteSyncSelectedDialog.vue'
|
||||
|
||||
const { isAuthenticated, handleAuthError } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t, locale } = useI18n()
|
||||
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
|
||||
const transcodeFailureLabel = useTranscodeFailureLabel()
|
||||
|
||||
const items = ref<FileItem[]>([])
|
||||
const total = ref(0)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(20)
|
||||
const totalPages = ref(1)
|
||||
const loading = ref(false)
|
||||
const searchQuery = ref('')
|
||||
const activeSearch = ref('')
|
||||
const accessMode = ref<'public' | 'token'>('public')
|
||||
const apiToken = ref('')
|
||||
const stats = ref<LibraryStatsData | null>(null)
|
||||
|
||||
const selectedKeys = ref<Set<string>>(new Set())
|
||||
const deleteModalOpen = ref(false)
|
||||
const batchTagOpen = ref(false)
|
||||
const syncOpen = ref(false)
|
||||
const deleteTargetKeys = ref<string[]>([])
|
||||
const deleting = ref(false)
|
||||
const previewOpen = ref(false)
|
||||
const previewItem = ref<FileItem | null>(null)
|
||||
const downloadOpen = ref(false)
|
||||
const downloadItem = ref<FileItem | null>(null)
|
||||
|
||||
const currentBackend = ref('all')
|
||||
const currentSource = ref('all')
|
||||
const backendOptions = ref<Array<{ id: string, name: string }>>([])
|
||||
const activeTagIds = ref<number[]>([])
|
||||
const activeTagMode = ref<'or' | 'and'>('or')
|
||||
const activeUntaggedOnly = ref(false)
|
||||
const { viewMode } = useLibraryView('video')
|
||||
|
||||
const selectedCount = computed(() => selectedKeys.value.size)
|
||||
const syncKeys = computed(() => [...selectedKeys.value])
|
||||
|
||||
const backendItems = computed(() => [
|
||||
{ label: t('stats.filterStorageAll'), value: 'all' },
|
||||
...backendOptions.value.map(backend => ({ label: backend.name, value: backend.id }))
|
||||
])
|
||||
|
||||
const sourceItems = computed(() => [
|
||||
{ label: t('stats.filterSourceAll'), value: 'all' },
|
||||
{ label: t('stats.sourceWeb'), value: 'web' },
|
||||
{ label: t('stats.sourceApi'), value: 'api' }
|
||||
])
|
||||
|
||||
const allSelected = computed(() =>
|
||||
items.value.length > 0 && items.value.every(item => selectedKeys.value.has(item.key))
|
||||
)
|
||||
|
||||
function withToken(raw: string | undefined): string {
|
||||
if (!raw) return ''
|
||||
if (accessMode.value !== 'token' || !apiToken.value) return raw
|
||||
const separator = raw.includes('?') ? '&' : '?'
|
||||
return `${raw}${separator}token=${encodeURIComponent(apiToken.value)}`
|
||||
}
|
||||
|
||||
/** 转码完成后主直链指向 m3u8 播放列表 */
|
||||
function videoLink(item: FileItem): string {
|
||||
return withToken(item.hlsUrl ?? item.url)
|
||||
}
|
||||
|
||||
function thumbLink(item: FileItem): string {
|
||||
return withToken(item.thumbUrl) || '/video-placeholder.svg'
|
||||
}
|
||||
|
||||
function downloadUrl(item: FileItem): string {
|
||||
return withToken(item.url)
|
||||
}
|
||||
|
||||
/** 转码完成后按 HLS 播放列表展示名称 */
|
||||
function displayName(item: FileItem): string {
|
||||
if (!item.hlsUrl) return item.originalName
|
||||
const dot = item.originalName.lastIndexOf('.')
|
||||
const base = dot > 0 ? item.originalName.slice(0, dot) : item.originalName
|
||||
return `${base}.m3u8`
|
||||
}
|
||||
|
||||
function uploadedLabel(item: FileItem): string {
|
||||
try {
|
||||
return new Date(item.uploadedAt).toLocaleString(locale.value, { hour12: false })
|
||||
} catch {
|
||||
return item.uploadedAt
|
||||
}
|
||||
}
|
||||
|
||||
async function loadApiToken() {
|
||||
try {
|
||||
const data = await $fetch<{ apiUploadToken: string }>('/api/user/api-token', {
|
||||
credentials: 'include'
|
||||
})
|
||||
apiToken.value = data.apiUploadToken ?? ''
|
||||
} catch {
|
||||
apiToken.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
async function loadBackendOptions() {
|
||||
try {
|
||||
const data = await $fetch<{ backends: Array<{ id: string, name: string }> }>(
|
||||
'/api/storage-backends',
|
||||
{ credentials: 'include' }
|
||||
)
|
||||
backendOptions.value = data.backends ?? []
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchStats() {
|
||||
if (!isAuthenticated.value) return
|
||||
try {
|
||||
stats.value = await $fetch<LibraryStatsData>('/api/library/stats', {
|
||||
credentials: 'include',
|
||||
query: { kind: 'video' }
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchList(targetPage = page.value) {
|
||||
if (!isAuthenticated.value) return
|
||||
loading.value = true
|
||||
try {
|
||||
const response = await $fetch<FileListResponse>('/api/files', {
|
||||
credentials: 'include',
|
||||
query: {
|
||||
limit: pageSize.value,
|
||||
page: targetPage,
|
||||
kind: 'video',
|
||||
...(activeSearch.value ? { q: activeSearch.value } : {}),
|
||||
...(currentBackend.value !== 'all' ? { backendId: currentBackend.value } : {}),
|
||||
...(currentSource.value !== 'all' ? { uploadSource: currentSource.value } : {}),
|
||||
...(activeTagIds.value.length ? { tagIds: activeTagIds.value.join(',') } : {}),
|
||||
...(activeUntaggedOnly.value ? { untagged: '1' } : {}),
|
||||
...(activeTagMode.value === 'and' ? { tagMode: 'and' } : {})
|
||||
}
|
||||
})
|
||||
|
||||
items.value = response.items
|
||||
total.value = response.total
|
||||
page.value = response.page
|
||||
totalPages.value = response.totalPages
|
||||
accessMode.value = response.accessMode
|
||||
|
||||
const visible = new Set(response.items.map(item => item.key))
|
||||
selectedKeys.value = new Set(
|
||||
[...selectedKeys.value].filter(key => visible.has(key))
|
||||
)
|
||||
|
||||
if (response.accessMode === 'token' && !apiToken.value) {
|
||||
await loadApiToken()
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('files.loadFailed'), color: 'error' })
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
await Promise.all([fetchList(1), fetchStats(), fetchTags()])
|
||||
}
|
||||
|
||||
async function submitSearch() {
|
||||
if (!isAuthenticated.value) return
|
||||
activeSearch.value = searchQuery.value.trim()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleBackendChange(value: string) {
|
||||
currentBackend.value = value
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleSourceChange(value: string) {
|
||||
currentSource.value = value
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleTagIdsChange(tagIds: number[]) {
|
||||
activeTagIds.value = tagIds
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleTagModeChange(tagMode: 'or' | 'and') {
|
||||
activeTagMode.value = tagMode
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function handleUntaggedChange(untaggedOnly: boolean) {
|
||||
activeUntaggedOnly.value = untaggedOnly
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
async function resetFilters() {
|
||||
searchQuery.value = ''
|
||||
activeSearch.value = ''
|
||||
currentBackend.value = 'all'
|
||||
currentSource.value = 'all'
|
||||
activeTagIds.value = []
|
||||
activeTagMode.value = 'or'
|
||||
activeUntaggedOnly.value = false
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
function toggleSelected(key: string, value: boolean) {
|
||||
const next = new Set(selectedKeys.value)
|
||||
if (value) next.add(key)
|
||||
else next.delete(key)
|
||||
selectedKeys.value = next
|
||||
}
|
||||
|
||||
function toggleSelectAll() {
|
||||
selectedKeys.value = allSelected.value
|
||||
? new Set()
|
||||
: new Set(items.value.map(item => item.key))
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedKeys.value = new Set()
|
||||
}
|
||||
|
||||
function setViewMode(mode: 'grid' | 'list') {
|
||||
viewMode.value = mode
|
||||
}
|
||||
|
||||
function openBatchTags() {
|
||||
batchTagOpen.value = true
|
||||
}
|
||||
|
||||
function openSync() {
|
||||
syncOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmBatchTags(tagIds: number[], action: 'add' | 'remove') {
|
||||
const keys = [...selectedKeys.value]
|
||||
if (!keys.length || !tagIds.length) return
|
||||
|
||||
try {
|
||||
await batchUpdateTags(keys, tagIds, action)
|
||||
batchTagOpen.value = false
|
||||
selectedKeys.value = new Set()
|
||||
toast.add({ title: t('tags.batchSuccess'), color: 'success' })
|
||||
await Promise.all([fetchList(1), fetchStats(), fetchTags(true)])
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
toast.add({ title: t('tags.batchFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
function openPreview(item: FileItem) {
|
||||
previewItem.value = item
|
||||
previewOpen.value = true
|
||||
}
|
||||
|
||||
function requestDownload(item: FileItem | null) {
|
||||
if (!item?.hlsUrl) return
|
||||
previewOpen.value = false
|
||||
downloadItem.value = item
|
||||
downloadOpen.value = true
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadBackendOptions()
|
||||
})
|
||||
|
||||
function requestDelete(item: FileItem) {
|
||||
if (!isAuthenticated.value) return
|
||||
deleteTargetKeys.value = [item.key]
|
||||
deleteModalOpen.value = true
|
||||
}
|
||||
|
||||
function requestBatchDelete() {
|
||||
if (!isAuthenticated.value) return
|
||||
if (!selectedCount.value) {
|
||||
toast.add({ title: t('library.selectFirst'), color: 'warning' })
|
||||
return
|
||||
}
|
||||
deleteTargetKeys.value = [...selectedKeys.value]
|
||||
deleteModalOpen.value = true
|
||||
}
|
||||
|
||||
async function confirmDelete() {
|
||||
const keys = [...deleteTargetKeys.value]
|
||||
if (!keys.length || !isAuthenticated.value) return
|
||||
|
||||
deleting.value = true
|
||||
try {
|
||||
if (keys.length === 1) {
|
||||
await $fetch('/api/files', {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
query: { key: keys[0] }
|
||||
})
|
||||
} else {
|
||||
const response = await $fetch<{ deleted: string[], failed: unknown[] }>(
|
||||
'/api/files/batch-delete',
|
||||
{ method: 'POST', credentials: 'include', body: { keys } }
|
||||
)
|
||||
if (response.failed.length) {
|
||||
toast.add({
|
||||
title: t('library.deletePartialFail', { n: response.failed.length }),
|
||||
color: 'warning'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
toast.add({ title: t('library.deleted', { n: keys.length }), color: 'success' })
|
||||
deleteModalOpen.value = false
|
||||
deleteTargetKeys.value = []
|
||||
selectedKeys.value = new Set()
|
||||
await refresh()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('files.deleteFailed'), color: 'error' })
|
||||
}
|
||||
} finally {
|
||||
deleting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handlePageChange(targetPage: number) {
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(targetPage)
|
||||
}
|
||||
|
||||
async function handlePageSizeChange(size: number) {
|
||||
pageSize.value = size
|
||||
selectedKeys.value = new Set()
|
||||
await fetchList(1)
|
||||
}
|
||||
|
||||
defineExpose({ refresh })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-6">
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<h1 class="text-2xl font-semibold tracking-tight">
|
||||
{{ t('library.video.title') }}
|
||||
</h1>
|
||||
<p class="text-sm text-muted">
|
||||
{{ t('library.video.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<UButton
|
||||
icon="i-lucide-refresh-cw"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
class="mt-0.5 shrink-0"
|
||||
:aria-label="t('common.refresh')"
|
||||
:loading="loading"
|
||||
@click="refresh"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<LibraryStatsPanel
|
||||
kind="video"
|
||||
:stats="stats"
|
||||
:loading="loading"
|
||||
/>
|
||||
|
||||
<section class="space-y-3">
|
||||
<div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
|
||||
<div class="flex items-center gap-2 text-sm">
|
||||
<UCheckbox
|
||||
:model-value="allSelected"
|
||||
:disabled="!items.length"
|
||||
@update:model-value="toggleSelectAll"
|
||||
/>
|
||||
<span class="text-muted">
|
||||
{{ t('library.selectedCount', { n: selectedCount }) }}
|
||||
</span>
|
||||
<UButton
|
||||
v-if="selectedCount > 0"
|
||||
variant="link"
|
||||
color="primary"
|
||||
size="xs"
|
||||
:label="t('library.clearSelection')"
|
||||
@click="clearSelection"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<UInput
|
||||
v-model="searchQuery"
|
||||
icon="i-lucide-search"
|
||||
:placeholder="t('library.searchPlaceholder')"
|
||||
size="sm"
|
||||
class="w-44"
|
||||
@keydown.enter.prevent="submitSearch"
|
||||
/>
|
||||
<USelect
|
||||
:model-value="currentBackend"
|
||||
:items="backendItems"
|
||||
value-key="value"
|
||||
size="sm"
|
||||
class="w-32"
|
||||
:aria-label="t('stats.filterStorageAll')"
|
||||
@update:model-value="handleBackendChange"
|
||||
/>
|
||||
<USelect
|
||||
:model-value="currentSource"
|
||||
:items="sourceItems"
|
||||
value-key="value"
|
||||
size="sm"
|
||||
class="w-28"
|
||||
:aria-label="t('stats.filterSourceAll')"
|
||||
@update:model-value="handleSourceChange"
|
||||
/>
|
||||
<TagFilterSelect
|
||||
:model-value="activeTagIds"
|
||||
:tag-mode="activeTagMode"
|
||||
:untagged-only="activeUntaggedOnly"
|
||||
:tags="tagItems"
|
||||
:disabled="loading"
|
||||
@update:model-value="handleTagIdsChange"
|
||||
@update:tag-mode="handleTagModeChange"
|
||||
@update:untagged-only="handleUntaggedChange"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-search"
|
||||
size="sm"
|
||||
:label="t('common.search')"
|
||||
:loading="loading"
|
||||
@click="submitSearch"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-rotate-ccw"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
:label="t('library.reset')"
|
||||
@click="resetFilters"
|
||||
/>
|
||||
<UButton
|
||||
v-if="selectedCount > 0"
|
||||
icon="i-lucide-tags"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
size="sm"
|
||||
:disabled="!selectedCount || loading"
|
||||
:label="t('tags.batchAdd')"
|
||||
@click="openBatchTags"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-trash-2"
|
||||
variant="outline"
|
||||
color="error"
|
||||
size="sm"
|
||||
:disabled="!selectedCount || loading"
|
||||
:label="t('library.batchDelete')"
|
||||
@click="requestBatchDelete"
|
||||
/>
|
||||
<UButton
|
||||
v-if="selectedCount > 0"
|
||||
icon="i-lucide-cloud-upload"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
:disabled="!selectedCount || loading"
|
||||
:label="t('storage.backup.syncSelectedAction')"
|
||||
@click="openSync"
|
||||
/>
|
||||
<div class="flex gap-0.5 rounded-lg border border-default p-0.5">
|
||||
<UButton
|
||||
icon="i-lucide-layout-grid"
|
||||
size="xs"
|
||||
:variant="viewMode === 'grid' ? 'solid' : 'ghost'"
|
||||
:color="viewMode === 'grid' ? 'primary' : 'neutral'"
|
||||
:aria-label="t('stats.viewGrid')"
|
||||
@click="setViewMode('grid')"
|
||||
/>
|
||||
<UButton
|
||||
icon="i-lucide-list"
|
||||
size="xs"
|
||||
:variant="viewMode === 'list' ? 'solid' : 'ghost'"
|
||||
:color="viewMode === 'list' ? 'primary' : 'neutral'"
|
||||
:aria-label="t('stats.viewList')"
|
||||
@click="setViewMode('list')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="loading && !items.length"
|
||||
class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
|
||||
>
|
||||
<USkeleton
|
||||
v-for="n in 8"
|
||||
:key="n"
|
||||
class="aspect-[4/3] rounded-xl"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-else-if="!items.length"
|
||||
class="rounded-lg border border-default py-10 text-center text-sm text-muted"
|
||||
>
|
||||
{{ activeSearch ? t('library.searchEmpty') : t('library.video.empty') }}
|
||||
</p>
|
||||
|
||||
<div
|
||||
v-else-if="viewMode === 'grid'"
|
||||
class="grid gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
|
||||
>
|
||||
<VideoCard
|
||||
v-for="item in items"
|
||||
:key="item.key"
|
||||
:item="item"
|
||||
:link="videoLink(item)"
|
||||
:thumb-link="thumbLink(item)"
|
||||
:download-link="downloadUrl(item)"
|
||||
selectable
|
||||
:selected="selectedKeys.has(item.key)"
|
||||
@update:selected="toggleSelected(item.key, $event)"
|
||||
@play="openPreview(item)"
|
||||
@download="requestDownload(item)"
|
||||
@delete="requestDelete(item)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="overflow-hidden rounded-xl border border-default bg-default"
|
||||
>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="min-w-full text-xs">
|
||||
<thead class="border-b border-default bg-elevated/40 text-muted">
|
||||
<tr>
|
||||
<th class="w-10 px-3 py-2.5 text-left font-medium">
|
||||
<UCheckbox
|
||||
:model-value="allSelected"
|
||||
:aria-label="t('stats.selectAll')"
|
||||
@update:model-value="toggleSelectAll"
|
||||
/>
|
||||
</th>
|
||||
<th class="min-w-[14rem] px-3 py-2.5 text-left font-medium">
|
||||
{{ t('stats.colFilename') }}
|
||||
</th>
|
||||
<th class="hidden w-24 px-3 py-2.5 text-left font-medium sm:table-cell">
|
||||
{{ t('stats.colSource') }}
|
||||
</th>
|
||||
<th class="w-20 px-3 py-2.5 text-left font-medium">
|
||||
{{ t('stats.colSize') }}
|
||||
</th>
|
||||
<th class="hidden w-28 px-3 py-2.5 text-left font-medium md:table-cell">
|
||||
{{ t('stats.colType') }}
|
||||
</th>
|
||||
<th class="hidden w-40 px-3 py-2.5 text-left font-medium lg:table-cell">
|
||||
{{ t('stats.colUploadedAt') }}
|
||||
</th>
|
||||
<th class="hidden min-w-[9rem] px-3 py-2.5 text-left font-medium md:table-cell">
|
||||
{{ t('tags.column') }}
|
||||
</th>
|
||||
<th class="w-32 px-3 py-2.5 text-right font-medium">
|
||||
{{ t('stats.colActions') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-default">
|
||||
<tr
|
||||
v-for="item in items"
|
||||
:key="item.key"
|
||||
class="transition-colors hover:bg-elevated/50"
|
||||
:class="selectedKeys.has(item.key) ? 'bg-primary/5' : ''"
|
||||
>
|
||||
<td class="px-3 py-2">
|
||||
<UCheckbox
|
||||
:model-value="selectedKeys.has(item.key)"
|
||||
@update:model-value="toggleSelected(item.key, $event === true)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-3 py-2.5">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="relative aspect-video w-12 shrink-0 overflow-hidden rounded-md border border-default bg-muted"
|
||||
:aria-label="t('library.play')"
|
||||
@click="openPreview(item)"
|
||||
>
|
||||
<VideoThumbnail
|
||||
:src="thumbLink(item)"
|
||||
:alt="displayName(item)"
|
||||
/>
|
||||
</button>
|
||||
<p
|
||||
class="min-w-0 flex-1 truncate text-highlighted"
|
||||
:title="displayName(item)"
|
||||
>
|
||||
{{ displayName(item) }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="item.hlsUrl"
|
||||
color="success"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="shrink-0"
|
||||
>
|
||||
m3u8
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-else-if="item.transcodeStatus === 'failed'"
|
||||
color="error"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="shrink-0"
|
||||
:title="transcodeFailureLabel(item.transcodeError)"
|
||||
>
|
||||
{{ transcodeFailureLabel(item.transcodeError) }}
|
||||
</UBadge>
|
||||
</div>
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 sm:table-cell">
|
||||
<span
|
||||
v-if="item.uploadSource"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-default px-1.5 py-0.5 text-[11px] leading-4 text-muted"
|
||||
>
|
||||
<UIcon
|
||||
:name="item.uploadSource === 'api' ? 'i-lucide-code-xml' : 'i-lucide-globe'"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ item.uploadSource === 'api' ? t('stats.tagApi') : t('stats.tagWeb') }}
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted"
|
||||
>—</span>
|
||||
</td>
|
||||
<td class="px-3 py-2 tabular-nums text-muted">
|
||||
{{ formatFileSize(item.size) }}
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 md:table-cell">
|
||||
<span
|
||||
v-if="item.storage"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-default px-1.5 py-0.5 text-[11px] leading-4 text-muted"
|
||||
>
|
||||
<UIcon
|
||||
:name="item.storage.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ item.storage.name }}
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted"
|
||||
>—</span>
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 text-muted lg:table-cell">
|
||||
{{ uploadedLabel(item) }}
|
||||
</td>
|
||||
<td class="hidden px-3 py-2 md:table-cell">
|
||||
<TagBadgeList
|
||||
:tags="item.tags"
|
||||
compact
|
||||
:empty-label="t('tags.unlabeled')"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex items-center justify-end gap-1">
|
||||
<CopyButton
|
||||
icon-only
|
||||
icon="i-lucide-link"
|
||||
:label="t('library.copyVideoLink')"
|
||||
:value="videoLink(item)"
|
||||
/>
|
||||
<CopyButton
|
||||
icon-only
|
||||
icon="i-lucide-image"
|
||||
:label="t('library.copyThumbLink')"
|
||||
:value="thumbLink(item)"
|
||||
/>
|
||||
<UButton
|
||||
v-if="!item.sourceDeleted"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
icon="i-lucide-download"
|
||||
:to="downloadUrl(item)"
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
:aria-label="t('files.download')"
|
||||
/>
|
||||
<UButton
|
||||
v-else-if="item.hlsUrl"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
icon="i-lucide-download"
|
||||
:aria-label="t('library.video.downloadMp4')"
|
||||
@click="requestDownload(item)"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="error"
|
||||
icon="i-lucide-trash-2"
|
||||
:aria-label="t('common.delete')"
|
||||
@click="requestDelete(item)"
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
v-if="!loading && total > 0"
|
||||
:page="page"
|
||||
:total-pages="totalPages"
|
||||
:total="total"
|
||||
:page-size="pageSize"
|
||||
unit=""
|
||||
:loading="loading"
|
||||
@update:page="handlePageChange"
|
||||
@update:page-size="handlePageSizeChange"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<DeleteConfirmModal
|
||||
v-model:open="deleteModalOpen"
|
||||
:count="deleteTargetKeys.length"
|
||||
:loading="deleting"
|
||||
kind="video"
|
||||
@confirm="confirmDelete"
|
||||
/>
|
||||
|
||||
<BatchTagModal
|
||||
v-model:open="batchTagOpen"
|
||||
:tags="tagItems"
|
||||
:selected-count="selectedCount"
|
||||
@confirm="confirmBatchTags"
|
||||
/>
|
||||
|
||||
<SiteSyncSelectedDialog
|
||||
v-model:open="syncOpen"
|
||||
:keys="syncKeys"
|
||||
scope="video"
|
||||
/>
|
||||
|
||||
<VideoPreviewModal
|
||||
v-model:open="previewOpen"
|
||||
:item="previewItem"
|
||||
:link="previewItem ? videoLink(previewItem) : ''"
|
||||
:thumb-link="previewItem ? thumbLink(previewItem) : ''"
|
||||
:download-link="previewItem ? downloadUrl(previewItem) : ''"
|
||||
:deleting="deleting"
|
||||
@download="requestDownload(previewItem)"
|
||||
@delete="previewItem && requestDelete(previewItem)"
|
||||
/>
|
||||
|
||||
<HlsDownloadModal
|
||||
v-model:open="downloadOpen"
|
||||
:item="downloadItem"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,533 @@
|
||||
<script setup lang="ts">
|
||||
import type { FileItem } from '~/types/file'
|
||||
import type { CopyFormat } from '~/composables/useUploadPreferences'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
open: boolean
|
||||
item: FileItem | null
|
||||
/** 已按访问模式拼接好的视频直链 */
|
||||
link: string
|
||||
/** 缩略图直链 */
|
||||
thumbLink: string
|
||||
/** 原始视频下载地址 */
|
||||
downloadLink: string
|
||||
deleting?: boolean
|
||||
allowDelete?: boolean
|
||||
}>(), {
|
||||
allowDelete: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
'delete': []
|
||||
'download': []
|
||||
}>()
|
||||
|
||||
const toast = useToast()
|
||||
const { formatFileSize } = useFileSize()
|
||||
const { t, locale } = useI18n()
|
||||
const transcodeFailureLabel = useTranscodeFailureLabel()
|
||||
const { copyFormat } = useUploadPreferences('video')
|
||||
|
||||
const videoEl = ref<HTMLVideoElement | null>(null)
|
||||
const copyingUrl = ref(false)
|
||||
const embedFormat = ref<CopyFormat>('url')
|
||||
|
||||
let hlsInstance: { destroy: () => void } | null = null
|
||||
|
||||
const embedFormatItems = computed(() => [
|
||||
{ label: t('copy.url'), value: 'url' as const },
|
||||
{ label: t('copy.markdown'), value: 'markdown' as const },
|
||||
{ label: t('copy.html'), value: 'html' as const },
|
||||
{ label: t('copy.bbcode'), value: 'bbcode' as const }
|
||||
])
|
||||
|
||||
/** 转码完成后按 HLS 播放列表展示 */
|
||||
const displayName = computed(() => {
|
||||
const item = props.item
|
||||
if (!item) return '—'
|
||||
if (!item.hlsUrl) return item.originalName
|
||||
const dot = item.originalName.lastIndexOf('.')
|
||||
const base = dot > 0 ? item.originalName.slice(0, dot) : item.originalName
|
||||
return `${base}.m3u8`
|
||||
})
|
||||
|
||||
const uploadedLabel = computed(() => {
|
||||
const item = props.item
|
||||
if (!item) return '—'
|
||||
try {
|
||||
return new Date(item.uploadedAt).toLocaleString(locale.value, { hour12: false })
|
||||
} catch {
|
||||
return item.uploadedAt
|
||||
}
|
||||
})
|
||||
|
||||
const sizeLabel = computed(() => {
|
||||
const item = props.item
|
||||
if (!item) return '—'
|
||||
return t('image.previewSizeDetail', {
|
||||
size: formatFileSize(item.size),
|
||||
bytes: item.size.toLocaleString(locale.value)
|
||||
})
|
||||
})
|
||||
|
||||
const transcodeLabel = computed(() => {
|
||||
const item = props.item
|
||||
if (!item) return '—'
|
||||
switch (item.transcodeStatus) {
|
||||
case 'pending':
|
||||
return t('library.transcodePending')
|
||||
case 'running':
|
||||
return `${t('library.transcoding')} ${item.transcodeProgress ?? 0}%`
|
||||
case 'done':
|
||||
return t('library.video.transcodeDone')
|
||||
case 'failed':
|
||||
return transcodeFailureLabel(item.transcodeError)
|
||||
default:
|
||||
return t('library.video.transcodeNone')
|
||||
}
|
||||
})
|
||||
|
||||
/** 转码完成后条目实际代表 HLS,路径与类型都按播放列表展示 */
|
||||
const storagePath = computed(() => props.item?.hlsKey ?? props.item?.key ?? '—')
|
||||
const contentTypeLabel = computed(() =>
|
||||
props.item?.hlsKey ? 'application/vnd.apple.mpegurl' : props.item?.contentType ?? '—'
|
||||
)
|
||||
|
||||
const previewValue = computed(() => {
|
||||
if (!props.item) return ''
|
||||
switch (embedFormat.value) {
|
||||
case 'markdown':
|
||||
return `[${displayName.value}](${props.link})`
|
||||
case 'html':
|
||||
return `<a href="${props.link}">${displayName.value}</a>`
|
||||
case 'bbcode':
|
||||
return `[url=${props.link}]${displayName.value}[/url]`
|
||||
default:
|
||||
return props.link
|
||||
}
|
||||
})
|
||||
|
||||
const copySuccessTitle = computed(() => {
|
||||
switch (embedFormat.value) {
|
||||
case 'markdown':
|
||||
return t('copy.copiedMarkdown')
|
||||
case 'html':
|
||||
return t('copy.copiedHtml')
|
||||
case 'bbcode':
|
||||
return t('copy.copiedBbcode')
|
||||
default:
|
||||
return t('copy.copiedUrl')
|
||||
}
|
||||
})
|
||||
|
||||
const storageIcon = computed(() =>
|
||||
props.item?.storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
|
||||
)
|
||||
|
||||
const uploadSourceTag = computed(() => {
|
||||
switch (props.item?.uploadSource) {
|
||||
case 'web':
|
||||
return t('stats.tagWeb')
|
||||
case 'api':
|
||||
return t('stats.tagApi')
|
||||
default:
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
const uploadSourceIcon = computed(() => {
|
||||
switch (props.item?.uploadSource) {
|
||||
case 'web':
|
||||
return 'i-lucide-globe'
|
||||
case 'api':
|
||||
return 'i-lucide-code-xml'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
})
|
||||
|
||||
function destroyPlayer() {
|
||||
if (hlsInstance) {
|
||||
hlsInstance.destroy()
|
||||
hlsInstance = null
|
||||
}
|
||||
if (videoEl.value) {
|
||||
videoEl.value.removeAttribute('src')
|
||||
videoEl.value.load()
|
||||
}
|
||||
}
|
||||
|
||||
async function attachPlayerSource() {
|
||||
const item = props.item
|
||||
const element = videoEl.value
|
||||
if (!item || !element) return
|
||||
|
||||
element.src = props.link
|
||||
if (!item.hlsUrl || element.canPlayType('application/vnd.apple.mpegurl')) return
|
||||
|
||||
const { default: Hls } = await import('hls.js')
|
||||
if (!Hls.isSupported()) return
|
||||
|
||||
const hls = new Hls()
|
||||
hls.on(Hls.Events.ERROR, (_event, data) => {
|
||||
if (!data.fatal) return
|
||||
// 切片缺失(例如从备份恢复)时回退播放原视频
|
||||
hls.destroy()
|
||||
hlsInstance = null
|
||||
element.src = props.downloadLink
|
||||
})
|
||||
hls.loadSource(props.link)
|
||||
hls.attachMedia(element)
|
||||
hlsInstance = hls
|
||||
}
|
||||
|
||||
watch(() => props.open, async (open) => {
|
||||
if (!open) {
|
||||
destroyPlayer()
|
||||
return
|
||||
}
|
||||
embedFormat.value = copyFormat.value
|
||||
await nextTick()
|
||||
await attachPlayerSource()
|
||||
})
|
||||
|
||||
onUnmounted(destroyPlayer)
|
||||
|
||||
function selectEmbedFormat(value: CopyFormat) {
|
||||
embedFormat.value = value
|
||||
copyFormat.value = value
|
||||
}
|
||||
|
||||
async function copyText(text: string, successTitle: string) {
|
||||
if (!text) return
|
||||
try {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(text)
|
||||
toast.add({ title: successTitle, color: 'success' })
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
// 回退方案见下
|
||||
}
|
||||
|
||||
const textarea = document.createElement('textarea')
|
||||
textarea.value = text
|
||||
textarea.setAttribute('readonly', '')
|
||||
textarea.style.position = 'fixed'
|
||||
textarea.style.left = '-9999px'
|
||||
document.body.appendChild(textarea)
|
||||
textarea.select()
|
||||
let ok = false
|
||||
try {
|
||||
ok = document.execCommand('copy')
|
||||
} catch {
|
||||
ok = false
|
||||
} finally {
|
||||
document.body.removeChild(textarea)
|
||||
}
|
||||
|
||||
toast.add({
|
||||
title: ok ? successTitle : t('copy.failedManual'),
|
||||
color: ok ? 'success' : 'error'
|
||||
})
|
||||
}
|
||||
|
||||
async function copyLink() {
|
||||
if (!props.link || copyingUrl.value) return
|
||||
copyingUrl.value = true
|
||||
try {
|
||||
await copyText(props.link, t('copy.copiedUrl'))
|
||||
} finally {
|
||||
copyingUrl.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openInNewTab() {
|
||||
if (!props.link) return
|
||||
window.open(props.link, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
function downloadOriginal() {
|
||||
if (!props.downloadLink) return
|
||||
const link = document.createElement('a')
|
||||
link.href = props.downloadLink
|
||||
link.download = props.item?.originalName || 'video'
|
||||
link.rel = 'noopener'
|
||||
link.click()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UModal
|
||||
:open="open && !!item"
|
||||
:title="t('library.video.previewTitle')"
|
||||
:description="t('library.video.previewSubtitle')"
|
||||
:ui="{ content: 'max-w-5xl' }"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<template
|
||||
v-if="item"
|
||||
#body
|
||||
>
|
||||
<div class="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.15fr)] lg:items-start">
|
||||
<div class="flex items-center justify-center overflow-hidden rounded-xl border border-default bg-black p-2">
|
||||
<video
|
||||
ref="videoEl"
|
||||
controls
|
||||
autoplay
|
||||
playsinline
|
||||
class="max-h-[min(60vh,24rem)] w-full rounded-lg bg-black"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-0 flex-col gap-5">
|
||||
<dl class="divide-y divide-default text-sm">
|
||||
<div class="flex gap-4 py-2.5 first:pt-0">
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('image.previewOriginalName') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1 break-all font-medium">
|
||||
{{ displayName }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex gap-4 py-2.5">
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('image.previewUploadedAt') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
{{ uploadedLabel }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex gap-4 py-2.5">
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('image.previewSize') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
{{ sizeLabel }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex gap-4 py-2.5">
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('image.previewContentType') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
{{ contentTypeLabel }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex gap-4 py-2.5">
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('library.video.previewTranscode') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
<UBadge
|
||||
:color="item.hlsUrl ? 'success' : item.transcodeStatus === 'failed' ? 'error' : 'neutral'"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ transcodeLabel }}
|
||||
</UBadge>
|
||||
</dd>
|
||||
</div>
|
||||
<div
|
||||
v-if="item.storage"
|
||||
class="flex gap-4 py-2.5"
|
||||
>
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('image.previewStorage') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
<UIcon
|
||||
:name="storageIcon"
|
||||
class="size-3.5 shrink-0 text-muted"
|
||||
/>
|
||||
{{ item.storage.name }}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div
|
||||
v-if="uploadSourceTag"
|
||||
class="flex gap-4 py-2.5"
|
||||
>
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('image.previewUploadSource') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
<span
|
||||
v-if="uploadSourceIcon"
|
||||
class="inline-flex items-center gap-1 rounded-md border border-default px-2 py-0.5 text-xs text-muted"
|
||||
>
|
||||
<UIcon
|
||||
:name="uploadSourceIcon"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ uploadSourceTag }}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div
|
||||
v-if="item.owner"
|
||||
class="flex gap-4 py-2.5"
|
||||
>
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('image.previewOwner') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
{{ item.owner.username }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex gap-4 py-2.5">
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('tags.column') }}
|
||||
</dt>
|
||||
<dd class="min-w-0 flex-1">
|
||||
<div
|
||||
v-if="item.tags?.length"
|
||||
class="flex flex-wrap gap-1.5"
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in item.tags"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
v-else
|
||||
class="inline-flex rounded-md border border-dashed border-default px-2 py-0.5 text-xs text-muted"
|
||||
>
|
||||
{{ t('tags.unlabeled') }}
|
||||
</span>
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex gap-4 py-2.5 last:pb-0">
|
||||
<dt class="w-20 shrink-0 text-muted">
|
||||
{{ t('library.video.previewKey') }}
|
||||
</dt>
|
||||
<dd class="flex min-w-0 flex-1 items-start gap-2">
|
||||
<span class="min-w-0 flex-1 break-all font-mono text-xs text-dimmed">
|
||||
{{ storagePath }}
|
||||
</span>
|
||||
<CopyButton
|
||||
icon="i-lucide-copy"
|
||||
icon-only
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
class="shrink-0"
|
||||
:label="t('common.copy')"
|
||||
:value="storagePath"
|
||||
:success-title="t('copy.copied')"
|
||||
/>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div class="border-t border-default pt-4">
|
||||
<p class="mb-2.5 text-sm font-medium">
|
||||
{{ t('image.previewLinks') }}
|
||||
</p>
|
||||
<div class="flex gap-1 rounded-lg border border-default bg-default p-0.5">
|
||||
<UButton
|
||||
v-for="option in embedFormatItems"
|
||||
:key="option.value"
|
||||
size="xs"
|
||||
class="flex-1 justify-center"
|
||||
:variant="embedFormat === option.value ? 'solid' : 'ghost'"
|
||||
:color="embedFormat === option.value ? 'primary' : 'neutral'"
|
||||
:label="option.label"
|
||||
@click="selectEmbedFormat(option.value)"
|
||||
/>
|
||||
</div>
|
||||
<div class="mt-2 flex items-center gap-2">
|
||||
<UInput
|
||||
:model-value="previewValue"
|
||||
readonly
|
||||
size="sm"
|
||||
class="min-w-0 flex-1 font-mono text-xs"
|
||||
/>
|
||||
<CopyButton
|
||||
:label="t('common.copy')"
|
||||
:value="previewValue"
|
||||
:success-title="copySuccessTitle"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="thumbLink"
|
||||
class="mt-3"
|
||||
>
|
||||
<p class="mb-1.5 text-xs text-muted">
|
||||
{{ t('library.video.previewThumbLink') }}
|
||||
</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<UInput
|
||||
:model-value="thumbLink"
|
||||
readonly
|
||||
size="sm"
|
||||
class="min-w-0 flex-1 font-mono text-xs"
|
||||
/>
|
||||
<CopyButton
|
||||
:label="t('common.copy')"
|
||||
:value="thumbLink"
|
||||
:success-title="t('copy.copiedUrl')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template
|
||||
v-if="item"
|
||||
#footer
|
||||
>
|
||||
<div class="flex w-full flex-wrap justify-end gap-1.5">
|
||||
<UButton
|
||||
:label="t('image.previewOpen')"
|
||||
icon="i-lucide-external-link"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="openInNewTab"
|
||||
/>
|
||||
<UButton
|
||||
v-if="!item.sourceDeleted"
|
||||
:label="t('image.previewDownload')"
|
||||
icon="i-lucide-download"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="downloadOriginal"
|
||||
/>
|
||||
<UButton
|
||||
v-else-if="item.hlsUrl"
|
||||
:label="t('library.video.downloadMp4')"
|
||||
icon="i-lucide-download"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="emit('download')"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('image.previewCopyLink')"
|
||||
icon="i-lucide-link"
|
||||
color="primary"
|
||||
size="sm"
|
||||
:loading="copyingUrl"
|
||||
@click="copyLink"
|
||||
/>
|
||||
<UButton
|
||||
v-if="allowDelete"
|
||||
:label="t('common.delete')"
|
||||
icon="i-lucide-trash-2"
|
||||
color="error"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:loading="deleting"
|
||||
@click="emit('delete')"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</template>
|
||||
@@ -0,0 +1,30 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
src?: string
|
||||
alt: string
|
||||
}>()
|
||||
|
||||
const failed = ref(false)
|
||||
|
||||
watch(() => props.src, () => {
|
||||
failed.value = false
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<img
|
||||
v-if="src && !failed"
|
||||
:src="src"
|
||||
:alt="alt"
|
||||
loading="lazy"
|
||||
class="size-full object-cover object-center"
|
||||
@error="failed = true"
|
||||
>
|
||||
<img
|
||||
v-else
|
||||
src="/video-placeholder.svg"
|
||||
:alt="alt"
|
||||
loading="lazy"
|
||||
class="size-full object-cover object-center"
|
||||
>
|
||||
</template>
|
||||
@@ -65,8 +65,14 @@ function resetForm() {
|
||||
if (!isDebugParam(param)) continue
|
||||
if (param.type === 'file') {
|
||||
files[param.name] = null
|
||||
} else if (param.name === 'kind') {
|
||||
values[param.name] = props.endpoint.category === 'video' ? 'video' : 'file'
|
||||
} else if (param.name === 'keys') {
|
||||
values[param.name] = '["images/2026/08/example.webp"]'
|
||||
values[param.name] = props.endpoint.category === 'video'
|
||||
? '["videos/2026/10/example.mp4"]'
|
||||
: props.endpoint.category === 'file'
|
||||
? '["files/2026/10/example.pdf"]'
|
||||
: '["images/2026/08/example.webp"]'
|
||||
} else if (param.name === 'token' && props.token) {
|
||||
values[param.name] = props.token
|
||||
} else {
|
||||
@@ -84,6 +90,12 @@ function fileLabel(name: string) {
|
||||
return fileValues.value[name]?.name ?? t('api.debug.noFileSelected')
|
||||
}
|
||||
|
||||
function fileAccept() {
|
||||
if (props.endpoint.category === 'video') return 'video/*'
|
||||
if (props.endpoint.category === 'file') return undefined
|
||||
return 'image/*'
|
||||
}
|
||||
|
||||
function triggerFilePick(name: string) {
|
||||
fileInputRefs.value[name]?.click()
|
||||
}
|
||||
@@ -101,8 +113,8 @@ function isParamFilled(param: ApiDocParam) {
|
||||
if (!value) return false
|
||||
if (param.location === 'body' && param.name === 'keys') {
|
||||
try {
|
||||
const parsed = JSON.parse(value) as { keys?: unknown }
|
||||
return Array.isArray(parsed.keys) && parsed.keys.length > 0
|
||||
const parsed = JSON.parse(value) as unknown
|
||||
return Array.isArray(parsed) && parsed.length > 0
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
@@ -159,7 +171,14 @@ async function sendRequest() {
|
||||
} else if (debugBodyParams.value.some(p => p.location === 'body')) {
|
||||
headers['Content-Type'] = 'application/json'
|
||||
try {
|
||||
body = JSON.stringify(JSON.parse(paramValues.value.keys || '{}'))
|
||||
const payload: Record<string, unknown> = {}
|
||||
for (const param of debugBodyParams.value) {
|
||||
if (param.location !== 'body') continue
|
||||
const value = paramValues.value[param.name]?.trim()
|
||||
if (!value) continue
|
||||
payload[param.name] = param.name === 'keys' ? JSON.parse(value) : value
|
||||
}
|
||||
body = JSON.stringify(payload)
|
||||
} catch {
|
||||
toast.add({ title: t('api.debug.invalidJson'), color: 'error' })
|
||||
sending.value = false
|
||||
@@ -297,7 +316,7 @@ const responseScrollable = computed(() => responseBody.value.split('\n').length
|
||||
<input
|
||||
:ref="(el) => { fileInputRefs[param.name] = el as HTMLInputElement }"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
:accept="fileAccept()"
|
||||
class="hidden"
|
||||
@change="onFileChange(param.name, $event)"
|
||||
>
|
||||
|
||||
@@ -38,19 +38,26 @@ const { t } = useI18n()
|
||||
</h3>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full min-w-[32rem] text-left text-sm">
|
||||
<table class="w-full min-w-[36rem] table-fixed text-left text-sm">
|
||||
<colgroup>
|
||||
<col class="w-[5.5rem]">
|
||||
<col class="w-[3.5rem]">
|
||||
<col class="w-[5.75rem]">
|
||||
<col class="w-[3.25rem]">
|
||||
<col>
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr class="border-b border-default text-xs text-muted">
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramName') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramType') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramLocation') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramRequired') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
@@ -64,20 +71,20 @@ const { t } = useI18n()
|
||||
:key="param.name"
|
||||
class="border-b border-default last:border-b-0"
|
||||
>
|
||||
<td class="px-4 py-2.5 font-mono text-xs">
|
||||
<td class="whitespace-nowrap px-4 py-2.5 font-mono text-xs">
|
||||
{{ param.name }}
|
||||
<span
|
||||
v-if="param.required"
|
||||
class="text-error"
|
||||
>*</span>
|
||||
</td>
|
||||
<td class="px-4 py-2.5 text-muted">
|
||||
<td class="whitespace-nowrap px-4 py-2.5 text-muted">
|
||||
{{ param.type }}
|
||||
</td>
|
||||
<td class="px-4 py-2.5 text-muted">
|
||||
<td class="whitespace-nowrap px-4 py-2.5 text-muted">
|
||||
{{ param.location }}
|
||||
</td>
|
||||
<td class="px-4 py-2.5">
|
||||
<td class="whitespace-nowrap px-4 py-2.5">
|
||||
<UBadge
|
||||
:color="param.required ? 'primary' : 'neutral'"
|
||||
variant="subtle"
|
||||
@@ -86,7 +93,7 @@ const { t } = useI18n()
|
||||
{{ param.required ? t('api.required') : t('api.optional') }}
|
||||
</UBadge>
|
||||
</td>
|
||||
<td class="px-4 py-2.5 text-muted">
|
||||
<td class="px-4 py-2.5 leading-relaxed text-muted break-words">
|
||||
{{ t(param.descriptionKey) }}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -20,9 +20,18 @@ const docsUrl = computed(() =>
|
||||
|
||||
const categories: { key: ApiDocCategory, labelKey: string }[] = [
|
||||
{ key: 'image', labelKey: 'api.categories.image' },
|
||||
{ key: 'video', labelKey: 'api.categories.video' },
|
||||
{ key: 'file', labelKey: 'api.categories.file' },
|
||||
{ key: 'extension', labelKey: 'api.categories.extension' },
|
||||
{ key: 'system', labelKey: 'api.categories.system' }
|
||||
]
|
||||
const openCategories = ref<Set<ApiDocCategory>>(
|
||||
new Set(
|
||||
categories
|
||||
.filter(category => category.key !== 'video' && category.key !== 'file')
|
||||
.map(category => category.key)
|
||||
)
|
||||
)
|
||||
|
||||
const filteredEndpoints = computed(() => {
|
||||
const q = search.value.trim().toLowerCase()
|
||||
@@ -38,6 +47,17 @@ function endpointsForCategory(category: ApiDocCategory) {
|
||||
return filteredEndpoints.value.filter(endpoint => endpoint.category === category)
|
||||
}
|
||||
|
||||
function isCategoryOpen(category: ApiDocCategory) {
|
||||
return openCategories.value.has(category)
|
||||
}
|
||||
|
||||
function toggleCategory(category: ApiDocCategory) {
|
||||
const next = new Set(openCategories.value)
|
||||
if (next.has(category)) next.delete(category)
|
||||
else next.add(category)
|
||||
openCategories.value = next
|
||||
}
|
||||
|
||||
function onSelect(id: string) {
|
||||
emit('select', id)
|
||||
}
|
||||
@@ -59,6 +79,15 @@ onMounted(() => {
|
||||
window.addEventListener('keydown', onGlobalKeydown)
|
||||
onUnmounted(() => window.removeEventListener('keydown', onGlobalKeydown))
|
||||
})
|
||||
|
||||
watch(search, (value) => {
|
||||
if (!value.trim()) return
|
||||
const next = new Set(openCategories.value)
|
||||
for (const category of categories) {
|
||||
if (endpointsForCategory(category.key).length) next.add(category.key)
|
||||
}
|
||||
openCategories.value = next
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -89,13 +118,24 @@ onMounted(() => {
|
||||
:key="category.key"
|
||||
class="mb-4"
|
||||
>
|
||||
<p
|
||||
<button
|
||||
v-if="endpointsForCategory(category.key).length"
|
||||
class="mb-1.5 px-2 text-xs font-medium text-muted"
|
||||
type="button"
|
||||
class="mb-1.5 flex w-full items-center justify-between rounded-md px-2 py-1 text-xs font-medium text-muted transition-colors hover:bg-muted/40 hover:text-highlighted"
|
||||
:aria-expanded="isCategoryOpen(category.key)"
|
||||
@click="toggleCategory(category.key)"
|
||||
>
|
||||
<span>{{ t(category.labelKey) }}</span>
|
||||
<UIcon
|
||||
name="i-lucide-chevron-down"
|
||||
class="size-3.5 transition-transform"
|
||||
:class="isCategoryOpen(category.key) ? '' : '-rotate-90'"
|
||||
/>
|
||||
</button>
|
||||
<ul
|
||||
v-show="isCategoryOpen(category.key)"
|
||||
class="space-y-0.5"
|
||||
>
|
||||
{{ t(category.labelKey) }}
|
||||
</p>
|
||||
<ul class="space-y-0.5">
|
||||
<li
|
||||
v-for="endpoint in endpointsForCategory(category.key)"
|
||||
:key="endpoint.id"
|
||||
|
||||
@@ -75,15 +75,6 @@ async function copyToken() {
|
||||
:description="t('api.envOverrideDesc')"
|
||||
/>
|
||||
|
||||
<UAlert
|
||||
v-else-if="!isAdmin"
|
||||
color="info"
|
||||
variant="subtle"
|
||||
icon="i-lucide-info"
|
||||
:title="t('api.personalTitle')"
|
||||
:description="t('api.personalDesc')"
|
||||
/>
|
||||
|
||||
<UAlert
|
||||
v-else-if="!token && !loading"
|
||||
color="info"
|
||||
|
||||
@@ -5,22 +5,42 @@ const props = withDefaults(defineProps<{
|
||||
storageBackendItems: Array<{ label: string, value: string }>
|
||||
uploadSource: string
|
||||
uploadSourceItems: Array<{ label: string, value: string }>
|
||||
tagIds?: number[]
|
||||
tagMode?: 'or' | 'and'
|
||||
untaggedOnly?: boolean
|
||||
tags?: Array<{ id: number, name: string, color: string, imageCount?: number }>
|
||||
viewMode: 'grid' | 'list'
|
||||
selectedCount?: number
|
||||
loading?: boolean
|
||||
showBatchDelete?: boolean
|
||||
showBatchTags?: boolean
|
||||
showBatchSync?: boolean
|
||||
}>(), {
|
||||
selectedCount: 0,
|
||||
loading: false
|
||||
loading: false,
|
||||
showBatchDelete: true,
|
||||
showBatchTags: false,
|
||||
showBatchSync: false,
|
||||
tagIds: () => [],
|
||||
tags: () => [],
|
||||
tagMode: 'or',
|
||||
untaggedOnly: false
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:searchQuery': [value: string]
|
||||
'update:storageBackend': [value: string]
|
||||
'update:uploadSource': [value: string]
|
||||
'update:tagIds': [value: number[]]
|
||||
'update:tagMode': [value: 'or' | 'and']
|
||||
'update:untaggedOnly': [value: boolean]
|
||||
'update:viewMode': [mode: 'grid' | 'list']
|
||||
'search': []
|
||||
'reset': []
|
||||
'batch-delete': []
|
||||
'batch-tags': []
|
||||
'batch-sync': []
|
||||
'manage-tags': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
@@ -72,6 +92,18 @@ function viewButtonClass(active: boolean) {
|
||||
@update:model-value="emit('update:uploadSource', $event)"
|
||||
/>
|
||||
|
||||
<TagFilterSelect
|
||||
:model-value="tagIds"
|
||||
:tag-mode="tagMode"
|
||||
:untagged-only="untaggedOnly"
|
||||
:tags="tags"
|
||||
:disabled="loading"
|
||||
@update:model-value="emit('update:tagIds', $event)"
|
||||
@update:tag-mode="emit('update:tagMode', $event)"
|
||||
@update:untagged-only="emit('update:untaggedOnly', $event)"
|
||||
@manage="emit('manage-tags')"
|
||||
/>
|
||||
|
||||
<UButton
|
||||
type="submit"
|
||||
icon="i-lucide-search"
|
||||
@@ -99,6 +131,21 @@ function viewButtonClass(active: boolean) {
|
||||
</UButton>
|
||||
|
||||
<UButton
|
||||
v-if="showBatchTags"
|
||||
type="button"
|
||||
icon="i-lucide-tags"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
class="shrink-0"
|
||||
:disabled="!selectedCount || loading"
|
||||
@click="emit('batch-tags')"
|
||||
>
|
||||
{{ t('tags.batchAdd') }}
|
||||
</UButton>
|
||||
|
||||
<UButton
|
||||
v-if="showBatchDelete"
|
||||
type="button"
|
||||
icon="i-lucide-trash-2"
|
||||
size="sm"
|
||||
@@ -111,6 +158,20 @@ function viewButtonClass(active: boolean) {
|
||||
{{ t('stats.batchDelete') }}
|
||||
</UButton>
|
||||
|
||||
<UButton
|
||||
v-if="showBatchSync"
|
||||
type="button"
|
||||
icon="i-lucide-cloud-upload"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
class="shrink-0"
|
||||
:disabled="!selectedCount || loading"
|
||||
@click="emit('batch-sync')"
|
||||
>
|
||||
{{ t('storage.backup.syncSelectedAction') }}
|
||||
</UButton>
|
||||
|
||||
<div
|
||||
class="inline-flex shrink-0 overflow-hidden rounded-md border border-default"
|
||||
role="group"
|
||||
|
||||
@@ -1,26 +1,34 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageItem } from '~/types/image'
|
||||
import type { ImageItem, ImageTag } from '~/types/image'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
items: ImageItem[]
|
||||
selectedKeys: Set<string>
|
||||
selectable?: boolean
|
||||
showStorage?: boolean
|
||||
showTags?: boolean
|
||||
emptyText?: string
|
||||
showDelete?: boolean
|
||||
}>(), {
|
||||
selectable: false,
|
||||
showStorage: false
|
||||
showStorage: false,
|
||||
showTags: false,
|
||||
showDelete: true
|
||||
})
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:selectedKeys': [value: Set<string>]
|
||||
'preview': [image: ImageItem]
|
||||
'delete': [image: ImageItem]
|
||||
'tag-click': [tagId: number]
|
||||
'untagged-click': []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const { formatFileSize } = useFileSize()
|
||||
|
||||
const INLINE_TAG_LIMIT = 3
|
||||
|
||||
const displayEmptyText = computed(() => props.emptyText ?? t('image.empty'))
|
||||
|
||||
const allSelected = computed(() =>
|
||||
@@ -74,10 +82,33 @@ function sourceLabel(image: ImageItem) {
|
||||
}
|
||||
}
|
||||
|
||||
function typeLabel(image: ImageItem) {
|
||||
if (props.showStorage && image.storage) return image.storage.name
|
||||
return '—'
|
||||
function sourceIcon(image: ImageItem) {
|
||||
switch (image.uploadSource) {
|
||||
case 'web':
|
||||
return 'i-lucide-globe'
|
||||
case 'api':
|
||||
return 'i-lucide-code-xml'
|
||||
default:
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function storageIcon(image: ImageItem) {
|
||||
return image.storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
|
||||
}
|
||||
|
||||
function tagDisplay(tags: ImageTag[] | undefined) {
|
||||
const list = tags ?? []
|
||||
if (list.length <= INLINE_TAG_LIMIT) {
|
||||
return { visible: list, hidden: [] as ImageTag[] }
|
||||
}
|
||||
return {
|
||||
visible: list.slice(0, INLINE_TAG_LIMIT),
|
||||
hidden: list.slice(INLINE_TAG_LIMIT)
|
||||
}
|
||||
}
|
||||
|
||||
const metaBadgeClass = 'inline-flex max-w-full items-center gap-1 rounded-md border border-default px-1.5 py-0.5 text-[11px] leading-4 text-muted'
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -86,12 +117,12 @@ function typeLabel(image: ImageItem) {
|
||||
class="overflow-hidden rounded-xl border border-default bg-default"
|
||||
>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="min-w-full text-sm">
|
||||
<thead class="border-b border-default text-xs text-muted">
|
||||
<table class="min-w-full text-xs">
|
||||
<thead class="border-b border-default bg-elevated/40 text-muted">
|
||||
<tr>
|
||||
<th
|
||||
v-if="selectable"
|
||||
class="w-10 px-4 py-3 text-left font-medium"
|
||||
class="w-10 px-3 py-2.5 text-left font-medium"
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="allSelected ? true : headerIndeterminate ? 'indeterminate' : false"
|
||||
@@ -99,22 +130,31 @@ function typeLabel(image: ImageItem) {
|
||||
@update:model-value="toggleAll"
|
||||
/>
|
||||
</th>
|
||||
<th class="min-w-[16rem] px-4 py-3 text-left font-medium">
|
||||
<th class="min-w-[14rem] px-3 py-2.5 text-left font-medium">
|
||||
{{ t('stats.colFilename') }}
|
||||
</th>
|
||||
<th class="hidden w-28 px-4 py-3 text-left font-medium sm:table-cell">
|
||||
<th class="hidden w-24 px-3 py-2.5 text-left font-medium sm:table-cell">
|
||||
{{ t('stats.colSource') }}
|
||||
</th>
|
||||
<th class="w-24 px-4 py-3 text-left font-medium">
|
||||
<th class="w-20 px-3 py-2.5 text-left font-medium">
|
||||
{{ t('stats.colSize') }}
|
||||
</th>
|
||||
<th class="hidden w-32 px-4 py-3 text-left font-medium md:table-cell">
|
||||
<th
|
||||
v-if="showStorage"
|
||||
class="hidden w-28 px-3 py-2.5 text-left font-medium md:table-cell"
|
||||
>
|
||||
{{ t('stats.colType') }}
|
||||
</th>
|
||||
<th class="hidden w-44 px-4 py-3 text-left font-medium lg:table-cell">
|
||||
<th class="hidden w-40 px-3 py-2.5 text-left font-medium lg:table-cell">
|
||||
{{ t('stats.colUploadedAt') }}
|
||||
</th>
|
||||
<th class="w-28 px-4 py-3 text-right font-medium">
|
||||
<th
|
||||
v-if="showTags"
|
||||
class="min-w-[9rem] px-3 py-2.5 text-left font-medium md:table-cell"
|
||||
>
|
||||
{{ t('tags.column') }}
|
||||
</th>
|
||||
<th class="w-24 px-3 py-2.5 text-right font-medium">
|
||||
{{ t('stats.colActions') }}
|
||||
</th>
|
||||
</tr>
|
||||
@@ -123,22 +163,23 @@ function typeLabel(image: ImageItem) {
|
||||
<tr
|
||||
v-for="image in items"
|
||||
:key="image.key"
|
||||
class="transition-colors hover:bg-muted/20"
|
||||
class="transition-colors hover:bg-elevated/50"
|
||||
:class="selectedKeys.has(image.key) ? 'bg-primary/5' : ''"
|
||||
>
|
||||
<td
|
||||
v-if="selectable"
|
||||
class="px-4 py-3"
|
||||
class="px-3 py-2"
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="selectedKeys.has(image.key)"
|
||||
@update:model-value="updateSelection(image.key, $event === true)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-4 py-3">
|
||||
<td class="px-3 py-2.5">
|
||||
<div class="flex min-w-0 items-center gap-3">
|
||||
<button
|
||||
type="button"
|
||||
class="relative size-10 shrink-0 overflow-hidden rounded-md border border-default bg-muted"
|
||||
class="relative size-12 shrink-0 overflow-hidden rounded-md border border-default bg-muted"
|
||||
:aria-label="t('image.openPreview')"
|
||||
@click="emit('preview', image)"
|
||||
>
|
||||
@@ -150,35 +191,108 @@ function typeLabel(image: ImageItem) {
|
||||
>
|
||||
</button>
|
||||
<p
|
||||
class="min-w-0 flex-1 truncate font-medium"
|
||||
class="min-w-0 flex-1 truncate text-highlighted"
|
||||
:title="image.originalName"
|
||||
>
|
||||
{{ image.originalName }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
<td class="hidden px-4 py-3 sm:table-cell">
|
||||
<td class="hidden px-3 py-2 sm:table-cell">
|
||||
<span
|
||||
v-if="sourceLabel(image)"
|
||||
class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary"
|
||||
v-if="sourceLabel(image) && sourceIcon(image)"
|
||||
:class="metaBadgeClass"
|
||||
>
|
||||
{{ sourceLabel(image) }}
|
||||
<UIcon
|
||||
:name="sourceIcon(image)!"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ sourceLabel(image) }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted"
|
||||
>—</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-muted">
|
||||
<td class="px-3 py-2 tabular-nums text-muted">
|
||||
{{ formatFileSize(image.size) }}
|
||||
</td>
|
||||
<td class="hidden px-4 py-3 text-muted md:table-cell">
|
||||
<span class="truncate">{{ typeLabel(image) }}</span>
|
||||
<td
|
||||
v-if="showStorage"
|
||||
class="hidden px-3 py-2 md:table-cell"
|
||||
>
|
||||
<span
|
||||
v-if="image.storage"
|
||||
:class="metaBadgeClass"
|
||||
:title="image.storage.name"
|
||||
>
|
||||
<UIcon
|
||||
:name="storageIcon(image)"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
<span class="truncate">{{ image.storage.name }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted"
|
||||
>—</span>
|
||||
</td>
|
||||
<td class="hidden px-4 py-3 text-muted lg:table-cell">
|
||||
<td class="hidden px-3 py-2 tabular-nums text-muted lg:table-cell">
|
||||
{{ formatUploadedAt(image.uploadedAt) }}
|
||||
</td>
|
||||
<td class="px-4 py-3">
|
||||
<td
|
||||
v-if="showTags"
|
||||
class="px-3 py-2 md:table-cell"
|
||||
>
|
||||
<div
|
||||
v-if="image.tags?.length"
|
||||
class="flex flex-wrap items-center gap-1"
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in tagDisplay(image.tags).visible"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
clickable
|
||||
@click="emit('tag-click', tag.id)"
|
||||
/>
|
||||
<UPopover
|
||||
v-if="tagDisplay(image.tags).hidden.length"
|
||||
:content="{ side: 'bottom', align: 'start' }"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex rounded-md border border-default px-1.5 py-0.5 text-[11px] text-muted transition-colors hover:border-primary/40 hover:text-primary"
|
||||
:aria-label="t('tags.moreTags', { n: tagDisplay(image.tags).hidden.length })"
|
||||
@click.stop
|
||||
>
|
||||
+{{ tagDisplay(image.tags).hidden.length }}
|
||||
</button>
|
||||
<template #content>
|
||||
<div
|
||||
class="flex max-w-56 flex-wrap gap-1 p-2"
|
||||
@click.stop
|
||||
>
|
||||
<TagBadge
|
||||
v-for="tag in tagDisplay(image.tags).hidden"
|
||||
:key="tag.id"
|
||||
:tag="tag"
|
||||
clickable
|
||||
@click="emit('tag-click', tag.id)"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UPopover>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="rounded-md border border-dashed border-default px-1.5 py-0.5 text-[11px] text-muted transition-colors hover:border-primary/40 hover:text-primary"
|
||||
@click.stop="emit('untagged-click')"
|
||||
>
|
||||
{{ t('tags.unlabeled') }}
|
||||
</button>
|
||||
</td>
|
||||
<td class="px-3 py-2">
|
||||
<div class="flex items-center justify-end gap-0.5 text-muted">
|
||||
<CopyButton
|
||||
icon="i-lucide-link"
|
||||
@@ -198,6 +312,7 @@ function typeLabel(image: ImageItem) {
|
||||
@click="emit('preview', image)"
|
||||
/>
|
||||
<UButton
|
||||
v-if="showDelete"
|
||||
icon="i-lucide-trash-2"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
@@ -214,7 +329,7 @@ function typeLabel(image: ImageItem) {
|
||||
</div>
|
||||
<div
|
||||
v-else
|
||||
class="rounded-xl border border-dashed border-default py-16 text-center text-sm text-muted"
|
||||
class="rounded-xl border border-dashed border-default py-16 text-center text-xs text-muted"
|
||||
>
|
||||
{{ displayEmptyText }}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
currentOrigin: string
|
||||
effectiveSiteUrl: string
|
||||
}>()
|
||||
|
||||
const siteBaseUrl = defineModel<string>('siteBaseUrl', { required: true })
|
||||
const imageBaseUrl = defineModel<string>('imageBaseUrl', { required: true })
|
||||
const videoBaseUrl = defineModel<string>('videoBaseUrl', { required: true })
|
||||
const fileBaseUrl = defineModel<string>('fileBaseUrl', { required: true })
|
||||
const imageSeparated = defineModel<boolean>('imageSeparated', { required: true })
|
||||
const videoSeparated = defineModel<boolean>('videoSeparated', { required: true })
|
||||
const fileSeparated = defineModel<boolean>('fileSeparated', { required: true })
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
function fillDetected(target: 'site' | 'image' | 'video' | 'file') {
|
||||
if (!props.currentOrigin) return
|
||||
if (target === 'site') siteBaseUrl.value = props.currentOrigin
|
||||
else if (target === 'image') imageBaseUrl.value = props.currentOrigin
|
||||
else if (target === 'video') videoBaseUrl.value = props.currentOrigin
|
||||
else fileBaseUrl.value = props.currentOrigin
|
||||
}
|
||||
|
||||
function effectiveUrl(separated: boolean, configuredUrl: string): string {
|
||||
return separated
|
||||
? configuredUrl.trim() || props.currentOrigin
|
||||
: siteBaseUrl.value.trim() || props.effectiveSiteUrl || props.currentOrigin
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid gap-4 sm:grid-cols-2">
|
||||
<SettingsGroup>
|
||||
<div class="space-y-3 py-4 sm:pr-4">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.siteBaseUrl') }}
|
||||
</p>
|
||||
<p class="text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.siteBaseUrlRoleHint') }}
|
||||
</p>
|
||||
<div class="flex gap-2">
|
||||
<UInput
|
||||
v-model="siteBaseUrl"
|
||||
size="sm"
|
||||
:placeholder="t('settings.siteBaseUrlPlaceholder')"
|
||||
class="min-w-0 flex-1 font-mono"
|
||||
/>
|
||||
<UButton
|
||||
v-if="currentOrigin"
|
||||
:label="t('settings.fillDetectedOrigin')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="shrink-0"
|
||||
@click="fillDetected('site')"
|
||||
/>
|
||||
</div>
|
||||
<p class="truncate rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted">
|
||||
{{ t('settings.siteBaseUrlActive', { url: effectiveSiteUrl || currentOrigin }) }}
|
||||
</p>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup>
|
||||
<div class="space-y-3 py-4 sm:pl-4">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.imageBaseUrl') }}
|
||||
</p>
|
||||
<USwitch v-model="imageSeparated" />
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.imageBaseUrlRoleHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="flex gap-2"
|
||||
:class="imageSeparated ? '' : 'pointer-events-none opacity-50'"
|
||||
>
|
||||
<UInput
|
||||
v-model="imageBaseUrl"
|
||||
size="sm"
|
||||
:placeholder="t('settings.imageBaseUrlPlaceholder')"
|
||||
class="min-w-0 flex-1 font-mono"
|
||||
/>
|
||||
<UButton
|
||||
v-if="currentOrigin"
|
||||
:label="t('settings.fillDetectedOrigin')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="shrink-0"
|
||||
@click="fillDetected('image')"
|
||||
/>
|
||||
</div>
|
||||
<p class="truncate rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted">
|
||||
{{ t('settings.imageBaseUrlActive', {
|
||||
url: effectiveUrl(imageSeparated, imageBaseUrl)
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup>
|
||||
<div class="space-y-3 py-4 sm:pr-4">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.videoBaseUrl') }}
|
||||
</p>
|
||||
<USwitch v-model="videoSeparated" />
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.videoBaseUrlRoleHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="flex gap-2"
|
||||
:class="videoSeparated ? '' : 'pointer-events-none opacity-50'"
|
||||
>
|
||||
<UInput
|
||||
v-model="videoBaseUrl"
|
||||
size="sm"
|
||||
:placeholder="t('settings.videoBaseUrlPlaceholder')"
|
||||
class="min-w-0 flex-1 font-mono"
|
||||
/>
|
||||
<UButton
|
||||
v-if="currentOrigin"
|
||||
:label="t('settings.fillDetectedOrigin')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="shrink-0"
|
||||
@click="fillDetected('video')"
|
||||
/>
|
||||
</div>
|
||||
<p class="truncate rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted">
|
||||
{{ t('settings.videoBaseUrlActive', {
|
||||
url: effectiveUrl(videoSeparated, videoBaseUrl)
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
|
||||
<SettingsGroup>
|
||||
<div class="space-y-3 py-4 sm:pl-4">
|
||||
<div class="flex flex-wrap items-center justify-between gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.fileBaseUrl') }}
|
||||
</p>
|
||||
<USwitch v-model="fileSeparated" />
|
||||
</div>
|
||||
<p class="text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.fileBaseUrlRoleHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="flex gap-2"
|
||||
:class="fileSeparated ? '' : 'pointer-events-none opacity-50'"
|
||||
>
|
||||
<UInput
|
||||
v-model="fileBaseUrl"
|
||||
size="sm"
|
||||
:placeholder="t('settings.fileBaseUrlPlaceholder')"
|
||||
class="min-w-0 flex-1 font-mono"
|
||||
/>
|
||||
<UButton
|
||||
v-if="currentOrigin"
|
||||
:label="t('settings.fillDetectedOrigin')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="shrink-0"
|
||||
@click="fillDetected('file')"
|
||||
/>
|
||||
</div>
|
||||
<p class="truncate rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted">
|
||||
{{ t('settings.fileBaseUrlActive', {
|
||||
url: effectiveUrl(fileSeparated, fileBaseUrl)
|
||||
}) }}
|
||||
</p>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div class="divide-y divide-default overflow-hidden rounded-lg border border-default">
|
||||
<div class="divide-y divide-default">
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import type { ActivityLogListResponse, ActivityLogStorage, LogAction, LogSource } from '~/types/logs'
|
||||
import type { ActivityLogListResponse, LogAction, LogSource, LogStatus } from '~/types/logs'
|
||||
|
||||
const { isAuthenticated, handleAuthError, isAdmin } = useAuth()
|
||||
const toast = useToast()
|
||||
@@ -8,36 +8,30 @@ const { formatFileSize } = useFileSize()
|
||||
|
||||
const loading = ref(true)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
const actionFilter = ref<'all' | LogAction>('all')
|
||||
const sourceFilter = ref<'all' | LogSource>('all')
|
||||
const userFilter = ref<'all' | number>('all')
|
||||
const dateFrom = ref('')
|
||||
const dateTo = ref('')
|
||||
const searchQuery = ref('')
|
||||
const activeSearch = ref('')
|
||||
const listData = ref<ActivityLogListResponse | null>(null)
|
||||
const imageLinkBase = ref('')
|
||||
const hideFolderInUrl = ref(false)
|
||||
|
||||
const pageSize = 10
|
||||
|
||||
const summaryLabel = computed(() => {
|
||||
const summary = listData.value?.summary
|
||||
if (!summary) return ''
|
||||
return t('logs.summaryAll', {
|
||||
total: summary.total,
|
||||
upload: summary.upload,
|
||||
delete: summary.delete
|
||||
})
|
||||
})
|
||||
|
||||
const actionItems = computed(() => [
|
||||
{ label: t('logs.filterActionAll'), value: 'all' as const },
|
||||
{ label: t('logs.actionUpload'), value: 'upload' as const },
|
||||
{ label: t('logs.actionDelete'), value: 'delete' as const }
|
||||
{ label: t('logs.actionDelete'), value: 'delete' as const },
|
||||
{ label: t('logs.actionLogin'), value: 'login' as const },
|
||||
{ label: t('logs.actionEdit'), value: 'edit' as const },
|
||||
{ label: t('logs.actionSettings'), value: 'settings' as const },
|
||||
{ label: t('logs.actionTags'), value: 'tags' as const }
|
||||
])
|
||||
|
||||
const sourceItems = computed(() => [
|
||||
{ label: t('logs.filterSourceAll'), value: 'all' as const },
|
||||
{ label: t('logs.sourceWeb'), value: 'web' as const },
|
||||
{ label: t('logs.sourceAdmin'), value: 'admin' as const },
|
||||
{ label: t('logs.sourceApi'), value: 'api' as const }
|
||||
])
|
||||
|
||||
@@ -73,66 +67,104 @@ function formatTimeShort(value: string) {
|
||||
}
|
||||
}
|
||||
|
||||
function actionLabel(action: LogAction) {
|
||||
const labels: Record<LogAction, string> = {
|
||||
upload: t('logs.actionUpload'),
|
||||
delete: t('logs.actionDelete'),
|
||||
login: t('logs.actionLogin'),
|
||||
edit: t('logs.actionEdit'),
|
||||
settings: t('logs.actionSettings'),
|
||||
tags: t('logs.actionTags')
|
||||
}
|
||||
return labels[action]
|
||||
}
|
||||
|
||||
function actionBadgeClass(action: LogAction) {
|
||||
const base = 'inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs font-medium whitespace-nowrap'
|
||||
return action === 'upload'
|
||||
? `${base} bg-success/10 text-success`
|
||||
: `${base} bg-error/10 text-error`
|
||||
switch (action) {
|
||||
case 'upload':
|
||||
return `${base} bg-success/10 text-success`
|
||||
case 'delete':
|
||||
return `${base} bg-error/10 text-error`
|
||||
case 'login':
|
||||
return `${base} bg-sky-500/10 text-sky-600 dark:text-sky-400`
|
||||
case 'edit':
|
||||
return `${base} bg-blue-500/10 text-blue-600 dark:text-blue-400`
|
||||
case 'settings':
|
||||
return `${base} bg-slate-500/10 text-slate-600 dark:text-slate-400`
|
||||
case 'tags':
|
||||
return `${base} bg-violet-500/10 text-violet-600 dark:text-violet-400`
|
||||
}
|
||||
}
|
||||
|
||||
function actionIcon(action: LogAction) {
|
||||
return action === 'upload' ? 'i-lucide-upload' : 'i-lucide-trash-2'
|
||||
switch (action) {
|
||||
case 'upload':
|
||||
return 'i-lucide-upload'
|
||||
case 'delete':
|
||||
return 'i-lucide-trash-2'
|
||||
case 'login':
|
||||
return 'i-lucide-log-in'
|
||||
case 'edit':
|
||||
return 'i-lucide-pencil'
|
||||
case 'settings':
|
||||
return 'i-lucide-settings'
|
||||
case 'tags':
|
||||
return 'i-lucide-tag'
|
||||
}
|
||||
}
|
||||
|
||||
function sourceIcon(source: LogSource) {
|
||||
switch (source) {
|
||||
case 'web':
|
||||
return 'i-lucide-monitor'
|
||||
case 'admin':
|
||||
return 'i-lucide-layout-dashboard'
|
||||
case 'api':
|
||||
return 'i-lucide-code-2'
|
||||
}
|
||||
}
|
||||
|
||||
function sourceLabel(source: LogSource) {
|
||||
switch (source) {
|
||||
case 'web':
|
||||
return t('logs.sourceWeb')
|
||||
case 'admin':
|
||||
return t('logs.sourceAdmin')
|
||||
case 'api':
|
||||
return t('logs.sourceApi')
|
||||
}
|
||||
}
|
||||
|
||||
function storageIcon(storage: ActivityLogStorage | null) {
|
||||
return storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
|
||||
function sourceBadgeClass(source: LogSource) {
|
||||
const base = 'inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs font-medium whitespace-nowrap'
|
||||
switch (source) {
|
||||
case 'web':
|
||||
return `${base} bg-primary/10 text-primary`
|
||||
case 'admin':
|
||||
return `${base} bg-orange-500/10 text-orange-600 dark:text-orange-400`
|
||||
case 'api':
|
||||
return `${base} bg-violet-500/10 text-violet-600 dark:text-violet-400`
|
||||
}
|
||||
}
|
||||
|
||||
function publicPathFromKey(key: string) {
|
||||
if (hideFolderInUrl.value) {
|
||||
const slash = key.lastIndexOf('/')
|
||||
return slash >= 0 ? key.slice(slash + 1) : key
|
||||
}
|
||||
const prefix = 'images/'
|
||||
return key.startsWith(prefix) ? key.slice(prefix.length) : key
|
||||
function statusLabel(status: LogStatus) {
|
||||
return status === 'failure' ? t('logs.resultFailure') : t('logs.resultSuccess')
|
||||
}
|
||||
|
||||
function imageUrl(key: string) {
|
||||
const base = imageLinkBase.value.replace(/\/$/, '')
|
||||
const path = publicPathFromKey(key)
|
||||
if (!base) return `/${path}`
|
||||
return `${base}/${path}`
|
||||
function statusDotClass(status: LogStatus) {
|
||||
return status === 'failure' ? 'bg-error' : 'bg-success'
|
||||
}
|
||||
|
||||
async function loadImageLinkBase() {
|
||||
try {
|
||||
if (isAdmin.value) {
|
||||
const data = await $fetch<{ effectiveImageBaseUrl: string, hideFolderInUrl: boolean }>('/api/settings', {
|
||||
credentials: 'include'
|
||||
})
|
||||
imageLinkBase.value = data.effectiveImageBaseUrl
|
||||
hideFolderInUrl.value = data.hideFolderInUrl
|
||||
return
|
||||
}
|
||||
const data = await $fetch<{ env: { imageBaseUrl: string, hideFolderInUrl: boolean } }>('/api/user/api-token', {
|
||||
credentials: 'include'
|
||||
})
|
||||
imageLinkBase.value = data.env.imageBaseUrl
|
||||
hideFolderInUrl.value = data.env.hideFolderInUrl
|
||||
} catch {
|
||||
if (import.meta.client) {
|
||||
imageLinkBase.value = window.location.origin
|
||||
}
|
||||
}
|
||||
function formatIp(value: string | null) {
|
||||
if (!value || value === '-') return '—'
|
||||
return value
|
||||
}
|
||||
|
||||
function formatSize(action: LogAction, size: number) {
|
||||
if (action !== 'upload' && action !== 'delete') return '—'
|
||||
if (action === 'delete' && size <= 0) return '—'
|
||||
return formatFileSize(size)
|
||||
}
|
||||
|
||||
async function loadLogs() {
|
||||
@@ -140,7 +172,7 @@ async function loadLogs() {
|
||||
try {
|
||||
const query: Record<string, string | number> = {
|
||||
page: page.value,
|
||||
limit: pageSize
|
||||
limit: pageSize.value
|
||||
}
|
||||
if (actionFilter.value !== 'all') {
|
||||
query.action = actionFilter.value
|
||||
@@ -154,6 +186,12 @@ async function loadLogs() {
|
||||
if (activeSearch.value) {
|
||||
query.q = activeSearch.value
|
||||
}
|
||||
if (dateFrom.value) {
|
||||
query.from = dateFrom.value
|
||||
}
|
||||
if (dateTo.value) {
|
||||
query.to = dateTo.value
|
||||
}
|
||||
|
||||
listData.value = await $fetch<ActivityLogListResponse>('/api/logs', {
|
||||
credentials: 'include',
|
||||
@@ -191,21 +229,32 @@ function handlePageChange(target: number) {
|
||||
void loadLogs()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadImageLinkBase()
|
||||
await loadLogs()
|
||||
function handlePageSizeChange(size: number) {
|
||||
pageSize.value = size
|
||||
page.value = 1
|
||||
void loadLogs()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadLogs()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-w-0">
|
||||
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default px-5 py-4 sm:px-6">
|
||||
<div>
|
||||
<h2 class="text-sm font-semibold">
|
||||
<div class="mb-6 flex items-start justify-between gap-4">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<span
|
||||
class="h-4 w-1 shrink-0 rounded-full bg-primary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<h2 class="text-sm font-semibold text-highlighted">
|
||||
{{ t('logs.pageTitle') }}
|
||||
</h2>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ isAdmin ? t('logs.pageSubtitleAdmin') : t('logs.pageSubtitle') }}
|
||||
</div>
|
||||
<p class="mt-1.5 pl-3 text-xs leading-relaxed text-muted">
|
||||
{{ isAdmin ? t('settings.pageSubtitleLogs') : t('logs.pageSubtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<UButton
|
||||
@@ -215,35 +264,45 @@ onMounted(async () => {
|
||||
size="sm"
|
||||
:label="t('common.refresh')"
|
||||
:loading="loading"
|
||||
class="shrink-0"
|
||||
@click="loadLogs"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<form
|
||||
class="border-b border-default px-5 py-3 sm:px-6"
|
||||
class="mb-4 flex flex-col gap-3"
|
||||
@submit.prevent="submitSearch"
|
||||
>
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<p
|
||||
v-if="summaryLabel"
|
||||
class="text-xs text-muted"
|
||||
>
|
||||
{{ summaryLabel }}
|
||||
</p>
|
||||
<p
|
||||
v-else
|
||||
class="text-xs text-muted"
|
||||
>
|
||||
{{ t('stats.counting') }}
|
||||
</p>
|
||||
<div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<UInput
|
||||
v-model="dateFrom"
|
||||
type="date"
|
||||
size="sm"
|
||||
class="min-w-0 w-full sm:w-36"
|
||||
:aria-label="t('logs.dateFrom')"
|
||||
:disabled="loading"
|
||||
@change="applyFilters"
|
||||
/>
|
||||
<span class="hidden text-xs text-muted sm:inline">{{ t('logs.dateRangeSeparator') }}</span>
|
||||
<UInput
|
||||
v-model="dateTo"
|
||||
type="date"
|
||||
size="sm"
|
||||
class="min-w-0 w-full sm:w-36"
|
||||
:aria-label="t('logs.dateTo')"
|
||||
:disabled="loading"
|
||||
@change="applyFilters"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-2 sm:justify-end">
|
||||
<div class="flex min-w-0 flex-wrap items-center gap-2 xl:justify-end">
|
||||
<USelect
|
||||
v-if="isAdmin"
|
||||
v-model="userFilter"
|
||||
:items="userItems"
|
||||
value-key="value"
|
||||
class="min-w-0 w-full sm:w-36"
|
||||
class="min-w-0 w-full sm:w-32"
|
||||
size="sm"
|
||||
@update:model-value="applyFilters"
|
||||
/>
|
||||
@@ -251,7 +310,7 @@ onMounted(async () => {
|
||||
v-model="actionFilter"
|
||||
:items="actionItems"
|
||||
value-key="value"
|
||||
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-32"
|
||||
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-28"
|
||||
size="sm"
|
||||
@update:model-value="applyFilters"
|
||||
/>
|
||||
@@ -259,7 +318,7 @@ onMounted(async () => {
|
||||
v-model="sourceFilter"
|
||||
:items="sourceItems"
|
||||
value-key="value"
|
||||
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-36"
|
||||
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-28"
|
||||
size="sm"
|
||||
@update:model-value="applyFilters"
|
||||
/>
|
||||
@@ -268,19 +327,17 @@ onMounted(async () => {
|
||||
v-model="searchQuery"
|
||||
icon="i-lucide-search"
|
||||
:placeholder="t('logs.searchPlaceholder')"
|
||||
class="min-w-0 flex-1 sm:w-40 sm:flex-none"
|
||||
class="min-w-0 flex-1 sm:w-44 sm:flex-none"
|
||||
size="sm"
|
||||
:disabled="loading"
|
||||
/>
|
||||
<UButton
|
||||
type="submit"
|
||||
icon="i-lucide-search"
|
||||
size="sm"
|
||||
class="shrink-0"
|
||||
:aria-label="t('common.search')"
|
||||
:loading="loading"
|
||||
>
|
||||
<span class="hidden sm:inline">{{ t('common.search') }}</span>
|
||||
{{ t('common.search') }}
|
||||
</UButton>
|
||||
<UButton
|
||||
v-if="activeSearch"
|
||||
@@ -292,14 +349,13 @@ onMounted(async () => {
|
||||
class="shrink-0"
|
||||
:aria-label="t('stats.clear')"
|
||||
@click="clearSearch"
|
||||
>
|
||||
<span class="hidden sm:inline">{{ t('stats.clear') }}</span>
|
||||
</UButton>
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="overflow-hidden rounded-xl border border-default bg-default">
|
||||
<div
|
||||
v-if="loading"
|
||||
class="p-4 sm:p-6"
|
||||
@@ -333,7 +389,7 @@ onMounted(async () => {
|
||||
{{ formatTimeShort(row.createdAt) }}
|
||||
</time>
|
||||
<span class="shrink-0 text-xs tabular-nums text-muted">
|
||||
{{ formatFileSize(row.size) }}
|
||||
{{ formatSize(row.action, row.size) }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -343,9 +399,13 @@ onMounted(async () => {
|
||||
:name="actionIcon(row.action)"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }}
|
||||
{{ actionLabel(row.action) }}
|
||||
</span>
|
||||
<span class="inline-flex items-center rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary whitespace-nowrap">
|
||||
<span :class="sourceBadgeClass(row.source)">
|
||||
<UIcon
|
||||
:name="sourceIcon(row.source)"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ sourceLabel(row.source) }}
|
||||
</span>
|
||||
<span
|
||||
@@ -354,19 +414,6 @@ onMounted(async () => {
|
||||
>
|
||||
{{ row.username ?? '—' }}
|
||||
</span>
|
||||
<UBadge
|
||||
v-if="row.storage"
|
||||
color="neutral"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
class="max-w-full truncate"
|
||||
>
|
||||
<UIcon
|
||||
:name="storageIcon(row.storage)"
|
||||
class="mr-1 size-3"
|
||||
/>
|
||||
{{ row.storage.name }}
|
||||
</UBadge>
|
||||
</div>
|
||||
|
||||
<p
|
||||
@@ -376,67 +423,50 @@ onMounted(async () => {
|
||||
{{ row.originalName }}
|
||||
</p>
|
||||
|
||||
<div class="mt-2 flex min-w-0 items-center gap-1">
|
||||
<a
|
||||
v-if="row.action === 'upload'"
|
||||
:href="imageUrl(row.key)"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="min-w-0 flex-1 truncate font-mono text-xs text-primary hover:underline"
|
||||
:title="row.key"
|
||||
>
|
||||
{{ row.key }}
|
||||
</a>
|
||||
<div class="mt-2 flex items-center justify-between gap-2 text-xs text-muted">
|
||||
<span>{{ formatIp(row.ipAddress) }}</span>
|
||||
<span class="inline-flex items-center gap-1.5">
|
||||
<span
|
||||
v-else
|
||||
class="min-w-0 flex-1 truncate font-mono text-xs text-dimmed"
|
||||
:title="row.key"
|
||||
>
|
||||
{{ row.key }}
|
||||
</span>
|
||||
<CopyButton
|
||||
icon="i-lucide-copy"
|
||||
icon-only
|
||||
class="shrink-0"
|
||||
:label="t('common.copy')"
|
||||
:value="row.key"
|
||||
:success-title="t('copy.copiedUrl')"
|
||||
class="size-1.5 rounded-full"
|
||||
:class="statusDotClass(row.status)"
|
||||
/>
|
||||
{{ statusLabel(row.status) }}
|
||||
</span>
|
||||
</div>
|
||||
</article>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="hidden min-w-0 sm:block">
|
||||
<table class="w-full table-fixed text-left text-sm">
|
||||
<div class="hidden min-w-0 overflow-x-auto sm:block">
|
||||
<table class="w-full min-w-[56rem] text-left text-sm">
|
||||
<thead class="border-b border-default bg-muted/30 text-xs text-muted">
|
||||
<tr>
|
||||
<th class="w-36 px-4 py-3 font-medium sm:px-6">
|
||||
<th class="whitespace-nowrap px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('logs.colTime') }}
|
||||
</th>
|
||||
<th
|
||||
v-if="isAdmin"
|
||||
class="w-20 px-4 py-3 font-medium"
|
||||
class="whitespace-nowrap px-4 py-3 font-medium"
|
||||
>
|
||||
{{ t('logs.colUser') }}
|
||||
</th>
|
||||
<th class="w-20 whitespace-nowrap px-4 py-3 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-3 font-medium">
|
||||
{{ t('logs.colAction') }}
|
||||
</th>
|
||||
<th class="w-16 whitespace-nowrap px-4 py-3 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-3 font-medium">
|
||||
{{ t('logs.colSource') }}
|
||||
</th>
|
||||
<th class="w-24 px-4 py-3 font-medium">
|
||||
{{ t('logs.colStorage') }}
|
||||
</th>
|
||||
<th class="hidden px-4 py-3 font-medium md:table-cell">
|
||||
<th class="px-4 py-3 font-medium">
|
||||
{{ t('logs.colFile') }}
|
||||
</th>
|
||||
<th class="w-20 px-4 py-3 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-3 font-medium">
|
||||
{{ t('logs.colSize') }}
|
||||
</th>
|
||||
<th class="hidden px-4 py-3 font-medium xl:table-cell">
|
||||
{{ t('logs.colKey') }}
|
||||
<th class="whitespace-nowrap px-4 py-3 font-medium">
|
||||
{{ t('logs.colIp') }}
|
||||
</th>
|
||||
<th class="whitespace-nowrap px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('logs.colResult') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -446,14 +476,14 @@ onMounted(async () => {
|
||||
:key="row.id"
|
||||
class="hover:bg-muted/20"
|
||||
>
|
||||
<td class="px-4 py-3 text-xs text-muted sm:px-6">
|
||||
<span class="block truncate">{{ formatTime(row.createdAt) }}</span>
|
||||
<td class="whitespace-nowrap px-4 py-3 text-xs text-muted sm:px-5">
|
||||
{{ formatTime(row.createdAt) }}
|
||||
</td>
|
||||
<td
|
||||
v-if="isAdmin"
|
||||
class="px-4 py-3 text-xs"
|
||||
class="whitespace-nowrap px-4 py-3 text-xs"
|
||||
>
|
||||
<span class="block truncate">{{ row.username ?? '—' }}</span>
|
||||
{{ row.username ?? '—' }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-4 py-3">
|
||||
<span :class="actionBadgeClass(row.action)">
|
||||
@@ -461,68 +491,38 @@ onMounted(async () => {
|
||||
:name="actionIcon(row.action)"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }}
|
||||
{{ actionLabel(row.action) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-4 py-3">
|
||||
<span class="inline-flex items-center rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
|
||||
<span :class="sourceBadgeClass(row.source)">
|
||||
<UIcon
|
||||
:name="sourceIcon(row.source)"
|
||||
class="size-3 shrink-0"
|
||||
/>
|
||||
{{ sourceLabel(row.source) }}
|
||||
</span>
|
||||
</td>
|
||||
<td class="px-4 py-3 text-xs">
|
||||
<span
|
||||
v-if="row.storage"
|
||||
class="flex min-w-0 items-center gap-1"
|
||||
:title="row.storage.name"
|
||||
>
|
||||
<UIcon
|
||||
:name="storageIcon(row.storage)"
|
||||
class="size-3.5 shrink-0 opacity-70"
|
||||
/>
|
||||
<span class="truncate">{{ row.storage.name }}</span>
|
||||
</span>
|
||||
<span
|
||||
v-else
|
||||
class="text-muted"
|
||||
>—</span>
|
||||
</td>
|
||||
<td
|
||||
class="hidden max-w-0 truncate px-4 py-3 md:table-cell"
|
||||
class="max-w-[12rem] truncate px-4 py-3"
|
||||
:title="row.originalName"
|
||||
>
|
||||
{{ row.originalName }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-4 py-3 tabular-nums text-muted">
|
||||
{{ formatFileSize(row.size) }}
|
||||
{{ formatSize(row.action, row.size) }}
|
||||
</td>
|
||||
<td class="hidden max-w-0 px-4 py-3 xl:table-cell">
|
||||
<div class="flex min-w-0 items-center gap-1">
|
||||
<a
|
||||
v-if="row.action === 'upload'"
|
||||
:href="imageUrl(row.key)"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="min-w-0 truncate font-mono text-xs text-primary hover:underline"
|
||||
:title="row.key"
|
||||
>
|
||||
{{ row.key }}
|
||||
</a>
|
||||
<td class="whitespace-nowrap px-4 py-3 font-mono text-xs text-muted">
|
||||
{{ formatIp(row.ipAddress) }}
|
||||
</td>
|
||||
<td class="whitespace-nowrap px-4 py-3 sm:px-5">
|
||||
<span class="inline-flex items-center gap-1.5 text-xs">
|
||||
<span
|
||||
v-else
|
||||
class="min-w-0 truncate font-mono text-xs text-dimmed"
|
||||
:title="row.key"
|
||||
>
|
||||
{{ row.key }}
|
||||
</span>
|
||||
<CopyButton
|
||||
icon="i-lucide-copy"
|
||||
icon-only
|
||||
class="shrink-0"
|
||||
:label="t('common.copy')"
|
||||
:value="row.key"
|
||||
:success-title="t('copy.copiedUrl')"
|
||||
class="size-1.5 rounded-full"
|
||||
:class="statusDotClass(row.status)"
|
||||
/>
|
||||
</div>
|
||||
{{ statusLabel(row.status) }}
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
@@ -539,16 +539,19 @@ onMounted(async () => {
|
||||
|
||||
<div
|
||||
v-if="listData && listData.total > 0"
|
||||
class="border-t border-default px-4 py-4 sm:px-6"
|
||||
class="border-t border-default px-4 py-4 sm:px-5"
|
||||
>
|
||||
<PaginationBar
|
||||
:page="listData.page"
|
||||
:total-pages="listData.totalPages"
|
||||
:total="listData.total"
|
||||
:unit="t('logs.entriesUnit')"
|
||||
:page-size="pageSize"
|
||||
:loading="loading"
|
||||
@update:page="handlePageChange"
|
||||
@update:page-size="handlePageSizeChange"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,29 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
icon: string
|
||||
title: string
|
||||
subtitle?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="mb-0 flex items-start gap-3 border-b border-default pb-6">
|
||||
<div class="flex size-10 shrink-0 items-center justify-center rounded-xl bg-primary/10">
|
||||
<UIcon
|
||||
:name="icon"
|
||||
class="size-5 text-primary"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0 pt-0.5">
|
||||
<h1 class="text-lg font-semibold tracking-tight text-highlighted">
|
||||
{{ title }}
|
||||
</h1>
|
||||
<p
|
||||
v-if="subtitle"
|
||||
class="mt-1 text-xs leading-relaxed text-muted"
|
||||
>
|
||||
{{ subtitle }}
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
@@ -1,7 +1,5 @@
|
||||
<template>
|
||||
<div class="overflow-hidden rounded-xl border border-default bg-default p-5 sm:p-6">
|
||||
<div class="space-y-8">
|
||||
<div class="mt-6 space-y-4">
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
defineProps<{
|
||||
title: string
|
||||
hint?: string
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="overflow-hidden rounded-xl border border-default bg-default">
|
||||
<div class="px-4 py-3">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<h2 class="text-sm font-semibold text-highlighted">
|
||||
{{ title }}
|
||||
</h2>
|
||||
<slot name="badge" />
|
||||
</div>
|
||||
<p
|
||||
v-if="hint"
|
||||
class="mt-1 text-xs leading-relaxed text-muted"
|
||||
>
|
||||
{{ hint }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="border-t border-default px-4 py-4">
|
||||
<slot />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,41 @@
|
||||
<script setup lang="ts">
|
||||
export type SettingsRadioOption = {
|
||||
value: string
|
||||
label: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
defineProps<{
|
||||
items: SettingsRadioOption[]
|
||||
}>()
|
||||
|
||||
const model = defineModel<string>({ required: true })
|
||||
|
||||
const radioUi = {
|
||||
fieldset: 'flex flex-col divide-y divide-default',
|
||||
item: 'flex items-start gap-4 py-4',
|
||||
wrapper: 'min-w-0 flex-1 pr-2',
|
||||
base: 'mt-0.5 shrink-0',
|
||||
label: 'block text-sm font-medium text-highlighted',
|
||||
description: 'mt-1 block text-xs leading-relaxed text-muted'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<URadioGroup
|
||||
v-model="model"
|
||||
:items="items"
|
||||
variant="list"
|
||||
:ui="radioUi"
|
||||
>
|
||||
<template #label="{ item }">
|
||||
<span class="text-sm font-medium text-highlighted">{{ item.label }}</span>
|
||||
</template>
|
||||
<template #description="{ item }">
|
||||
<span
|
||||
v-if="item.description"
|
||||
class="mt-1 block text-xs leading-relaxed text-muted"
|
||||
>{{ item.description }}</span>
|
||||
</template>
|
||||
</URadioGroup>
|
||||
</template>
|
||||
@@ -6,8 +6,8 @@ defineProps<{
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="space-y-4">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<section class="overflow-hidden rounded-xl border border-default bg-default">
|
||||
<div class="flex items-start justify-between gap-4 px-4 py-3">
|
||||
<div class="min-w-0">
|
||||
<div class="flex items-center gap-2">
|
||||
<span
|
||||
@@ -32,6 +32,8 @@ defineProps<{
|
||||
<slot name="action" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="border-t border-default px-4">
|
||||
<slot />
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -6,6 +6,7 @@ defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
save: []
|
||||
restore: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
@@ -13,13 +14,19 @@ const { t } = useI18n()
|
||||
|
||||
<template>
|
||||
<div class="border-t border-default bg-default px-4 py-4 sm:px-6">
|
||||
<div class="flex items-center justify-end gap-3">
|
||||
<div class="flex flex-wrap items-center justify-end gap-3">
|
||||
<p
|
||||
v-if="hasChanges"
|
||||
class="mr-auto text-xs text-warning"
|
||||
>
|
||||
{{ t('settings.unsavedChanges') }}
|
||||
</p>
|
||||
<UButton
|
||||
:label="t('settings.restoreDefaults')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
@click="emit('restore')"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('settings.saveSettings')"
|
||||
icon="i-lucide-save"
|
||||
|
||||
@@ -1,39 +1,67 @@
|
||||
<script setup lang="ts">
|
||||
import type { SettingsTab } from '~/types/settings'
|
||||
|
||||
defineProps<{
|
||||
const props = defineProps<{
|
||||
modelValue: SettingsTab
|
||||
items: Array<{ id: SettingsTab, label: string, icon: string }>
|
||||
title: string
|
||||
subtitle: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:modelValue': [SettingsTab]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const searchQuery = ref('')
|
||||
|
||||
const filteredItems = computed(() => {
|
||||
const q = searchQuery.value.trim().toLowerCase()
|
||||
if (!q) return props.items
|
||||
return props.items.filter(item => item.label.toLowerCase().includes(q))
|
||||
})
|
||||
|
||||
function selectTab(id: SettingsTab) {
|
||||
emit('update:modelValue', id)
|
||||
searchQuery.value = ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="flex w-full shrink-0 flex-col border-b border-default bg-neutral-50 dark:bg-neutral-900/30 lg:w-56 lg:border-b-0 lg:border-r xl:w-60">
|
||||
<div class="border-b border-default px-4 py-5 sm:px-5">
|
||||
<h1 class="text-lg font-semibold tracking-tight text-highlighted">
|
||||
{{ title }}
|
||||
</h1>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ subtitle }}
|
||||
</p>
|
||||
<div class="border-b border-default p-3">
|
||||
<UInput
|
||||
v-model="searchQuery"
|
||||
size="sm"
|
||||
:placeholder="t('settings.searchPlaceholder')"
|
||||
icon="i-lucide-search"
|
||||
class="w-full"
|
||||
>
|
||||
<template #trailing>
|
||||
<UKbd
|
||||
size="sm"
|
||||
class="hidden sm:inline-flex"
|
||||
>
|
||||
⌘K
|
||||
</UKbd>
|
||||
</template>
|
||||
</UInput>
|
||||
</div>
|
||||
|
||||
<nav class="flex-1 space-y-0.5 p-3">
|
||||
<p
|
||||
v-if="searchQuery.trim() && !filteredItems.length"
|
||||
class="px-3 py-6 text-center text-xs text-muted"
|
||||
>
|
||||
{{ t('settings.searchEmpty') }}
|
||||
</p>
|
||||
<button
|
||||
v-for="item in items"
|
||||
v-for="item in filteredItems"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
class="flex w-full items-center gap-2.5 rounded-lg px-3 py-2.5 text-left text-sm transition-colors"
|
||||
:class="modelValue === item.id
|
||||
? 'bg-primary/10 font-medium text-primary'
|
||||
: 'text-muted hover:bg-muted/50 hover:text-highlighted'"
|
||||
@click="emit('update:modelValue', item.id)"
|
||||
@click="selectTab(item.id)"
|
||||
>
|
||||
<UIcon
|
||||
:name="item.icon"
|
||||
|
||||
@@ -4,33 +4,68 @@ defineProps<{
|
||||
updateAvailable: boolean
|
||||
latestVersion: string | null
|
||||
releaseUrl: string | null
|
||||
checking: boolean
|
||||
}>()
|
||||
|
||||
// 「检查更新」已停用(改动较大,与上游版本号已不对应),暂时保留事件定义
|
||||
defineEmits<{
|
||||
checkUpdate: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="pl-3">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-sm font-medium text-highlighted">
|
||||
<div class="flex flex-wrap items-center justify-between gap-4 py-4">
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.systemVersion') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.systemVersionHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-sm font-medium tabular-nums text-highlighted">
|
||||
v{{ appVersion }}
|
||||
</span>
|
||||
<!-- 检查更新功能已停用,需要时恢复下面这段
|
||||
<UBadge
|
||||
color="neutral"
|
||||
v-if="updateAvailable && latestVersion"
|
||||
color="warning"
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
>
|
||||
v{{ appVersion }}
|
||||
{{ t('settings.updateAvailable', { version: `v${latestVersion}` }) }}
|
||||
</UBadge>
|
||||
<UBadge
|
||||
v-else
|
||||
color="success"
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
>
|
||||
{{ t('settings.upToDate') }}
|
||||
</UBadge>
|
||||
<UButton
|
||||
:label="t('settings.checkUpdate')"
|
||||
icon="i-lucide-refresh-cw"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
size="sm"
|
||||
class="shrink-0"
|
||||
:loading="checking"
|
||||
@click="emit('checkUpdate')"
|
||||
/>
|
||||
<a
|
||||
v-if="updateAvailable && latestVersion"
|
||||
:href="releaseUrl || 'https://github.com/O96u/PicHost/releases'"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-xs text-warning hover:underline"
|
||||
class="text-xs text-primary hover:underline"
|
||||
>
|
||||
{{ t('settings.updateAvailable', { version: `v${latestVersion}` }) }}
|
||||
{{ t('settings.viewReleases') }}
|
||||
</a>
|
||||
-->
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,31 @@
|
||||
<script setup lang="ts">
|
||||
const { items: tags, loading, fetchTags } = useTags()
|
||||
|
||||
onMounted(() => {
|
||||
void fetchTags()
|
||||
})
|
||||
|
||||
async function handleChanged() {
|
||||
await fetchTags(true)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SettingsPanel>
|
||||
<div
|
||||
v-if="loading && !tags.length"
|
||||
class="flex justify-center py-16"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-6 animate-spin text-muted"
|
||||
/>
|
||||
</div>
|
||||
<TagManagePanel
|
||||
v-else
|
||||
:tags="tags"
|
||||
embedded
|
||||
@changed="handleChanged"
|
||||
/>
|
||||
</SettingsPanel>
|
||||
</template>
|
||||
@@ -9,7 +9,7 @@ const model = defineModel<boolean>({ required: true })
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-start justify-between gap-4 px-4 py-4 sm:px-5">
|
||||
<div class="flex items-start justify-between gap-4 py-4">
|
||||
<div class="min-w-0 flex-1 pr-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
<slot name="title">
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
<script setup lang="ts">
|
||||
type PolicySource = 'env' | 'db' | 'default'
|
||||
type MimeType = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/gif' | 'image/svg+xml' | 'image/x-icon'
|
||||
type VideoExtension = 'mp4' | 'm4v' | 'webm' | 'mov' | 'mkv' | 'avi' | 'flv' | 'wmv' | 'mpg' | 'mpeg'
|
||||
|
||||
const props = defineProps<{
|
||||
part: 'upload-preference' | 'image-processing' | 'login-rate'
|
||||
uploadImageMaxFileSizeMbSource?: PolicySource
|
||||
uploadVideoMaxFileSizeMbSource?: PolicySource
|
||||
uploadFileMaxFileSizeMbSource?: PolicySource
|
||||
allowedMimeTypesSource?: PolicySource
|
||||
allowedVideoExtensionsSource?: PolicySource
|
||||
forbiddenFileExtensionsSource?: PolicySource
|
||||
uploadRateIpMaxSource?: PolicySource
|
||||
uploadRateTokenMaxSource?: PolicySource
|
||||
uploadRateWindowMinutesSource?: PolicySource
|
||||
loginRateMaxSource?: PolicySource
|
||||
loginRateWindowMinutesSource?: PolicySource
|
||||
preserveOriginalUploadSource?: PolicySource
|
||||
mimeTypeOptions?: ReadonlyArray<{ mime: MimeType, label: string }>
|
||||
videoExtensionOptions?: ReadonlyArray<{ extension: VideoExtension, label: string }>
|
||||
forbiddenFileExtensionOptions?: ReadonlyArray<{ extension: string, label: string }>
|
||||
}>()
|
||||
|
||||
const uploadImageMaxFileSizeMbDraft = defineModel<number>('uploadImageMaxFileSizeMb')
|
||||
const uploadVideoMaxFileSizeMbDraft = defineModel<number>('uploadVideoMaxFileSizeMb')
|
||||
const uploadFileMaxFileSizeMbDraft = defineModel<number>('uploadFileMaxFileSizeMb')
|
||||
const allowedMimeTypesDraft = defineModel<MimeType[]>('allowedMimeTypes')
|
||||
const allowedVideoExtensionsDraft = defineModel<VideoExtension[]>('allowedVideoExtensions')
|
||||
const forbiddenFileExtensionsDraft = defineModel<string[]>('forbiddenFileExtensions')
|
||||
const uploadRateIpMaxDraft = defineModel<number>('uploadRateIpMax')
|
||||
const uploadRateTokenMaxDraft = defineModel<number>('uploadRateTokenMax')
|
||||
const uploadRateWindowMinutesDraft = defineModel<number>('uploadRateWindowMinutes')
|
||||
const loginRateMaxDraft = defineModel<number>('loginRateMax')
|
||||
const loginRateWindowMinutesDraft = defineModel<number>('loginRateWindowMinutes')
|
||||
const preserveOriginalUploadDraft = defineModel<boolean>('preserveOriginalUpload')
|
||||
const customForbiddenExtension = ref('')
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
function sourceBadge(source: PolicySource) {
|
||||
switch (source) {
|
||||
case 'env':
|
||||
return { label: t('settings.badgeEnv'), color: 'warning' as const }
|
||||
case 'db':
|
||||
return { label: t('settings.badgeSaved'), color: 'success' as const }
|
||||
default:
|
||||
return { label: t('settings.badgeDefault'), color: 'neutral' as const }
|
||||
}
|
||||
}
|
||||
|
||||
function toggleMime(mime: MimeType, checked: boolean) {
|
||||
if (!allowedMimeTypesDraft.value) return
|
||||
if (checked) {
|
||||
if (!allowedMimeTypesDraft.value.includes(mime)) {
|
||||
allowedMimeTypesDraft.value = [...allowedMimeTypesDraft.value, mime]
|
||||
}
|
||||
return
|
||||
}
|
||||
if (allowedMimeTypesDraft.value.length <= 1) return
|
||||
allowedMimeTypesDraft.value = allowedMimeTypesDraft.value.filter(item => item !== mime)
|
||||
}
|
||||
|
||||
function isMimeChecked(mime: MimeType): boolean {
|
||||
return allowedMimeTypesDraft.value?.includes(mime) ?? false
|
||||
}
|
||||
|
||||
function toggleVideoExtension(extension: VideoExtension, checked: boolean) {
|
||||
if (!allowedVideoExtensionsDraft.value) return
|
||||
if (checked) {
|
||||
if (!allowedVideoExtensionsDraft.value.includes(extension)) {
|
||||
allowedVideoExtensionsDraft.value = [
|
||||
...allowedVideoExtensionsDraft.value,
|
||||
extension
|
||||
]
|
||||
}
|
||||
return
|
||||
}
|
||||
if (allowedVideoExtensionsDraft.value.length <= 1) return
|
||||
allowedVideoExtensionsDraft.value = allowedVideoExtensionsDraft.value
|
||||
.filter(item => item !== extension)
|
||||
}
|
||||
|
||||
function isVideoExtensionChecked(extension: VideoExtension): boolean {
|
||||
return allowedVideoExtensionsDraft.value?.includes(extension) ?? false
|
||||
}
|
||||
|
||||
function toggleForbiddenExtension(extension: string, checked: boolean) {
|
||||
if (!forbiddenFileExtensionsDraft.value) return
|
||||
if (checked) {
|
||||
if (!forbiddenFileExtensionsDraft.value.includes(extension)) {
|
||||
forbiddenFileExtensionsDraft.value = [
|
||||
...forbiddenFileExtensionsDraft.value,
|
||||
extension
|
||||
]
|
||||
}
|
||||
return
|
||||
}
|
||||
forbiddenFileExtensionsDraft.value = forbiddenFileExtensionsDraft.value
|
||||
.filter(item => item !== extension)
|
||||
}
|
||||
|
||||
function isForbiddenExtensionChecked(extension: string): boolean {
|
||||
return forbiddenFileExtensionsDraft.value?.includes(extension) ?? false
|
||||
}
|
||||
|
||||
const allForbiddenExtensionOptions = computed(() => {
|
||||
const options = new Map(
|
||||
(props.forbiddenFileExtensionOptions ?? []).map(option => [
|
||||
option.extension,
|
||||
option.label
|
||||
])
|
||||
)
|
||||
for (const extension of forbiddenFileExtensionsDraft.value ?? []) {
|
||||
if (!options.has(extension)) options.set(extension, extension.toUpperCase())
|
||||
}
|
||||
return [...options].map(([extension, label]) => ({ extension, label }))
|
||||
})
|
||||
|
||||
function addCustomForbiddenExtension() {
|
||||
const values = customForbiddenExtension.value
|
||||
.split(',')
|
||||
.map(value => value.trim().toLowerCase().replace(/^\.+/, ''))
|
||||
.filter(value => /^[a-z0-9][a-z0-9_-]{0,15}$/.test(value))
|
||||
if (!values.length) return
|
||||
const next = new Set(forbiddenFileExtensionsDraft.value ?? [])
|
||||
for (const value of values) next.add(value)
|
||||
forbiddenFileExtensionsDraft.value = [...next]
|
||||
customForbiddenExtension.value = ''
|
||||
}
|
||||
|
||||
type UploadSizeKind = 'image' | 'video' | 'file'
|
||||
|
||||
const uploadSizeFields = computed(() => [
|
||||
{
|
||||
kind: 'image' as const,
|
||||
title: t('settings.uploadImageMaxFileSize'),
|
||||
hint: t('settings.uploadImageMaxFileSizeHint'),
|
||||
source: props.uploadImageMaxFileSizeMbSource,
|
||||
value: uploadImageMaxFileSizeMbDraft.value ?? 10,
|
||||
max: 100
|
||||
},
|
||||
{
|
||||
kind: 'video' as const,
|
||||
title: t('settings.uploadVideoMaxFileSize'),
|
||||
hint: t('settings.uploadVideoMaxFileSizeHint'),
|
||||
source: props.uploadVideoMaxFileSizeMbSource,
|
||||
value: uploadVideoMaxFileSizeMbDraft.value ?? 500,
|
||||
max: 2048
|
||||
},
|
||||
{
|
||||
kind: 'file' as const,
|
||||
title: t('settings.uploadFileMaxFileSize'),
|
||||
hint: t('settings.uploadFileMaxFileSizeHint'),
|
||||
source: props.uploadFileMaxFileSizeMbSource,
|
||||
value: uploadFileMaxFileSizeMbDraft.value ?? 100,
|
||||
max: 1024
|
||||
}
|
||||
])
|
||||
|
||||
function uploadSizeModel(kind: UploadSizeKind) {
|
||||
if (kind === 'video') return uploadVideoMaxFileSizeMbDraft
|
||||
if (kind === 'file') return uploadFileMaxFileSizeMbDraft
|
||||
return uploadImageMaxFileSizeMbDraft
|
||||
}
|
||||
|
||||
function clampUploadMaxFileSizeMb(kind: UploadSizeKind, value: unknown): number {
|
||||
const num = Number(value)
|
||||
const model = uploadSizeModel(kind)
|
||||
const max = kind === 'video' ? 2048 : kind === 'file' ? 1024 : 100
|
||||
if (!Number.isFinite(num)) return model.value ?? (kind === 'video' ? 500 : kind === 'file' ? 100 : 10)
|
||||
return Math.min(max, Math.max(0, Math.round(num)))
|
||||
}
|
||||
|
||||
function onUploadMaxFileSizeInput(kind: UploadSizeKind, event: Event) {
|
||||
uploadSizeModel(kind).value = clampUploadMaxFileSizeMb(kind,
|
||||
(event.target as HTMLInputElement).value
|
||||
)
|
||||
}
|
||||
|
||||
function onUploadMaxFileSizeNumberInput(kind: UploadSizeKind, value: string | number) {
|
||||
uploadSizeModel(kind).value = clampUploadMaxFileSizeMb(kind, value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-if="part === 'upload-preference'">
|
||||
<div class="space-y-5 py-4">
|
||||
<div
|
||||
v-for="field in uploadSizeFields"
|
||||
:key="field.kind"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ field.title }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="field.source"
|
||||
:color="sourceBadge(field.source).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(field.source).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ field.hint }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex items-center gap-3"
|
||||
:class="field.source === 'env' ? 'pointer-events-none opacity-60' : ''"
|
||||
>
|
||||
<input
|
||||
type="range"
|
||||
min="0"
|
||||
:max="field.max"
|
||||
:value="field.value"
|
||||
class="h-1.5 min-w-0 flex-1 cursor-pointer appearance-none rounded-full bg-muted accent-primary"
|
||||
:disabled="field.source === 'env'"
|
||||
@input="onUploadMaxFileSizeInput(field.kind, $event)"
|
||||
>
|
||||
<div class="flex shrink-0 items-center gap-1.5">
|
||||
<UInput
|
||||
:model-value="field.value"
|
||||
type="number"
|
||||
:min="0"
|
||||
:max="field.max"
|
||||
size="xs"
|
||||
class="w-16 tabular-nums"
|
||||
:disabled="field.source === 'env'"
|
||||
@update:model-value="onUploadMaxFileSizeNumberInput(field.kind, $event)"
|
||||
/>
|
||||
<span class="text-xs text-muted">MB</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-default/50 py-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.allowedMimeTypes') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="allowedMimeTypesSource"
|
||||
:color="sourceBadge(allowedMimeTypesSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(allowedMimeTypesSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.allowedMimeTypesHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex flex-wrap gap-2"
|
||||
:class="allowedMimeTypesSource === 'env' ? 'pointer-events-none opacity-60' : ''"
|
||||
>
|
||||
<label
|
||||
v-for="option in mimeTypeOptions ?? []"
|
||||
:key="option.mime"
|
||||
class="inline-flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors"
|
||||
:class="isMimeChecked(option.mime)
|
||||
? 'border-primary/40 bg-primary/5'
|
||||
: 'border-default bg-muted/20 hover:bg-muted/40'"
|
||||
:title="option.mime"
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="isMimeChecked(option.mime)"
|
||||
@update:model-value="(v) => toggleMime(option.mime, v === true)"
|
||||
@click.stop
|
||||
/>
|
||||
<span class="font-medium text-highlighted">{{ option.label }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-default/50 py-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.allowedVideoExtensions') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="allowedVideoExtensionsSource"
|
||||
:color="sourceBadge(allowedVideoExtensionsSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(allowedVideoExtensionsSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.allowedVideoExtensionsHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex flex-wrap gap-2"
|
||||
:class="allowedVideoExtensionsSource === 'env' ? 'pointer-events-none opacity-60' : ''"
|
||||
>
|
||||
<label
|
||||
v-for="option in videoExtensionOptions ?? []"
|
||||
:key="option.extension"
|
||||
class="inline-flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors"
|
||||
:class="isVideoExtensionChecked(option.extension)
|
||||
? 'border-primary/40 bg-primary/5'
|
||||
: 'border-default bg-muted/20 hover:bg-muted/40'"
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="isVideoExtensionChecked(option.extension)"
|
||||
@update:model-value="(v) => toggleVideoExtension(option.extension, v === true)"
|
||||
@click.stop
|
||||
/>
|
||||
<span class="font-medium text-highlighted">{{ option.label }}</span>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-default/50 py-4">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.forbiddenFileExtensions') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="forbiddenFileExtensionsSource"
|
||||
:color="sourceBadge(forbiddenFileExtensionsSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(forbiddenFileExtensionsSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.forbiddenFileExtensionsHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="mt-3 flex flex-wrap gap-2"
|
||||
:class="forbiddenFileExtensionsSource === 'env' ? 'pointer-events-none opacity-60' : ''"
|
||||
>
|
||||
<label
|
||||
v-for="option in allForbiddenExtensionOptions"
|
||||
:key="option.extension"
|
||||
class="inline-flex cursor-pointer items-center gap-2 rounded-lg border px-3 py-2 text-sm transition-colors"
|
||||
:class="isForbiddenExtensionChecked(option.extension)
|
||||
? 'border-error/40 bg-error/5'
|
||||
: 'border-default bg-muted/20 hover:bg-muted/40'"
|
||||
>
|
||||
<UCheckbox
|
||||
:model-value="isForbiddenExtensionChecked(option.extension)"
|
||||
@update:model-value="(v) => toggleForbiddenExtension(option.extension, v === true)"
|
||||
@click.stop
|
||||
/>
|
||||
<span class="font-medium text-highlighted">{{ option.label }}</span>
|
||||
</label>
|
||||
</div>
|
||||
<div
|
||||
class="mt-3 flex max-w-md items-center gap-2"
|
||||
:class="forbiddenFileExtensionsSource === 'env' ? 'pointer-events-none opacity-60' : ''"
|
||||
>
|
||||
<UInput
|
||||
v-model="customForbiddenExtension"
|
||||
size="sm"
|
||||
class="min-w-0 flex-1"
|
||||
:placeholder="t('settings.forbiddenFileExtensionsCustomPlaceholder')"
|
||||
:disabled="forbiddenFileExtensionsSource === 'env'"
|
||||
@keydown.enter.prevent="addCustomForbiddenExtension"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('settings.forbiddenFileExtensionsAdd')"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
:disabled="forbiddenFileExtensionsSource === 'env'"
|
||||
@click="addCustomForbiddenExtension"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="py-4">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.uploadRateGroup') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.uploadRateFootnote') }}
|
||||
</p>
|
||||
<div class="mt-3 grid gap-4 sm:grid-cols-3">
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-medium text-muted">
|
||||
{{ t('settings.uploadRateIpMax') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="uploadRateIpMaxSource"
|
||||
:color="sourceBadge(uploadRateIpMaxSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(uploadRateIpMaxSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<UInput
|
||||
v-model.number="uploadRateIpMaxDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="1000"
|
||||
size="sm"
|
||||
class="mt-2 w-full tabular-nums"
|
||||
:disabled="uploadRateIpMaxSource === 'env'"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-medium text-muted">
|
||||
{{ t('settings.uploadRateTokenMax') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="uploadRateTokenMaxSource"
|
||||
:color="sourceBadge(uploadRateTokenMaxSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(uploadRateTokenMaxSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<UInput
|
||||
v-model.number="uploadRateTokenMaxDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="5000"
|
||||
size="sm"
|
||||
class="mt-2 w-full tabular-nums"
|
||||
:disabled="uploadRateTokenMaxSource === 'env'"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-xs font-medium text-muted">
|
||||
{{ t('settings.uploadRateWindowMinutes') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="uploadRateWindowMinutesSource"
|
||||
:color="sourceBadge(uploadRateWindowMinutesSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(uploadRateWindowMinutesSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<div class="mt-2 flex items-center gap-2">
|
||||
<UInput
|
||||
v-model.number="uploadRateWindowMinutesDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="1440"
|
||||
size="sm"
|
||||
class="w-full tabular-nums"
|
||||
:disabled="uploadRateWindowMinutesSource === 'env'"
|
||||
/>
|
||||
<span class="shrink-0 text-xs text-muted">{{ t('settings.minutesUnit') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<SettingsToggleRow
|
||||
v-else-if="part === 'image-processing'"
|
||||
v-model="preserveOriginalUploadDraft!"
|
||||
:disabled="preserveOriginalUploadSource === 'env'"
|
||||
>
|
||||
<template #title>
|
||||
<span class="inline-flex flex-wrap items-center gap-2">
|
||||
{{ t('settings.preserveOriginalUpload') }}
|
||||
<UBadge
|
||||
v-if="preserveOriginalUploadSource"
|
||||
:color="sourceBadge(preserveOriginalUploadSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(preserveOriginalUploadSource).label }}
|
||||
</UBadge>
|
||||
</span>
|
||||
</template>
|
||||
<template #hint>
|
||||
{{ t('settings.preserveOriginalUploadHint') }}
|
||||
</template>
|
||||
</SettingsToggleRow>
|
||||
|
||||
<template v-else-if="part === 'login-rate'">
|
||||
<div class="grid gap-4 py-4 sm:grid-cols-2">
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.loginRateMax') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="loginRateMaxSource"
|
||||
:color="sourceBadge(loginRateMaxSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(loginRateMaxSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<UInput
|
||||
v-model.number="loginRateMaxDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="100"
|
||||
size="sm"
|
||||
class="mt-2 w-full tabular-nums"
|
||||
:disabled="loginRateMaxSource === 'env'"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.loginRateWindowMinutes') }}
|
||||
</p>
|
||||
<UBadge
|
||||
v-if="loginRateWindowMinutesSource"
|
||||
:color="sourceBadge(loginRateWindowMinutesSource).color"
|
||||
variant="subtle"
|
||||
size="xs"
|
||||
>
|
||||
{{ sourceBadge(loginRateWindowMinutesSource).label }}
|
||||
</UBadge>
|
||||
</div>
|
||||
<div class="mt-2 flex items-center gap-2">
|
||||
<UInput
|
||||
v-model.number="loginRateWindowMinutesDraft"
|
||||
type="number"
|
||||
:min="1"
|
||||
:max="1440"
|
||||
size="sm"
|
||||
class="w-full tabular-nums"
|
||||
:disabled="loginRateWindowMinutesSource === 'env'"
|
||||
/>
|
||||
<span class="shrink-0 text-xs text-muted">{{ t('settings.minutesUnit') }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="pb-4 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.loginRateFootnote') }}
|
||||
</p>
|
||||
</template>
|
||||
</template>
|
||||
@@ -1,11 +1,20 @@
|
||||
<script setup lang="ts">
|
||||
import type { UploadMediaKind } from '~/composables/useUploadPreferences'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
part: 'upload-preference' | 'image-processing'
|
||||
kind?: UploadMediaKind
|
||||
}>(), {
|
||||
kind: 'image'
|
||||
})
|
||||
|
||||
const {
|
||||
compressEnabled,
|
||||
autoCopyMarkdown,
|
||||
copyFormat,
|
||||
clientWebpQuality,
|
||||
loadPreferences
|
||||
} = useUploadPreferences()
|
||||
} = useUploadPreferences(props.kind)
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -19,16 +28,11 @@ const {
|
||||
const copyFormatItems = computed(() => [
|
||||
{ label: t('copy.url'), value: 'url' as const },
|
||||
{ label: t('copy.markdown'), value: 'markdown' as const },
|
||||
{ label: t('copy.html'), value: 'html' as const }
|
||||
{ label: t('copy.html'), value: 'html' as const },
|
||||
{ label: t('copy.bbcode'), value: 'bbcode' as const }
|
||||
])
|
||||
|
||||
const clientQualityLevel = computed(() => {
|
||||
if (clientWebpQuality.value >= 85) return t('preferences.qualityHigh')
|
||||
if (clientWebpQuality.value >= 60) return t('preferences.qualityMedium')
|
||||
return t('preferences.qualityLow')
|
||||
})
|
||||
|
||||
function setCopyFormat(value: 'url' | 'markdown' | 'html') {
|
||||
function setCopyFormat(value: 'url' | 'markdown' | 'html' | 'bbcode') {
|
||||
copyFormat.value = value
|
||||
}
|
||||
|
||||
@@ -37,6 +41,11 @@ function onClientQualityInput(event: Event) {
|
||||
clientWebpQuality.value = Number.isFinite(value) ? value : 80
|
||||
}
|
||||
|
||||
function onClientQualityNumberInput(value: string | number) {
|
||||
const num = Number(value)
|
||||
clientWebpQuality.value = Number.isFinite(num) ? Math.min(100, Math.max(1, Math.round(num))) : 80
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadPreferences()
|
||||
void loadUserSettings()
|
||||
@@ -44,8 +53,7 @@ onMounted(() => {
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SettingsSection :title="t('preferences.processing')">
|
||||
<SettingsGroup>
|
||||
<template v-if="part === 'image-processing'">
|
||||
<SettingsToggleRow
|
||||
v-model="compressEnabled"
|
||||
:title="t('preferences.clientCompress')"
|
||||
@@ -53,7 +61,7 @@ onMounted(() => {
|
||||
/>
|
||||
<div
|
||||
v-if="userSettings"
|
||||
class="flex items-start justify-between gap-4 px-4 py-4 sm:px-5"
|
||||
class="flex items-start justify-between gap-4 py-4"
|
||||
>
|
||||
<div class="min-w-0 flex-1 pr-2">
|
||||
<p class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm font-medium text-highlighted">
|
||||
@@ -87,9 +95,8 @@ onMounted(() => {
|
||||
class="size-5 animate-spin text-muted"
|
||||
/>
|
||||
</div>
|
||||
<div class="px-4 py-4 sm:px-5">
|
||||
<div class="flex items-start justify-between gap-4">
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="py-4">
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('preferences.webpQuality') }}
|
||||
</p>
|
||||
@@ -97,45 +104,50 @@ onMounted(() => {
|
||||
{{ t('preferences.webpQualityHint') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="shrink-0 text-right text-xs text-muted">
|
||||
<p>{{ t('preferences.current', { n: clientWebpQuality }) }}</p>
|
||||
<p class="mt-0.5">
|
||||
{{ clientQualityLevel }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-3 flex items-center gap-3">
|
||||
<input
|
||||
type="range"
|
||||
min="1"
|
||||
max="100"
|
||||
:value="clientWebpQuality"
|
||||
class="mt-3 h-1.5 w-full cursor-pointer appearance-none rounded-full bg-muted accent-primary"
|
||||
class="h-1.5 min-w-0 flex-1 cursor-pointer appearance-none rounded-full bg-muted accent-primary"
|
||||
@input="onClientQualityInput"
|
||||
>
|
||||
<UInput
|
||||
:model-value="clientWebpQuality"
|
||||
type="number"
|
||||
min="1"
|
||||
max="100"
|
||||
size="xs"
|
||||
class="w-14 shrink-0 tabular-nums"
|
||||
@update:model-value="onClientQualityNumberInput"
|
||||
/>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<SettingsSection :title="t('settings.uploadConvenience')">
|
||||
<SettingsGroup>
|
||||
<template v-else>
|
||||
<SettingsToggleRow
|
||||
v-model="autoCopyMarkdown"
|
||||
:title="t('preferences.autoCopy')"
|
||||
:hint="t('preferences.autoCopyHint')"
|
||||
/>
|
||||
<div class="flex flex-col gap-3 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
|
||||
<div class="py-4">
|
||||
<p class="text-sm font-medium text-highlighted">
|
||||
{{ t('settings.defaultCopyFormat') }}
|
||||
</p>
|
||||
<p class="mt-1 text-xs leading-relaxed text-muted">
|
||||
{{ t('settings.defaultCopyFormatHint') }}
|
||||
</p>
|
||||
<div
|
||||
class="flex w-full max-w-xs gap-1 rounded-lg border border-default p-0.5 sm:w-auto"
|
||||
class="mt-3 flex w-full max-w-md gap-1 rounded-lg border border-default p-0.5"
|
||||
:class="autoCopyMarkdown ? '' : 'pointer-events-none opacity-40'"
|
||||
>
|
||||
<UButton
|
||||
v-for="item in copyFormatItems"
|
||||
:key="item.value"
|
||||
size="xs"
|
||||
class="flex-1 justify-center sm:min-w-[4.5rem]"
|
||||
class="flex-1 justify-center"
|
||||
:variant="copyFormat === item.value ? 'solid' : 'ghost'"
|
||||
:color="copyFormat === item.value ? 'primary' : 'neutral'"
|
||||
:label="item.label"
|
||||
@@ -143,6 +155,5 @@ onMounted(() => {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</SettingsGroup>
|
||||
</SettingsSection>
|
||||
</template>
|
||||
</template>
|
||||
@@ -0,0 +1,43 @@
|
||||
<script setup lang="ts">
|
||||
const { transcodeToHls, loadPreferences } = useUploadPreferences('video')
|
||||
const { t } = useI18n()
|
||||
const {
|
||||
lowMemory,
|
||||
memoryBytes,
|
||||
load: loadTranscodeSettings
|
||||
} = useTranscodeSettings()
|
||||
|
||||
const memoryGb = computed(() => (
|
||||
memoryBytes.value > 0
|
||||
? (memoryBytes.value / (1024 * 1024 * 1024)).toFixed(1)
|
||||
: '—'
|
||||
))
|
||||
|
||||
onMounted(() => {
|
||||
loadPreferences()
|
||||
void loadTranscodeSettings()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UAlert
|
||||
v-if="lowMemory"
|
||||
color="warning"
|
||||
variant="subtle"
|
||||
icon="i-lucide-triangle-alert"
|
||||
:title="t('preferences.lowMemoryTranscodeTitle')"
|
||||
:description="t('preferences.lowMemoryTranscodeHint', { memory: memoryGb })"
|
||||
class="my-4"
|
||||
/>
|
||||
<SettingsToggleRow
|
||||
v-model="transcodeToHls"
|
||||
:title="t('preferences.transcodeToHls')"
|
||||
:hint="t('preferences.transcodeToHlsHint')"
|
||||
/>
|
||||
<div
|
||||
v-if="transcodeToHls"
|
||||
class="border-t border-default/50 py-4"
|
||||
>
|
||||
<TranscodeSettingsControls />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,444 @@
|
||||
<script setup lang="ts">
|
||||
import type { BackendSyncPreview, SyncDraft } from '~/types/backup'
|
||||
import type { StorageBackendItem } from '~/types/storage'
|
||||
|
||||
const props = defineProps<{
|
||||
backends: StorageBackendItem[]
|
||||
syncDraft: SyncDraft | null
|
||||
highlighted?: boolean
|
||||
busy: boolean
|
||||
disabled?: boolean
|
||||
activeJob?: { progress: number, total: number, message: string } | null
|
||||
previewSync: (body: { fromBackendId: string, toBackendId: string }) => Promise<BackendSyncPreview>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
sync: [body: {
|
||||
fromBackendId: string
|
||||
toBackendId: string
|
||||
deleteSource: boolean
|
||||
setDefault: boolean
|
||||
}]
|
||||
}>()
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const { formatFileSize } = useFileSize()
|
||||
const toast = useToast()
|
||||
|
||||
const fromBackendId = ref('')
|
||||
const toBackendId = ref('')
|
||||
const deleteSource = ref(false)
|
||||
const setDefault = ref(false)
|
||||
const preview = ref<BackendSyncPreview | null>(null)
|
||||
const previewLoading = ref(false)
|
||||
const statsLoading = ref(false)
|
||||
const confirmOpen = ref(false)
|
||||
const userTouched = ref(false)
|
||||
|
||||
let statsTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
const backendOptions = computed(() =>
|
||||
props.backends.map(backend => ({
|
||||
label: backend.name,
|
||||
value: backend.id
|
||||
}))
|
||||
)
|
||||
|
||||
const backendNameById = computed(() =>
|
||||
new Map(props.backends.map(backend => [backend.id, backend.name]))
|
||||
)
|
||||
|
||||
const needsMoreBackends = computed(() => props.backends.length < 2)
|
||||
|
||||
const syncDisabled = computed(() =>
|
||||
props.disabled || props.busy || needsMoreBackends.value
|
||||
)
|
||||
|
||||
function formatCount(value: number) {
|
||||
return value.toLocaleString(locale.value)
|
||||
}
|
||||
|
||||
function initDefaultSelection() {
|
||||
if (userTouched.value || props.syncDraft) return
|
||||
const defaultBackend = props.backends.find(backend => backend.isDefault)
|
||||
const target = props.backends.find(backend => !backend.isDefault && backend.enabled)
|
||||
if (defaultBackend && target) {
|
||||
fromBackendId.value = defaultBackend.id
|
||||
toBackendId.value = target.id
|
||||
return
|
||||
}
|
||||
if (props.backends.length >= 2) {
|
||||
fromBackendId.value = props.backends[0]!.id
|
||||
toBackendId.value = props.backends[1]!.id
|
||||
}
|
||||
}
|
||||
|
||||
function canLoadStats(): boolean {
|
||||
return !needsMoreBackends.value
|
||||
&& Boolean(fromBackendId.value)
|
||||
&& Boolean(toBackendId.value)
|
||||
&& fromBackendId.value !== toBackendId.value
|
||||
}
|
||||
|
||||
async function refreshStats(immediate = false) {
|
||||
if (!canLoadStats()) {
|
||||
preview.value = null
|
||||
return
|
||||
}
|
||||
if (immediate) {
|
||||
if (statsTimer) clearTimeout(statsTimer)
|
||||
await loadStats()
|
||||
return
|
||||
}
|
||||
scheduleStatsLoad()
|
||||
}
|
||||
|
||||
async function loadStats() {
|
||||
if (needsMoreBackends.value || !fromBackendId.value || !toBackendId.value) {
|
||||
preview.value = null
|
||||
return
|
||||
}
|
||||
if (fromBackendId.value === toBackendId.value) {
|
||||
preview.value = null
|
||||
return
|
||||
}
|
||||
statsLoading.value = true
|
||||
try {
|
||||
preview.value = await props.previewSync({
|
||||
fromBackendId: fromBackendId.value,
|
||||
toBackendId: toBackendId.value
|
||||
})
|
||||
} catch {
|
||||
preview.value = null
|
||||
} finally {
|
||||
statsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleStatsLoad() {
|
||||
if (statsTimer) clearTimeout(statsTimer)
|
||||
statsTimer = setTimeout(() => {
|
||||
void loadStats()
|
||||
}, 400)
|
||||
}
|
||||
|
||||
watch(
|
||||
() => props.backends,
|
||||
async () => {
|
||||
initDefaultSelection()
|
||||
await nextTick()
|
||||
await refreshStats(true)
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
watch(
|
||||
() => props.syncDraft,
|
||||
async (draft) => {
|
||||
if (!draft) return
|
||||
fromBackendId.value = draft.fromBackendId
|
||||
toBackendId.value = draft.toBackendId
|
||||
userTouched.value = true
|
||||
await refreshStats(true)
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
watch([fromBackendId, toBackendId], () => {
|
||||
void refreshStats()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (statsTimer) clearTimeout(statsTimer)
|
||||
})
|
||||
|
||||
function applyDraft(draft: SyncDraft) {
|
||||
fromBackendId.value = draft.fromBackendId
|
||||
toBackendId.value = draft.toBackendId
|
||||
userTouched.value = true
|
||||
void refreshStats(true)
|
||||
}
|
||||
|
||||
defineExpose({ applyDraft })
|
||||
|
||||
function backendName(id: string) {
|
||||
return backendNameById.value.get(id) ?? id
|
||||
}
|
||||
|
||||
function validateSelection(): boolean {
|
||||
if (needsMoreBackends.value) {
|
||||
toast.add({ title: t('storage.backup.syncNeedTwoBackends'), color: 'warning' })
|
||||
return false
|
||||
}
|
||||
if (!fromBackendId.value || !toBackendId.value) {
|
||||
toast.add({ title: t('storage.backup.syncSelectRequired'), color: 'warning' })
|
||||
return false
|
||||
}
|
||||
if (fromBackendId.value === toBackendId.value) {
|
||||
toast.add({ title: t('storage.backup.syncSameBackend'), color: 'warning' })
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!validateSelection()) return
|
||||
previewLoading.value = true
|
||||
try {
|
||||
preview.value = await props.previewSync({
|
||||
fromBackendId: fromBackendId.value,
|
||||
toBackendId: toBackendId.value
|
||||
})
|
||||
confirmOpen.value = true
|
||||
} catch {
|
||||
toast.add({ title: t('storage.backup.previewFailed'), color: 'error' })
|
||||
} finally {
|
||||
previewLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function confirmSync() {
|
||||
emit('sync', {
|
||||
fromBackendId: fromBackendId.value,
|
||||
toBackendId: toBackendId.value,
|
||||
deleteSource: deleteSource.value,
|
||||
setDefault: setDefault.value
|
||||
})
|
||||
confirmOpen.value = false
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article
|
||||
class="flex h-full flex-col rounded-xl border bg-elevated p-4 transition-colors sm:p-5"
|
||||
:class="highlighted ? 'border-primary ring-2 ring-primary/25' : 'border-default'"
|
||||
>
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-info/10 text-info">
|
||||
<UIcon
|
||||
name="i-lucide-arrow-left-right"
|
||||
class="size-5"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ t('storage.backup.syncTitle') }}
|
||||
</h3>
|
||||
<p class="mt-0.5 text-sm text-muted">
|
||||
{{ t('storage.backup.syncSubtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-1 flex-col">
|
||||
<UAlert
|
||||
v-if="needsMoreBackends"
|
||||
color="warning"
|
||||
variant="subtle"
|
||||
icon="i-lucide-triangle-alert"
|
||||
:description="t('storage.backup.syncNeedTwoBackends')"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="flex flex-1 flex-col space-y-3"
|
||||
>
|
||||
<div class="grid gap-3 sm:grid-cols-[1fr_auto_1fr] sm:items-end">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.syncFrom') }}</label>
|
||||
<USelect
|
||||
v-model="fromBackendId"
|
||||
:items="backendOptions"
|
||||
size="sm"
|
||||
class="w-full"
|
||||
:disabled="syncDisabled"
|
||||
@update:model-value="userTouched = true"
|
||||
/>
|
||||
</div>
|
||||
<UIcon
|
||||
name="i-lucide-arrow-right"
|
||||
class="hidden size-4 shrink-0 text-muted sm:mb-2.5 sm:block"
|
||||
/>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.syncTo') }}</label>
|
||||
<USelect
|
||||
v-model="toBackendId"
|
||||
:items="backendOptions"
|
||||
size="sm"
|
||||
class="w-full"
|
||||
:disabled="syncDisabled"
|
||||
@update:model-value="userTouched = true"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<dl class="space-y-1.5 rounded-lg bg-muted/25 px-3 py-2.5 text-sm">
|
||||
<div class="flex items-baseline justify-between gap-2">
|
||||
<dt class="text-muted">
|
||||
{{ t('storage.backup.syncPendingImages') }}
|
||||
</dt>
|
||||
<dd class="font-medium tabular-nums">
|
||||
<template v-if="statsLoading">
|
||||
…
|
||||
</template>
|
||||
<template v-else-if="preview">
|
||||
{{ formatCount(preview.imageCount) }}
|
||||
</template>
|
||||
<template v-else>
|
||||
—
|
||||
</template>
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex items-baseline justify-between gap-2">
|
||||
<dt class="text-muted">
|
||||
{{ t('storage.backup.syncPendingSize') }}
|
||||
</dt>
|
||||
<dd class="font-medium tabular-nums">
|
||||
<template v-if="statsLoading">
|
||||
…
|
||||
</template>
|
||||
<template v-else-if="preview">
|
||||
{{ formatFileSize(preview.imageBytes) }}
|
||||
</template>
|
||||
<template v-else>
|
||||
—
|
||||
</template>
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div class="space-y-2 text-xs">
|
||||
<label class="flex cursor-pointer items-center gap-2">
|
||||
<UCheckbox
|
||||
v-model="deleteSource"
|
||||
:disabled="syncDisabled"
|
||||
/>
|
||||
<span class="text-muted">{{ t('storage.backup.syncDeleteSource') }}</span>
|
||||
</label>
|
||||
<label class="flex cursor-pointer items-center gap-2">
|
||||
<UCheckbox
|
||||
v-model="setDefault"
|
||||
:disabled="syncDisabled"
|
||||
/>
|
||||
<span class="text-muted">{{ t('storage.backup.syncSetDefault') }}</span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-auto rounded-lg bg-muted/15 px-3 py-2.5">
|
||||
<p class="text-xs font-medium text-default">
|
||||
{{ t('storage.backup.syncIncludesTitle') }}
|
||||
</p>
|
||||
<ul class="mt-2 space-y-1.5 text-xs leading-relaxed text-muted">
|
||||
<li class="flex items-start gap-2">
|
||||
<UIcon
|
||||
name="i-lucide-check"
|
||||
class="mt-0.5 size-3.5 shrink-0 text-info"
|
||||
/>
|
||||
<span>{{ t('storage.backup.syncIncludesCopy') }}</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<UIcon
|
||||
name="i-lucide-check"
|
||||
class="mt-0.5 size-3.5 shrink-0 text-info"
|
||||
/>
|
||||
<span>{{ t('storage.backup.syncIncludesIndex') }}</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<UIcon
|
||||
name="i-lucide-minus"
|
||||
class="mt-0.5 size-3.5 shrink-0 text-muted"
|
||||
/>
|
||||
<span>{{ t('storage.backup.syncIncludesConfig') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<StorageBackupJobProgress
|
||||
v-if="busy && activeJob"
|
||||
class="mt-auto"
|
||||
:message="activeJob.message"
|
||||
:progress="activeJob.progress"
|
||||
:total="activeJob.total"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="!needsMoreBackends"
|
||||
class="mt-auto border-t border-default pt-4"
|
||||
>
|
||||
<UButton
|
||||
:label="t('storage.backup.syncPreview')"
|
||||
icon="i-lucide-play"
|
||||
size="sm"
|
||||
:loading="previewLoading || busy"
|
||||
:disabled="syncDisabled"
|
||||
@click="submit"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UModal
|
||||
v-model:open="confirmOpen"
|
||||
:ui="{ content: 'max-w-md' }"
|
||||
>
|
||||
<template #content>
|
||||
<div class="p-5 sm:p-6">
|
||||
<h2 class="text-base font-semibold">
|
||||
{{ t('storage.backup.syncConfirmTitle') }}
|
||||
</h2>
|
||||
<p class="mt-2 text-sm text-muted">
|
||||
{{ backendName(fromBackendId) }} → {{ backendName(toBackendId) }}
|
||||
</p>
|
||||
|
||||
<dl
|
||||
v-if="preview"
|
||||
class="mt-4 grid grid-cols-2 gap-3 text-sm"
|
||||
>
|
||||
<div>
|
||||
<dt class="text-xs text-muted">
|
||||
{{ t('storage.backup.previewImages') }}
|
||||
</dt>
|
||||
<dd class="mt-0.5 font-semibold tabular-nums">
|
||||
{{ formatCount(preview.imageCount) }}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted">
|
||||
{{ t('storage.backup.previewSize') }}
|
||||
</dt>
|
||||
<dd class="mt-0.5 font-semibold tabular-nums">
|
||||
{{ formatFileSize(preview.imageBytes) }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<UAlert
|
||||
v-if="deleteSource"
|
||||
class="mt-4"
|
||||
color="warning"
|
||||
variant="subtle"
|
||||
icon="i-lucide-triangle-alert"
|
||||
:description="t('storage.backup.syncDeleteWarning')"
|
||||
/>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<UButton
|
||||
:label="t('common.cancel')"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="() => { confirmOpen = false }"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('storage.backup.syncConfirm')"
|
||||
size="sm"
|
||||
icon="i-lucide-play"
|
||||
:loading="busy"
|
||||
@click="confirmSync"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</article>
|
||||
</template>
|
||||
@@ -0,0 +1,141 @@
|
||||
<script setup lang="ts">
|
||||
import type { BackupEstimate } from '~/types/backup'
|
||||
|
||||
defineProps<{
|
||||
estimate: BackupEstimate | null
|
||||
loading: boolean
|
||||
busy: boolean
|
||||
disabled?: boolean
|
||||
activeJob?: { progress: number, total: number, message: string } | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
export: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const { formatFileSize } = useFileSize()
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="flex h-full flex-col rounded-xl border border-default bg-elevated p-4 sm:p-5">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
|
||||
<UIcon
|
||||
name="i-lucide-archive"
|
||||
class="size-5"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ t('storage.backup.exportTitle') }}
|
||||
</h3>
|
||||
<p class="mt-0.5 text-sm text-muted">
|
||||
{{ t('storage.backup.exportSubtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-1 flex-col space-y-2">
|
||||
<div
|
||||
v-if="loading"
|
||||
class="flex items-center gap-2 text-sm text-muted"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-4 animate-spin"
|
||||
/>
|
||||
{{ t('storage.backup.estimateLoading') }}
|
||||
</div>
|
||||
|
||||
<dl
|
||||
v-else-if="estimate"
|
||||
class="space-y-1.5 rounded-lg bg-muted/25 px-3 py-2.5 text-sm"
|
||||
>
|
||||
<div class="flex items-baseline justify-between gap-2">
|
||||
<dt class="text-muted">
|
||||
{{ t('storage.backup.estimateImageCountLabel') }}
|
||||
</dt>
|
||||
<dd class="font-medium tabular-nums">
|
||||
{{ estimate.imageCount }} · {{ formatFileSize(estimate.imageBytes) }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex items-baseline justify-between gap-2">
|
||||
<dt class="text-muted">
|
||||
{{ t('storage.backup.estimateDatabaseSnapshotLabel') }}
|
||||
</dt>
|
||||
<dd class="font-medium tabular-nums">
|
||||
{{ formatFileSize(estimate.databaseBytes) }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex items-baseline justify-between gap-2 border-t border-default/40 pt-1.5">
|
||||
<dt class="font-medium text-default">
|
||||
{{ t('storage.backup.estimatePackageSizeLabel') }}
|
||||
</dt>
|
||||
<dd class="font-semibold tabular-nums">
|
||||
{{ formatFileSize(estimate.totalBytes) }}
|
||||
</dd>
|
||||
</div>
|
||||
<div class="flex items-baseline justify-between gap-2 border-t border-default/40 pt-1.5">
|
||||
<dt class="text-muted">
|
||||
{{ t('storage.backup.estimateStoragePathLabel') }}
|
||||
</dt>
|
||||
<dd class="truncate font-mono text-xs font-medium">
|
||||
{{ t('storage.backup.estimateStoragePathValue') }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<div
|
||||
v-if="estimate && !loading"
|
||||
class="mt-auto rounded-lg bg-muted/15 px-3 py-2.5"
|
||||
>
|
||||
<p class="text-xs font-medium text-default">
|
||||
{{ t('storage.backup.exportIncludesTitle') }}
|
||||
</p>
|
||||
<ul class="mt-2 space-y-1.5 text-xs leading-relaxed text-muted">
|
||||
<li class="flex items-start gap-2">
|
||||
<UIcon
|
||||
name="i-lucide-check"
|
||||
class="mt-0.5 size-3.5 shrink-0 text-primary"
|
||||
/>
|
||||
<span>{{ t('storage.backup.exportIncludesDb') }}</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<UIcon
|
||||
name="i-lucide-check"
|
||||
class="mt-0.5 size-3.5 shrink-0 text-primary"
|
||||
/>
|
||||
<span>{{ t('storage.backup.exportIncludesImages', { count: estimate.imageCount }) }}</span>
|
||||
</li>
|
||||
<li class="flex items-start gap-2">
|
||||
<UIcon
|
||||
name="i-lucide-minus"
|
||||
class="mt-0.5 size-3.5 shrink-0 text-muted"
|
||||
/>
|
||||
<span>{{ t('storage.backup.exportExcludesSecrets') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<StorageBackupJobProgress
|
||||
v-if="busy && activeJob"
|
||||
class="mt-2"
|
||||
:message="activeJob.message"
|
||||
:progress="activeJob.progress"
|
||||
:total="activeJob.total"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-auto border-t border-default pt-4">
|
||||
<UButton
|
||||
:label="t('storage.backup.exportAction')"
|
||||
icon="i-lucide-download"
|
||||
size="sm"
|
||||
:loading="busy"
|
||||
:disabled="disabled || busy"
|
||||
@click="emit('export')"
|
||||
/>
|
||||
</div>
|
||||
</article>
|
||||
</template>
|
||||
@@ -0,0 +1,32 @@
|
||||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
message: string
|
||||
progress: number
|
||||
total: number
|
||||
}>()
|
||||
|
||||
const percent = computed(() => {
|
||||
if (!props.total) return 0
|
||||
return Math.min(100, Math.round((props.progress / props.total) * 100))
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-1.5">
|
||||
<div class="flex items-center justify-between gap-2 text-xs text-muted">
|
||||
<span class="truncate">{{ message }}</span>
|
||||
<span
|
||||
v-if="total > 0"
|
||||
class="shrink-0 tabular-nums"
|
||||
>
|
||||
{{ progress }} / {{ total }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="h-1 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
class="h-full rounded-full bg-primary transition-all duration-300"
|
||||
:style="{ width: `${percent}%` }"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,310 @@
|
||||
<script setup lang="ts">
|
||||
import type { BackupJobItem } from '~/types/backup'
|
||||
|
||||
defineProps<{
|
||||
jobs: BackupJobItem[]
|
||||
polling: boolean
|
||||
page: number
|
||||
totalPages: number
|
||||
total: number
|
||||
pageSize: number
|
||||
showHidden: boolean
|
||||
loading?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'retry': [jobId: string]
|
||||
'download': [jobId: string]
|
||||
'cancel': [jobId: string]
|
||||
'hide': [jobId: string, hidden: boolean]
|
||||
'hideAll': [hidden: boolean]
|
||||
'toggleHidden': []
|
||||
'view': [job: BackupJobItem]
|
||||
'update:page': [page: number]
|
||||
'update:pageSize': [pageSize: number]
|
||||
}>()
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
|
||||
function typeLabel(type: BackupJobItem['type']): string {
|
||||
const map: Record<BackupJobItem['type'], string> = {
|
||||
full_export: t('storage.backup.jobTypeExport'),
|
||||
full_restore: t('storage.backup.jobTypeRestore'),
|
||||
backend_sync: t('storage.backup.jobTypeSync'),
|
||||
site_sync: t('storage.backup.jobTypeSiteSync')
|
||||
}
|
||||
return map[type]
|
||||
}
|
||||
|
||||
function statusColor(status: BackupJobItem['status']): 'success' | 'error' | 'warning' | 'neutral' {
|
||||
if (status === 'done') return 'success'
|
||||
if (status === 'failed') return 'error'
|
||||
if (status === 'running') return 'warning'
|
||||
return 'neutral'
|
||||
}
|
||||
|
||||
function statusLabel(status: BackupJobItem['status']): string {
|
||||
const map: Record<BackupJobItem['status'], string> = {
|
||||
pending: t('storage.backup.statusPending'),
|
||||
running: t('storage.backup.statusRunning'),
|
||||
done: t('storage.backup.statusDone'),
|
||||
failed: t('storage.backup.statusFailed')
|
||||
}
|
||||
return map[status]
|
||||
}
|
||||
|
||||
function progressPercent(job: BackupJobItem): number {
|
||||
if (!job.total) return job.status === 'done' ? 100 : 0
|
||||
return Math.min(100, Math.round((job.progress / job.total) * 100))
|
||||
}
|
||||
|
||||
function progressUnit(job: BackupJobItem): string {
|
||||
return job.type === 'full_restore'
|
||||
? t('storage.backup.progressUnitObjects')
|
||||
: t('storage.backup.progressUnitMedia')
|
||||
}
|
||||
|
||||
function jobMessage(job: BackupJobItem): string {
|
||||
if (job.status === 'failed') {
|
||||
return job.error || job.message || t('storage.backup.jobFailedUnknown')
|
||||
}
|
||||
if (job.status === 'running' || job.status === 'pending') {
|
||||
return job.message
|
||||
}
|
||||
if (job.status === 'done' && job.message) {
|
||||
return job.message
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
function canRetry(job: BackupJobItem): boolean {
|
||||
return job.type === 'backend_sync' && job.status === 'failed'
|
||||
}
|
||||
|
||||
function canCancel(job: BackupJobItem): boolean {
|
||||
return job.status === 'running' || job.status === 'pending'
|
||||
}
|
||||
|
||||
function canView(job: BackupJobItem): boolean {
|
||||
return job.type === 'full_restore' && job.status === 'done' && Boolean(job.message)
|
||||
}
|
||||
|
||||
function canHide(job: BackupJobItem): boolean {
|
||||
return job.status === 'done' || job.status === 'failed' || job.hidden
|
||||
}
|
||||
|
||||
function formatTime(value: string) {
|
||||
if (!value) return '—'
|
||||
return new Date(value).toLocaleString(locale.value, { hour12: false })
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="overflow-hidden rounded-xl border border-default bg-elevated">
|
||||
<header class="flex items-center justify-between gap-3 border-b border-default/50 px-4 py-4 sm:px-5">
|
||||
<div>
|
||||
<h3 class="text-sm font-semibold">
|
||||
{{ t('storage.backup.jobsTitle') }}
|
||||
</h3>
|
||||
<p class="mt-0.5 text-xs text-muted">
|
||||
{{ t('storage.backup.jobsSubtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex shrink-0 items-center gap-2">
|
||||
<UIcon
|
||||
v-if="polling"
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-4 animate-spin text-muted"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
:icon="showHidden ? 'i-lucide-eye-off' : 'i-lucide-eye'"
|
||||
:label="showHidden
|
||||
? t('storage.backup.hiddenJobsHide')
|
||||
: t('storage.backup.hiddenJobsShow')"
|
||||
@click="emit('toggleHidden')"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
:icon="showHidden ? 'i-lucide-rotate-ccw' : 'i-lucide-x'"
|
||||
:label="showHidden
|
||||
? t('storage.backup.jobsRestoreAll')
|
||||
: t('storage.backup.jobsHideAll')"
|
||||
@click="emit('hideAll', !showHidden)"
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-if="!jobs.length && !loading"
|
||||
class="flex flex-col items-center gap-2 px-4 py-12 text-center sm:px-5"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-clipboard-list"
|
||||
class="size-7 text-muted"
|
||||
/>
|
||||
<p class="text-sm text-muted">
|
||||
{{ t('storage.backup.jobsEmpty') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="overflow-x-auto"
|
||||
>
|
||||
<table class="w-full min-w-[800px] text-left text-sm">
|
||||
<thead>
|
||||
<tr class="border-b border-default/50 text-xs text-muted">
|
||||
<th class="px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('storage.backup.colTask') }}
|
||||
</th>
|
||||
<th class="px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('storage.backup.colStatus') }}
|
||||
</th>
|
||||
<th class="px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('storage.backup.colMessage') }}
|
||||
</th>
|
||||
<th class="px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('storage.backup.colProgress') }}
|
||||
</th>
|
||||
<th class="px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('storage.backup.colUpdated') }}
|
||||
</th>
|
||||
<th class="px-4 py-3 font-medium sm:px-5">
|
||||
{{ t('storage.backup.colActions') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr
|
||||
v-for="job in jobs"
|
||||
:key="job.id"
|
||||
class="border-b border-default/40 last:border-0"
|
||||
>
|
||||
<td class="px-4 py-3.5 whitespace-nowrap font-medium sm:px-5">
|
||||
{{ typeLabel(job.type) }}
|
||||
</td>
|
||||
<td class="px-4 py-3.5 sm:px-5">
|
||||
<UBadge
|
||||
:color="statusColor(job.status)"
|
||||
variant="subtle"
|
||||
size="sm"
|
||||
>
|
||||
{{ statusLabel(job.status) }}
|
||||
</UBadge>
|
||||
</td>
|
||||
<td class="max-w-xs px-4 py-3.5 sm:px-5">
|
||||
<p
|
||||
v-if="jobMessage(job)"
|
||||
class="line-clamp-2 text-xs leading-relaxed"
|
||||
:class="job.status === 'failed' ? 'text-error' : 'text-muted'"
|
||||
:title="jobMessage(job)"
|
||||
>
|
||||
{{ jobMessage(job) }}
|
||||
</p>
|
||||
<span
|
||||
v-else
|
||||
class="text-xs text-dimmed"
|
||||
>—</span>
|
||||
</td>
|
||||
<td class="min-w-40 px-4 py-3.5 sm:px-5">
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="h-1 min-w-0 flex-1 overflow-hidden rounded-full bg-muted">
|
||||
<div
|
||||
class="h-full rounded-full bg-primary transition-all"
|
||||
:class="{ 'animate-pulse': job.status === 'running' }"
|
||||
:style="{ width: `${progressPercent(job)}%` }"
|
||||
/>
|
||||
</div>
|
||||
<span class="flex shrink-0 flex-col text-right">
|
||||
<span class="text-xs tabular-nums text-muted">
|
||||
<template v-if="job.total">{{ job.progress }}/{{ job.total }}</template>
|
||||
<template v-else-if="job.status === 'done'">100%</template>
|
||||
<template v-else>—</template>
|
||||
</span>
|
||||
<span class="text-[10px] text-dimmed">
|
||||
{{ progressUnit(job) }}
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td class="px-4 py-3.5 whitespace-nowrap text-xs text-muted sm:px-5">
|
||||
{{ formatTime(job.updatedAt || job.finishedAt || job.createdAt) }}
|
||||
</td>
|
||||
<td class="px-4 py-3.5 sm:px-5">
|
||||
<div class="flex flex-wrap gap-1.5">
|
||||
<UButton
|
||||
v-if="job.downloadable"
|
||||
:label="t('storage.backup.download')"
|
||||
icon="i-lucide-download"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="emit('download', job.id)"
|
||||
/>
|
||||
<UButton
|
||||
v-if="canView(job)"
|
||||
:label="t('storage.backup.jobView')"
|
||||
icon="i-lucide-eye"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="emit('view', job)"
|
||||
/>
|
||||
<UButton
|
||||
v-if="canCancel(job)"
|
||||
:label="t('storage.backup.cancel')"
|
||||
icon="i-lucide-x"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
color="warning"
|
||||
@click="emit('cancel', job.id)"
|
||||
/>
|
||||
<UButton
|
||||
v-if="canRetry(job)"
|
||||
:label="t('storage.backup.retry')"
|
||||
icon="i-lucide-rotate-ccw"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="emit('retry', job.id)"
|
||||
/>
|
||||
<UButton
|
||||
v-if="canHide(job)"
|
||||
size="xs"
|
||||
variant="outline"
|
||||
:color="job.hidden ? 'neutral' : 'error'"
|
||||
:icon="job.hidden ? 'i-lucide-eye' : 'i-lucide-x'"
|
||||
:title="job.hidden
|
||||
? t('storage.backup.jobUnhide')
|
||||
: t('storage.backup.jobHide')"
|
||||
@click="emit('hide', job.id, !job.hidden)"
|
||||
/>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="total > 0"
|
||||
class="border-t border-default/50 px-4 py-4 sm:px-5"
|
||||
>
|
||||
<PaginationBar
|
||||
:page="page"
|
||||
:total-pages="totalPages"
|
||||
:total="total"
|
||||
:page-size="pageSize"
|
||||
:loading="loading"
|
||||
:unit="t('storage.backup.jobsUnit')"
|
||||
@update:page="emit('update:page', $event)"
|
||||
@update:page-size="emit('update:pageSize', $event)"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,322 @@
|
||||
<script setup lang="ts">
|
||||
import type { BackupPackageItem, BackupRestorePreview } from '~/types/backup'
|
||||
|
||||
const props = defineProps<{
|
||||
packages: BackupPackageItem[]
|
||||
busy: boolean
|
||||
disabled?: boolean
|
||||
restoreBusy?: boolean
|
||||
activeJob?: { progress: number, total: number, message: string } | null
|
||||
previewRestore: (input: { file?: File, archiveName?: string }) => Promise<BackupRestorePreview>
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
restore: [input: { file?: File, archiveName?: string, conflictMode: 'skip' | 'overwrite' }]
|
||||
}>()
|
||||
|
||||
const { t, locale } = useI18n()
|
||||
const { formatFileSize } = useFileSize()
|
||||
const toast = useToast()
|
||||
|
||||
const fileInput = ref<HTMLInputElement | null>(null)
|
||||
const selectedFile = ref<File | null>(null)
|
||||
const selectedPackage = ref<string>('')
|
||||
const conflictMode = ref<'skip' | 'overwrite'>('skip')
|
||||
const preview = ref<BackupRestorePreview | null>(null)
|
||||
const previewLoading = ref(false)
|
||||
const confirmOpen = ref(false)
|
||||
|
||||
const conflictItems = computed(() => [
|
||||
{ label: t('storage.backup.conflictSkip'), value: 'skip' },
|
||||
{ label: t('storage.backup.conflictOverwrite'), value: 'overwrite' }
|
||||
])
|
||||
|
||||
const selectMenuUi = {
|
||||
content: 'min-w-[var(--reka-select-trigger-width)] w-max max-w-[min(100vw-2rem,24rem)]',
|
||||
item: 'whitespace-normal',
|
||||
itemLabel: 'whitespace-normal'
|
||||
}
|
||||
|
||||
const packageOptions = computed(() =>
|
||||
props.packages.map(pkg => ({
|
||||
label: `${shortenName(pkg.name)} (${formatFileSize(pkg.bytes)})`,
|
||||
value: pkg.name
|
||||
}))
|
||||
)
|
||||
|
||||
function shortenName(name: string) {
|
||||
if (name.length <= 36) return name
|
||||
return `${name.slice(0, 22)}…${name.slice(-10)}`
|
||||
}
|
||||
|
||||
function formatTime(value: string) {
|
||||
if (!value) return '—'
|
||||
return new Date(value).toLocaleString(locale.value, { hour12: false })
|
||||
}
|
||||
|
||||
function getErrorMessage(error: unknown) {
|
||||
const value = error as {
|
||||
data?: { data?: { message?: string }, message?: string }
|
||||
statusMessage?: string
|
||||
message?: string
|
||||
}
|
||||
return value?.data?.data?.message
|
||||
?? value?.data?.message
|
||||
?? value?.statusMessage
|
||||
?? value?.message
|
||||
?? t('storage.backup.previewFailed')
|
||||
}
|
||||
|
||||
function pickFile() {
|
||||
fileInput.value?.click()
|
||||
}
|
||||
|
||||
function onFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
const file = input.files?.[0] ?? null
|
||||
if (!file) return
|
||||
selectedFile.value = file
|
||||
selectedPackage.value = ''
|
||||
preview.value = null
|
||||
if (input) input.value = ''
|
||||
}
|
||||
|
||||
function selectPackage(name: string | null) {
|
||||
if (!name) {
|
||||
selectedPackage.value = ''
|
||||
return
|
||||
}
|
||||
selectedPackage.value = name
|
||||
selectedFile.value = null
|
||||
preview.value = null
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!selectedFile.value && !selectedPackage.value) {
|
||||
toast.add({ title: t('storage.backup.restoreSelectRequired'), color: 'warning' })
|
||||
return
|
||||
}
|
||||
previewLoading.value = true
|
||||
try {
|
||||
preview.value = await props.previewRestore({
|
||||
file: selectedFile.value ?? undefined,
|
||||
archiveName: selectedPackage.value || undefined
|
||||
})
|
||||
confirmOpen.value = true
|
||||
} catch (error: unknown) {
|
||||
toast.add({
|
||||
title: t('storage.backup.previewFailed'),
|
||||
description: getErrorMessage(error),
|
||||
color: 'error'
|
||||
})
|
||||
} finally {
|
||||
previewLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function confirmRestore() {
|
||||
emit('restore', {
|
||||
file: selectedFile.value ?? undefined,
|
||||
archiveName: selectedPackage.value || undefined,
|
||||
conflictMode: conflictMode.value
|
||||
})
|
||||
confirmOpen.value = false
|
||||
selectedFile.value = null
|
||||
selectedPackage.value = ''
|
||||
preview.value = null
|
||||
}
|
||||
|
||||
const sourceLabel = computed(() => selectedFile.value?.name || selectedPackage.value || '')
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="flex h-full flex-col rounded-xl border border-default bg-elevated p-4 sm:p-5">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-warning/10 text-warning">
|
||||
<UIcon
|
||||
name="i-lucide-upload"
|
||||
class="size-5"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ t('storage.backup.restoreTitle') }}
|
||||
</h3>
|
||||
<p class="mt-0.5 text-sm text-muted">
|
||||
{{ t('storage.backup.restoreSubtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 flex flex-1 flex-col space-y-3">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.restoreUploadLabel') }}</label>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full flex-col items-center gap-1.5 rounded-lg border-2 border-dashed px-3 py-2.5 text-center transition-colors disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:class="selectedFile
|
||||
? 'border-primary/50 bg-primary/5'
|
||||
: 'border-warning/40 bg-warning/5 hover:border-warning/60 hover:bg-warning/10'"
|
||||
:disabled="disabled || busy"
|
||||
@click="pickFile"
|
||||
>
|
||||
<div
|
||||
class="flex size-8 items-center justify-center rounded-full"
|
||||
:class="selectedFile ? 'bg-primary/15 text-primary' : 'bg-warning/15 text-warning'"
|
||||
>
|
||||
<UIcon
|
||||
:name="selectedFile ? 'i-lucide-check' : 'i-lucide-upload'"
|
||||
class="size-4.5"
|
||||
/>
|
||||
</div>
|
||||
<span class="max-w-full truncate text-sm font-medium text-default">
|
||||
{{ selectedFile?.name ?? t('storage.backup.restoreUpload') }}
|
||||
</span>
|
||||
<span
|
||||
v-if="!selectedFile"
|
||||
class="text-xs text-muted"
|
||||
>
|
||||
{{ t('storage.backup.restoreUploadHint') }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="packages.length"
|
||||
class="space-y-1.5"
|
||||
>
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.restoreServerPackages') }}</label>
|
||||
<USelect
|
||||
:model-value="selectedPackage || undefined"
|
||||
:items="packageOptions"
|
||||
size="sm"
|
||||
class="w-full"
|
||||
:ui="selectMenuUi"
|
||||
:placeholder="t('storage.backup.restoreServerSelectPlaceholder')"
|
||||
:disabled="disabled || busy"
|
||||
@update:model-value="selectPackage"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.conflictMode') }}</label>
|
||||
<URadioGroup
|
||||
v-model="conflictMode"
|
||||
:items="conflictItems"
|
||||
:disabled="disabled || busy"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<StorageBackupJobProgress
|
||||
v-if="restoreBusy && activeJob"
|
||||
class="mt-auto"
|
||||
:message="activeJob.message"
|
||||
:progress="activeJob.progress"
|
||||
:total="activeJob.total"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-auto border-t border-default pt-4">
|
||||
<UButton
|
||||
:label="t('storage.backup.restorePreviewConfirm')"
|
||||
icon="i-lucide-search"
|
||||
size="sm"
|
||||
:loading="previewLoading || restoreBusy"
|
||||
:disabled="disabled || busy"
|
||||
@click="submit"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<input
|
||||
ref="fileInput"
|
||||
type="file"
|
||||
accept=".phost.tar.gz,.tar.gz"
|
||||
class="hidden"
|
||||
@change="onFileChange"
|
||||
>
|
||||
|
||||
<UModal
|
||||
v-model:open="confirmOpen"
|
||||
:ui="{ content: 'max-w-md' }"
|
||||
>
|
||||
<template #content>
|
||||
<div class="p-5 sm:p-6">
|
||||
<h2 class="text-base font-semibold">
|
||||
{{ t('storage.backup.restoreConfirmTitle') }}
|
||||
</h2>
|
||||
<p
|
||||
v-if="sourceLabel"
|
||||
class="mt-2 truncate font-mono text-xs text-muted"
|
||||
:title="sourceLabel"
|
||||
>
|
||||
{{ sourceLabel }}
|
||||
</p>
|
||||
|
||||
<dl
|
||||
v-if="preview"
|
||||
class="mt-4 grid grid-cols-2 gap-3 text-sm"
|
||||
>
|
||||
<div>
|
||||
<dt class="text-xs text-muted">
|
||||
{{ t('storage.backup.previewImages') }}
|
||||
</dt>
|
||||
<dd class="mt-0.5 font-semibold tabular-nums">
|
||||
{{ preview.imageCount }}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted">
|
||||
{{ t('storage.backup.previewNew') }}
|
||||
</dt>
|
||||
<dd class="mt-0.5 font-semibold tabular-nums">
|
||||
{{ preview.newImages }}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted">
|
||||
{{ t('storage.backup.previewConflicts') }}
|
||||
</dt>
|
||||
<dd class="mt-0.5 font-semibold tabular-nums">
|
||||
{{ preview.conflictingImages }}
|
||||
</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt class="text-xs text-muted">
|
||||
{{ t('storage.backup.previewCreated') }}
|
||||
</dt>
|
||||
<dd class="mt-0.5 text-xs">
|
||||
{{ formatTime(preview.createdAt) }}
|
||||
</dd>
|
||||
</div>
|
||||
</dl>
|
||||
|
||||
<UAlert
|
||||
v-if="conflictMode === 'overwrite'"
|
||||
class="mt-4"
|
||||
color="warning"
|
||||
variant="subtle"
|
||||
icon="i-lucide-triangle-alert"
|
||||
:description="t('storage.backup.restoreOverwriteWarning')"
|
||||
/>
|
||||
|
||||
<div class="mt-5 flex justify-end gap-2">
|
||||
<UButton
|
||||
:label="t('common.cancel')"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="() => { confirmOpen = false }"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('storage.backup.restoreConfirm')"
|
||||
size="sm"
|
||||
color="warning"
|
||||
:loading="restoreBusy"
|
||||
@click="confirmRestore"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</article>
|
||||
</template>
|
||||
@@ -0,0 +1,330 @@
|
||||
<script setup lang="ts">
|
||||
import type {
|
||||
SiteSyncDirection,
|
||||
SiteSyncRequest
|
||||
} from '~/types/backup'
|
||||
import { loadSiteSyncForm, saveSiteSyncForm } from '~/utils/site-sync-form'
|
||||
|
||||
const props = defineProps<{
|
||||
busy: boolean
|
||||
disabled?: boolean
|
||||
activeJob?: {
|
||||
progress: number
|
||||
total: number
|
||||
message: string
|
||||
payload: Record<string, unknown>
|
||||
} | null
|
||||
resumableJob?: {
|
||||
id: string
|
||||
payload: Record<string, unknown>
|
||||
} | null
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
sync: [body: SiteSyncRequest]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const targetBaseUrl = ref('')
|
||||
const token = ref('')
|
||||
const conflictMode = ref<'skip' | 'overwrite'>('skip')
|
||||
const direction = ref<SiteSyncDirection>('push')
|
||||
const scope = ref<'all' | 'image' | 'video' | 'file'>('all')
|
||||
|
||||
function loadSavedForm() {
|
||||
if (!import.meta.client) return
|
||||
const saved = loadSiteSyncForm()
|
||||
if (saved?.targetBaseUrl) targetBaseUrl.value = saved.targetBaseUrl
|
||||
if (saved?.token) token.value = saved.token
|
||||
}
|
||||
|
||||
function persistForm() {
|
||||
saveSiteSyncForm(targetBaseUrl.value, token.value)
|
||||
}
|
||||
|
||||
watch([targetBaseUrl, token], persistForm)
|
||||
|
||||
onMounted(loadSavedForm)
|
||||
|
||||
const scopeItems = computed(() => [
|
||||
{ value: 'all' as const, label: t('storage.backup.siteSyncScopeAll') },
|
||||
{ value: 'image' as const, label: t('storage.backup.siteSyncScopeImage') },
|
||||
{ value: 'video' as const, label: t('storage.backup.siteSyncScopeVideo') },
|
||||
{ value: 'file' as const, label: t('storage.backup.siteSyncScopeFile') }
|
||||
])
|
||||
|
||||
watch(() => props.resumableJob, (job) => {
|
||||
if (!job) return
|
||||
direction.value = job.payload.direction === 'pull' ? 'pull' : 'push'
|
||||
if (typeof job.payload.targetBaseUrl === 'string') {
|
||||
targetBaseUrl.value = job.payload.targetBaseUrl
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
const canSubmit = computed(() =>
|
||||
!props.busy
|
||||
&& !props.disabled
|
||||
&& Boolean(targetBaseUrl.value.trim())
|
||||
&& Boolean(token.value.trim())
|
||||
)
|
||||
const canResume = computed(() =>
|
||||
!props.busy
|
||||
&& !props.disabled
|
||||
&& Boolean(props.resumableJob)
|
||||
&& Boolean(token.value.trim())
|
||||
)
|
||||
const fileProgress = computed(() => {
|
||||
const payload = props.activeJob?.payload
|
||||
return {
|
||||
synced: Number(payload?.filesSynced ?? 0),
|
||||
total: Number(payload?.totalFiles ?? 0)
|
||||
}
|
||||
})
|
||||
const isPull = computed(() => direction.value === 'pull')
|
||||
const canAbandon = computed(() =>
|
||||
!props.busy
|
||||
&& Boolean(props.resumableJob)
|
||||
)
|
||||
const abandonConfirm = computed(() => (
|
||||
isPull.value || token.value.trim()
|
||||
? t('storage.backup.siteSyncAbandonConfirm')
|
||||
: t('storage.backup.siteSyncAbandonWithoutTokenConfirm')
|
||||
))
|
||||
const directionSubtitle = computed(() => (
|
||||
isPull.value
|
||||
? t('storage.backup.siteSyncPullSubtitle')
|
||||
: t('storage.backup.siteSyncPushSubtitle')
|
||||
))
|
||||
const endpointLabel = computed(() => (
|
||||
isPull.value
|
||||
? t('storage.backup.siteSyncSource')
|
||||
: t('storage.backup.siteSyncTarget')
|
||||
))
|
||||
const tokenLabel = computed(() => (
|
||||
isPull.value
|
||||
? t('storage.backup.siteSyncSourceToken')
|
||||
: t('storage.backup.siteSyncToken')
|
||||
))
|
||||
const tokenPlaceholder = computed(() => (
|
||||
isPull.value
|
||||
? t('storage.backup.siteSyncSourceTokenPlaceholder')
|
||||
: t('storage.backup.siteSyncTokenPlaceholder')
|
||||
))
|
||||
const startLabel = computed(() => (
|
||||
isPull.value
|
||||
? t('storage.backup.siteSyncStartPull')
|
||||
: t('storage.backup.siteSyncStartPush')
|
||||
))
|
||||
|
||||
function submit(resume = false) {
|
||||
if (resume ? !canResume.value : !canSubmit.value) return
|
||||
emit('sync', {
|
||||
targetBaseUrl: targetBaseUrl.value.trim(),
|
||||
token: token.value.trim(),
|
||||
conflictMode: conflictMode.value,
|
||||
direction: direction.value,
|
||||
scope: scope.value,
|
||||
...(resume && props.resumableJob ? { resumeJobId: props.resumableJob.id } : {})
|
||||
})
|
||||
}
|
||||
|
||||
function startNew() {
|
||||
submit(false)
|
||||
}
|
||||
|
||||
function resumeSync() {
|
||||
submit(true)
|
||||
}
|
||||
|
||||
function abandonSync() {
|
||||
if (!canAbandon.value || !props.resumableJob) return
|
||||
if (!window.confirm(abandonConfirm.value)) return
|
||||
emit('sync', {
|
||||
targetBaseUrl: targetBaseUrl.value.trim(),
|
||||
token: token.value.trim(),
|
||||
conflictMode: conflictMode.value,
|
||||
direction: direction.value,
|
||||
abandonJobId: props.resumableJob.id
|
||||
})
|
||||
}
|
||||
|
||||
function setConflictMode(mode: 'skip' | 'overwrite') {
|
||||
conflictMode.value = mode
|
||||
}
|
||||
|
||||
function setDirection(value: SiteSyncDirection) {
|
||||
direction.value = value
|
||||
}
|
||||
|
||||
function setScope(value: 'all' | 'image' | 'video' | 'file') {
|
||||
scope.value = value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<article class="rounded-xl border border-default bg-elevated p-4 sm:p-5">
|
||||
<div class="flex items-start gap-3">
|
||||
<div class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
|
||||
<UIcon
|
||||
name="i-lucide-server-cog"
|
||||
class="size-5"
|
||||
/>
|
||||
</div>
|
||||
<div class="min-w-0">
|
||||
<h3 class="text-base font-semibold">
|
||||
{{ t('storage.backup.siteSyncTitle') }}
|
||||
</h3>
|
||||
<p class="mt-0.5 text-sm leading-relaxed text-muted">
|
||||
{{ directionSubtitle }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-4 grid gap-3 lg:grid-cols-[minmax(0,1.2fr)_minmax(0,1fr)_auto] lg:items-end">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ endpointLabel }}</label>
|
||||
<UInput
|
||||
v-model="targetBaseUrl"
|
||||
placeholder="https://target.example.com"
|
||||
size="sm"
|
||||
class="w-full"
|
||||
:disabled="busy || disabled"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ tokenLabel }}</label>
|
||||
<UInput
|
||||
v-model="token"
|
||||
type="password"
|
||||
:placeholder="tokenPlaceholder"
|
||||
size="sm"
|
||||
class="w-full"
|
||||
:disabled="busy || disabled"
|
||||
/>
|
||||
</div>
|
||||
<UButton
|
||||
:label="startLabel"
|
||||
:icon="isPull ? 'i-lucide-cloud-download' : 'i-lucide-cloud-upload'"
|
||||
color="primary"
|
||||
:loading="busy"
|
||||
:disabled="!canSubmit"
|
||||
@click="startNew"
|
||||
/>
|
||||
<UButton
|
||||
v-if="resumableJob"
|
||||
:label="t('storage.backup.siteSyncResume')"
|
||||
icon="i-lucide-play"
|
||||
color="warning"
|
||||
:loading="busy"
|
||||
:disabled="!canResume"
|
||||
class="lg:col-start-3"
|
||||
@click="resumeSync"
|
||||
/>
|
||||
<UButton
|
||||
v-if="resumableJob"
|
||||
:label="t('storage.backup.siteSyncAbandon')"
|
||||
icon="i-lucide-trash-2"
|
||||
color="error"
|
||||
variant="outline"
|
||||
:loading="busy"
|
||||
:disabled="!canAbandon"
|
||||
class="lg:col-start-3"
|
||||
@click="abandonSync"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 grid gap-3 sm:grid-cols-2">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs text-muted">{{ t('storage.backup.siteSyncDirection') }}</span>
|
||||
<UButton
|
||||
size="xs"
|
||||
:variant="direction === 'push' ? 'solid' : 'ghost'"
|
||||
:color="direction === 'push' ? 'primary' : 'neutral'"
|
||||
:label="t('storage.backup.siteSyncPush')"
|
||||
:disabled="busy || disabled"
|
||||
@click="setDirection('push')"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
:variant="direction === 'pull' ? 'solid' : 'ghost'"
|
||||
:color="direction === 'pull' ? 'primary' : 'neutral'"
|
||||
:label="t('storage.backup.siteSyncPull')"
|
||||
:disabled="busy || disabled"
|
||||
@click="setDirection('pull')"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2 sm:justify-end">
|
||||
<span class="text-xs text-muted">{{ t('storage.backup.siteSyncConflict') }}</span>
|
||||
<UButton
|
||||
size="xs"
|
||||
:variant="conflictMode === 'skip' ? 'solid' : 'ghost'"
|
||||
:color="conflictMode === 'skip' ? 'primary' : 'neutral'"
|
||||
:label="t('storage.backup.siteSyncSkip')"
|
||||
:disabled="busy || disabled"
|
||||
@click="setConflictMode('skip')"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
:variant="conflictMode === 'overwrite' ? 'solid' : 'ghost'"
|
||||
:color="conflictMode === 'overwrite' ? 'primary' : 'neutral'"
|
||||
:label="t('storage.backup.siteSyncOverwrite')"
|
||||
:disabled="busy || disabled"
|
||||
@click="setConflictMode('overwrite')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs text-muted">{{ t('storage.backup.siteSyncContent') }}</span>
|
||||
<UButton
|
||||
v-for="item in scopeItems"
|
||||
:key="item.value"
|
||||
size="xs"
|
||||
:variant="scope === item.value ? 'solid' : 'ghost'"
|
||||
:color="scope === item.value ? 'primary' : 'neutral'"
|
||||
:label="item.label"
|
||||
:disabled="busy || disabled"
|
||||
@click="setScope(item.value)"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<UAlert
|
||||
v-if="activeJob"
|
||||
class="mt-4"
|
||||
color="primary"
|
||||
variant="subtle"
|
||||
icon="i-lucide-refresh-cw"
|
||||
:description="activeJob.message"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="activeJob"
|
||||
class="mt-3 grid gap-3 rounded-lg border border-default bg-default/40 p-3 sm:grid-cols-2"
|
||||
>
|
||||
<div>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('storage.backup.siteSyncScanProgress') }}
|
||||
</p>
|
||||
<p class="mt-1 font-mono text-sm font-medium">
|
||||
{{ activeJob.message }}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('storage.backup.siteSyncFileProgress') }}
|
||||
</p>
|
||||
<p class="mt-1 font-mono text-sm font-medium">
|
||||
{{ fileProgress.synced }} / {{ fileProgress.total }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<BackupJobProgress
|
||||
v-if="activeJob"
|
||||
class="mt-2"
|
||||
:message="activeJob.message"
|
||||
:progress="activeJob.progress"
|
||||
:total="activeJob.total"
|
||||
/>
|
||||
</article>
|
||||
</template>
|
||||
@@ -0,0 +1,134 @@
|
||||
<script setup lang="ts">
|
||||
import { loadSiteSyncForm, saveSiteSyncForm } from '~/utils/site-sync-form'
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean
|
||||
keys: string[]
|
||||
scope: 'image' | 'video' | 'file'
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
'update:open': [value: boolean]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const { startSiteSync } = useBackup()
|
||||
|
||||
const targetBaseUrl = ref('')
|
||||
const token = ref('')
|
||||
const conflictMode = ref<'skip' | 'overwrite'>('skip')
|
||||
const busy = ref(false)
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (!open) return
|
||||
const saved = loadSiteSyncForm()
|
||||
if (saved) {
|
||||
targetBaseUrl.value = saved.targetBaseUrl
|
||||
token.value = saved.token
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
watch([targetBaseUrl, token], () => {
|
||||
saveSiteSyncForm(targetBaseUrl.value, token.value)
|
||||
})
|
||||
|
||||
const canSubmit = computed(() =>
|
||||
!busy.value
|
||||
&& props.keys.length > 0
|
||||
&& Boolean(targetBaseUrl.value.trim())
|
||||
&& Boolean(token.value.trim())
|
||||
)
|
||||
|
||||
function setConflict(mode: 'skip' | 'overwrite') {
|
||||
conflictMode.value = mode
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!canSubmit.value) return
|
||||
busy.value = true
|
||||
try {
|
||||
await startSiteSync({
|
||||
targetBaseUrl: targetBaseUrl.value.trim(),
|
||||
token: token.value.trim(),
|
||||
conflictMode: conflictMode.value,
|
||||
direction: 'push',
|
||||
scope: props.scope,
|
||||
keys: props.keys
|
||||
})
|
||||
emit('update:open', false)
|
||||
} catch {
|
||||
// useBackup 已提示错误
|
||||
} finally {
|
||||
busy.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<UModal
|
||||
:open="open"
|
||||
:title="t('storage.backup.syncSelectedTitle')"
|
||||
:description="t('storage.backup.syncSelectedSubtitle', { n: keys.length })"
|
||||
@update:open="emit('update:open', $event)"
|
||||
>
|
||||
<template #body>
|
||||
<div class="space-y-3">
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.siteSyncTarget') }}</label>
|
||||
<UInput
|
||||
v-model="targetBaseUrl"
|
||||
placeholder="https://target.example.com"
|
||||
size="sm"
|
||||
class="w-full"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.siteSyncToken') }}</label>
|
||||
<UInput
|
||||
v-model="token"
|
||||
type="password"
|
||||
:placeholder="t('storage.backup.siteSyncTokenPlaceholder')"
|
||||
size="sm"
|
||||
class="w-full"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-xs text-muted">{{ t('storage.backup.siteSyncConflict') }}</span>
|
||||
<UButton
|
||||
size="xs"
|
||||
:variant="conflictMode === 'skip' ? 'solid' : 'ghost'"
|
||||
:color="conflictMode === 'skip' ? 'primary' : 'neutral'"
|
||||
:label="t('storage.backup.siteSyncSkip')"
|
||||
@click="setConflict('skip')"
|
||||
/>
|
||||
<UButton
|
||||
size="xs"
|
||||
:variant="conflictMode === 'overwrite' ? 'solid' : 'ghost'"
|
||||
:color="conflictMode === 'overwrite' ? 'primary' : 'neutral'"
|
||||
:label="t('storage.backup.siteSyncOverwrite')"
|
||||
@click="setConflict('overwrite')"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #footer>
|
||||
<div class="flex justify-end gap-2">
|
||||
<UButton
|
||||
:label="t('common.cancel')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
@click="emit('update:open', false)"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('storage.backup.syncSelectedStart')"
|
||||
icon="i-lucide-cloud-upload"
|
||||
color="primary"
|
||||
:loading="busy"
|
||||
:disabled="!canSubmit"
|
||||
@click="submit"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</template>
|
||||
@@ -5,6 +5,8 @@ const props = defineProps<{
|
||||
backend: StorageBackendItem
|
||||
envOverride?: boolean
|
||||
busy?: boolean
|
||||
showMigrateIn?: boolean
|
||||
showMigrateOut?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -13,17 +15,23 @@ const emit = defineEmits<{
|
||||
test: []
|
||||
toggleEnabled: []
|
||||
delete: []
|
||||
migrateIn: []
|
||||
migrateOut: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const typeIcon = computed(() =>
|
||||
props.backend.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
|
||||
)
|
||||
const typeIcon = computed(() => {
|
||||
if (props.backend.type === 'local') return 'i-lucide-hard-drive'
|
||||
if (props.backend.type === 'telegram') return 'i-lucide-send'
|
||||
return 'i-lucide-cloud'
|
||||
})
|
||||
|
||||
const typeLabel = computed(() =>
|
||||
props.backend.type === 'local' ? t('storage.backendLocal') : t('storage.backendCloud')
|
||||
)
|
||||
const typeLabel = computed(() => {
|
||||
if (props.backend.type === 'local') return t('storage.backendLocal')
|
||||
if (props.backend.type === 'telegram') return t('storage.backendTelegram')
|
||||
return t('storage.backendCloud')
|
||||
})
|
||||
|
||||
const actionsDisabled = computed(() => props.envOverride || props.busy)
|
||||
|
||||
@@ -34,7 +42,7 @@ function canSetDefault() {
|
||||
}
|
||||
|
||||
function canEdit() {
|
||||
return props.backend.type === 's3'
|
||||
return props.backend.type === 's3' || props.backend.type === 'telegram'
|
||||
}
|
||||
|
||||
function canToggle() {
|
||||
@@ -129,6 +137,28 @@ function canDelete() {
|
||||
:disabled="actionsDisabled"
|
||||
@click="emit('setDefault')"
|
||||
/>
|
||||
<UButton
|
||||
v-if="showMigrateIn"
|
||||
:label="t('storage.backup.migrateIn')"
|
||||
:title="t('storage.backup.migrateInHint')"
|
||||
icon="i-lucide-import"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
:disabled="actionsDisabled"
|
||||
@click="emit('migrateIn')"
|
||||
/>
|
||||
<UButton
|
||||
v-if="showMigrateOut"
|
||||
:label="t('storage.backup.migrateOut')"
|
||||
:title="t('storage.backup.migrateOutHint')"
|
||||
icon="i-lucide-arrow-up-from-line"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
:disabled="actionsDisabled"
|
||||
@click="emit('migrateOut')"
|
||||
/>
|
||||
<UButton
|
||||
v-if="canEdit()"
|
||||
:label="t('common.edit')"
|
||||
|
||||
@@ -2,9 +2,10 @@
|
||||
import type { QuotaUnit } from '~/composables/useFileSize'
|
||||
import type { StorageBackendItem } from '~/types/storage'
|
||||
|
||||
type StorageProvider = 'r2' | 'cos' | 'oss' | 'aws' | 'custom'
|
||||
type StorageProvider = 'r2' | 'cos' | 'oss' | 'aws' | 'custom' | 'telegram'
|
||||
|
||||
export interface StorageFormPayload {
|
||||
backendType: 's3' | 'telegram'
|
||||
name: string
|
||||
provider: StorageProvider
|
||||
config: {
|
||||
@@ -13,10 +14,13 @@ export interface StorageFormPayload {
|
||||
bucket: string
|
||||
prefix?: string
|
||||
forcePathStyle: boolean
|
||||
chatId?: string
|
||||
apiProxyUrl?: string
|
||||
}
|
||||
secrets: {
|
||||
accessKeyId: string
|
||||
secretAccessKey: string
|
||||
botToken: string
|
||||
}
|
||||
servingMode: 'proxy' | 'public'
|
||||
publicUrl: string
|
||||
@@ -47,11 +51,18 @@ const prefix = ref('')
|
||||
const forcePathStyle = ref(false)
|
||||
const accessKeyId = ref('')
|
||||
const secretAccessKey = ref('')
|
||||
const chatId = ref('')
|
||||
const botToken = ref('')
|
||||
const apiProxyUrl = ref('')
|
||||
const servingMode = ref<'proxy' | 'public'>('proxy')
|
||||
const publicUrl = ref('')
|
||||
const quotaValue = ref('')
|
||||
const quotaUnit = ref<QuotaUnit>('GB')
|
||||
|
||||
const isTelegram = computed(() =>
|
||||
provider.value === 'telegram' || props.backend?.type === 'telegram'
|
||||
)
|
||||
|
||||
const quotaUnitOptions = computed(() =>
|
||||
QUOTA_UNITS.map(unit => ({ label: unit, value: unit }))
|
||||
)
|
||||
@@ -61,7 +72,8 @@ const providerOptions = computed(() => [
|
||||
{ label: t('storage.providerCos'), value: 'cos' as const },
|
||||
{ label: t('storage.providerOss'), value: 'oss' as const },
|
||||
{ label: t('storage.providerAws'), value: 'aws' as const },
|
||||
{ label: t('storage.providerCustom'), value: 'custom' as const }
|
||||
{ label: t('storage.providerCustom'), value: 'custom' as const },
|
||||
{ label: t('storage.providerTelegram'), value: 'telegram' as const }
|
||||
])
|
||||
|
||||
const servingModeOptions = computed(() => [
|
||||
@@ -79,6 +91,10 @@ function applyProviderTemplate(value: StorageProvider) {
|
||||
if (props.createMode) {
|
||||
name.value = providerLabel(value)
|
||||
}
|
||||
if (value === 'telegram') {
|
||||
servingMode.value = 'proxy'
|
||||
return
|
||||
}
|
||||
switch (value) {
|
||||
case 'r2':
|
||||
endpoint.value = 'https://{account_id}.r2.cloudflarestorage.com'
|
||||
@@ -114,9 +130,7 @@ function detectProvider(config: StorageBackendItem['config']): StorageProvider {
|
||||
return 'custom'
|
||||
}
|
||||
|
||||
function loadBackend(backend: StorageBackendItem | null | undefined) {
|
||||
if (!backend || backend.type !== 's3') {
|
||||
if (props.createMode) {
|
||||
function resetCreateDefaults() {
|
||||
name.value = ''
|
||||
provider.value = 'r2'
|
||||
applyProviderTemplate('r2')
|
||||
@@ -124,11 +138,36 @@ function loadBackend(backend: StorageBackendItem | null | undefined) {
|
||||
prefix.value = ''
|
||||
accessKeyId.value = ''
|
||||
secretAccessKey.value = ''
|
||||
chatId.value = ''
|
||||
botToken.value = ''
|
||||
apiProxyUrl.value = ''
|
||||
servingMode.value = 'proxy'
|
||||
publicUrl.value = ''
|
||||
quotaValue.value = ''
|
||||
quotaUnit.value = 'GB'
|
||||
}
|
||||
|
||||
function loadBackend(backend: StorageBackendItem | null | undefined) {
|
||||
if (!backend) {
|
||||
if (props.createMode) resetCreateDefaults()
|
||||
return
|
||||
}
|
||||
|
||||
if (backend.type === 'telegram') {
|
||||
name.value = backend.name
|
||||
provider.value = 'telegram'
|
||||
chatId.value = backend.config.chatId ?? ''
|
||||
apiProxyUrl.value = backend.config.apiProxyUrl ?? ''
|
||||
botToken.value = ''
|
||||
const quota = bytesToQuotaInput(backend.quotaBytes)
|
||||
quotaValue.value = quota.value
|
||||
quotaUnit.value = quota.unit
|
||||
servingMode.value = 'proxy'
|
||||
return
|
||||
}
|
||||
|
||||
if (backend.type !== 's3') {
|
||||
if (props.createMode) resetCreateDefaults()
|
||||
return
|
||||
}
|
||||
|
||||
@@ -157,7 +196,9 @@ watch(provider, (value) => {
|
||||
})
|
||||
|
||||
function handleSubmit() {
|
||||
const backendType = isTelegram.value ? 'telegram' : 's3'
|
||||
emit('submit', {
|
||||
backendType,
|
||||
name: name.value.trim() || providerLabel(provider.value),
|
||||
provider: provider.value,
|
||||
config: {
|
||||
@@ -165,13 +206,16 @@ function handleSubmit() {
|
||||
region: region.value.trim() || 'auto',
|
||||
bucket: bucket.value.trim(),
|
||||
prefix: prefix.value.trim() || undefined,
|
||||
forcePathStyle: forcePathStyle.value
|
||||
forcePathStyle: forcePathStyle.value,
|
||||
chatId: chatId.value.trim() || undefined,
|
||||
apiProxyUrl: apiProxyUrl.value.trim() || undefined
|
||||
},
|
||||
secrets: {
|
||||
accessKeyId: accessKeyId.value.trim(),
|
||||
secretAccessKey: secretAccessKey.value.trim()
|
||||
secretAccessKey: secretAccessKey.value.trim(),
|
||||
botToken: botToken.value.trim()
|
||||
},
|
||||
servingMode: servingMode.value,
|
||||
servingMode: isTelegram.value ? 'proxy' : servingMode.value,
|
||||
publicUrl: publicUrl.value.trim(),
|
||||
quotaValue: String(quotaValue.value ?? '').trim(),
|
||||
quotaUnit: quotaUnit.value
|
||||
@@ -190,6 +234,7 @@ function handleSubmit() {
|
||||
v-model="provider"
|
||||
:items="providerOptions"
|
||||
class="w-full"
|
||||
:disabled="!createMode && backend?.type === 'telegram'"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -201,6 +246,58 @@ function handleSubmit() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<template v-if="isTelegram">
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm">
|
||||
{{ t('storage.telegramChatId') }}
|
||||
<span class="text-error">*</span>
|
||||
</label>
|
||||
<UInput
|
||||
v-model="chatId"
|
||||
:placeholder="t('storage.telegramChatIdPlaceholder')"
|
||||
class="w-full font-mono text-sm"
|
||||
required
|
||||
/>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('storage.telegramChatIdHint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm">
|
||||
{{ t('storage.telegramBotToken') }}
|
||||
<span
|
||||
v-if="createMode"
|
||||
class="text-error"
|
||||
>*</span>
|
||||
</label>
|
||||
<UInput
|
||||
v-model="botToken"
|
||||
type="password"
|
||||
:placeholder="backend?.secretsMasked.botToken || ''"
|
||||
class="w-full font-mono text-sm"
|
||||
:required="createMode"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm">{{ t('storage.telegramApiProxy') }}</label>
|
||||
<UInput
|
||||
v-model="apiProxyUrl"
|
||||
:placeholder="t('storage.telegramApiProxyPlaceholder')"
|
||||
class="w-full font-mono text-sm"
|
||||
/>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('storage.telegramApiProxyHint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('storage.telegramServingHint') }}
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm">{{ t('storage.endpoint') }}</label>
|
||||
<UInput
|
||||
@@ -300,6 +397,7 @@ function handleSubmit() {
|
||||
class="w-full font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm">
|
||||
@@ -324,7 +422,7 @@ function handleSubmit() {
|
||||
/>
|
||||
</div>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('storage.quotaHint') }}
|
||||
{{ isTelegram ? t('storage.telegramQuotaHint') : t('storage.quotaHint') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
<script setup lang="ts">
|
||||
import type {
|
||||
BackupJobItem,
|
||||
SiteSyncRequest,
|
||||
SyncDraft
|
||||
} from '~/types/backup'
|
||||
import type { StorageBackendItem } from '~/types/storage'
|
||||
|
||||
const props = defineProps<{
|
||||
backends: StorageBackendItem[]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
const toast = useToast()
|
||||
const {
|
||||
jobs,
|
||||
jobsPage,
|
||||
jobsPageSize,
|
||||
jobsTotal,
|
||||
jobsTotalPages,
|
||||
jobsLoading,
|
||||
showHiddenJobs,
|
||||
estimate,
|
||||
packages,
|
||||
loadingEstimate,
|
||||
polling,
|
||||
hasActiveJob,
|
||||
getActiveJob,
|
||||
loadJobs,
|
||||
toggleShowHiddenJobs,
|
||||
hideJob,
|
||||
hideAllJobs,
|
||||
setJobsPage,
|
||||
setJobsPageSize,
|
||||
loadEstimate,
|
||||
startPolling,
|
||||
createExport,
|
||||
previewRestore,
|
||||
confirmRestore,
|
||||
previewSync,
|
||||
startSync,
|
||||
startSiteSync,
|
||||
retryJob,
|
||||
cancelJob,
|
||||
downloadUrl
|
||||
} = useBackup()
|
||||
|
||||
const syncDraft = ref<SyncDraft | null>(null)
|
||||
const syncCardRef = ref<{ applyDraft: (draft: SyncDraft) => void } | null>(null)
|
||||
const panelRef = ref<HTMLElement | null>(null)
|
||||
const syncHighlighted = ref(false)
|
||||
|
||||
const activeJob = computed(() => getActiveJob())
|
||||
const exportBusy = computed(() => activeJob.value?.type === 'full_export')
|
||||
const restoreBusy = computed(() => activeJob.value?.type === 'full_restore')
|
||||
const syncBusy = computed(() => activeJob.value?.type === 'backend_sync')
|
||||
const siteSyncBusy = computed(() => activeJob.value?.type === 'site_sync')
|
||||
const resumableSiteSyncJob = computed(() =>
|
||||
jobs.value.find(job =>
|
||||
job.type === 'site_sync'
|
||||
&& job.status === 'failed'
|
||||
&& job.payload.resumable === true
|
||||
) ?? null
|
||||
)
|
||||
const anyJobBusy = computed(() => Boolean(activeJob.value))
|
||||
|
||||
onMounted(async () => {
|
||||
await Promise.all([loadJobs(), loadEstimate()])
|
||||
if (hasActiveJob()) {
|
||||
startPolling()
|
||||
}
|
||||
})
|
||||
|
||||
function applySyncDraft(draft: SyncDraft) {
|
||||
syncDraft.value = draft
|
||||
syncCardRef.value?.applyDraft(draft)
|
||||
syncHighlighted.value = true
|
||||
window.setTimeout(() => {
|
||||
syncHighlighted.value = false
|
||||
}, 2500)
|
||||
nextTick(() => {
|
||||
panelRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
|
||||
})
|
||||
toast.add({ title: t('storage.backup.syncDraftApplied'), color: 'info' })
|
||||
}
|
||||
|
||||
defineExpose({ applySyncDraft })
|
||||
|
||||
async function onExport() {
|
||||
await createExport()
|
||||
}
|
||||
|
||||
async function onRestore(input: {
|
||||
file?: File
|
||||
archiveName?: string
|
||||
conflictMode: 'skip' | 'overwrite'
|
||||
}) {
|
||||
await confirmRestore(input)
|
||||
}
|
||||
|
||||
async function onCancel(jobId: string) {
|
||||
await cancelJob(jobId)
|
||||
}
|
||||
|
||||
async function onHideJob(jobId: string, hidden: boolean) {
|
||||
await hideJob(jobId, hidden)
|
||||
}
|
||||
|
||||
async function onHideAll(hidden: boolean) {
|
||||
await hideAllJobs(hidden)
|
||||
}
|
||||
|
||||
async function onSync(body: {
|
||||
fromBackendId: string
|
||||
toBackendId: string
|
||||
deleteSource: boolean
|
||||
setDefault: boolean
|
||||
}) {
|
||||
await startSync(body)
|
||||
}
|
||||
|
||||
async function onSiteSync(body: SiteSyncRequest) {
|
||||
await startSiteSync(body)
|
||||
}
|
||||
|
||||
function onDownload(jobId: string) {
|
||||
window.open(downloadUrl(jobId), '_blank')
|
||||
}
|
||||
|
||||
async function onRetry(jobId: string) {
|
||||
await retryJob(jobId)
|
||||
}
|
||||
|
||||
function onViewJob(job: BackupJobItem) {
|
||||
toast.add({
|
||||
title: t('storage.backup.jobTypeRestore'),
|
||||
description: job.message,
|
||||
color: 'info'
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
ref="panelRef"
|
||||
class="scroll-mt-20 space-y-4 border-t border-default pt-5"
|
||||
>
|
||||
<header>
|
||||
<h2 class="text-base font-semibold">
|
||||
{{ t('storage.backup.sectionTitle') }}
|
||||
</h2>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
{{ t('storage.backup.sectionSubtitle') }}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div class="grid grid-cols-1 items-stretch gap-4 xl:grid-cols-3">
|
||||
<StorageBackupExportCard
|
||||
class="h-full"
|
||||
:estimate="estimate"
|
||||
:loading="loadingEstimate"
|
||||
:busy="exportBusy"
|
||||
:active-job="exportBusy ? activeJob : null"
|
||||
:disabled="anyJobBusy && !exportBusy"
|
||||
@export="onExport"
|
||||
/>
|
||||
<StorageBackupRestoreCard
|
||||
class="h-full"
|
||||
:packages="packages"
|
||||
:busy="anyJobBusy"
|
||||
:restore-busy="restoreBusy"
|
||||
:active-job="restoreBusy ? activeJob : null"
|
||||
:disabled="anyJobBusy && !restoreBusy"
|
||||
:preview-restore="previewRestore"
|
||||
@restore="onRestore"
|
||||
/>
|
||||
<StorageBackendSyncCard
|
||||
ref="syncCardRef"
|
||||
class="h-full"
|
||||
:backends="props.backends"
|
||||
:sync-draft="syncDraft"
|
||||
:highlighted="syncHighlighted"
|
||||
:busy="syncBusy"
|
||||
:active-job="syncBusy ? activeJob : null"
|
||||
:disabled="anyJobBusy && !syncBusy"
|
||||
:preview-sync="previewSync"
|
||||
@sync="onSync"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<StorageSiteSyncCard
|
||||
:busy="siteSyncBusy"
|
||||
:disabled="anyJobBusy && !siteSyncBusy"
|
||||
:active-job="siteSyncBusy ? activeJob : null"
|
||||
:resumable-job="resumableSiteSyncJob"
|
||||
@sync="onSiteSync"
|
||||
/>
|
||||
|
||||
<StorageBackupJobTable
|
||||
:jobs="jobs"
|
||||
:polling="polling"
|
||||
:page="jobsPage"
|
||||
:total-pages="jobsTotalPages"
|
||||
:total="jobsTotal"
|
||||
:page-size="jobsPageSize"
|
||||
:loading="jobsLoading"
|
||||
:show-hidden="showHiddenJobs"
|
||||
@update:page="setJobsPage"
|
||||
@update:page-size="setJobsPageSize"
|
||||
@download="onDownload"
|
||||
@retry="onRetry"
|
||||
@cancel="onCancel"
|
||||
@hide="onHideJob"
|
||||
@hide-all="onHideAll"
|
||||
@toggle-hidden="toggleShowHiddenJobs"
|
||||
@view="onViewJob"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -22,6 +22,13 @@ const items = computed(() => [
|
||||
boxClass: 'border-blue-500/20 bg-blue-500/5',
|
||||
title: t('storage.supportedS3Title'),
|
||||
desc: t('storage.supportedS3Desc')
|
||||
},
|
||||
{
|
||||
icon: 'i-lucide-send',
|
||||
iconClass: 'text-sky-500',
|
||||
boxClass: 'border-sky-500/20 bg-sky-500/5',
|
||||
title: t('storage.backendTelegram'),
|
||||
desc: t('storage.supportedTelegramDesc')
|
||||
}
|
||||
])
|
||||
</script>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
export type ApiDocMethod = 'GET' | 'POST' | 'DELETE'
|
||||
export type ApiDocCategory = 'image' | 'extension' | 'system'
|
||||
export type ApiDocCategory = 'image' | 'video' | 'file' | 'extension' | 'system'
|
||||
export type ApiParamLocation = 'form-data' | 'query' | 'header' | 'body'
|
||||
|
||||
export interface ApiDocParam {
|
||||
@@ -73,11 +73,19 @@ export function buildApiDocs(ctx: ApiDocsContext): ApiDocEndpoint[] {
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.token'
|
||||
},
|
||||
{
|
||||
name: 'tagNames',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.tagNames'
|
||||
}
|
||||
],
|
||||
curl: `curl -X POST "${baseUrl}/api/images/upload" \\
|
||||
${auth} \\
|
||||
-F "image=@./demo.png"`,
|
||||
-F "image=@./demo.png" \\
|
||||
-F 'tagNames=["博客","截图"]'`,
|
||||
responseExample: `{
|
||||
"success": true,
|
||||
"items": [
|
||||
@@ -243,6 +251,659 @@ export function buildApiDocs(ctx: ApiDocsContext): ApiDocEndpoint[] {
|
||||
"success": true,
|
||||
"deleted": ["images/2026/08/a.webp"],
|
||||
"failed": []
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'videoUpload',
|
||||
category: 'video',
|
||||
method: 'POST',
|
||||
path: '/api/videos/upload',
|
||||
titleKey: 'api.docs.videoUpload.title',
|
||||
descKey: 'api.docs.videoUpload.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'video',
|
||||
type: 'file',
|
||||
location: 'form-data',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.videoUpload.video'
|
||||
},
|
||||
{
|
||||
name: 'file',
|
||||
type: 'file',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.videoUpload.file'
|
||||
},
|
||||
{
|
||||
name: 'files',
|
||||
type: 'file',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.videoUpload.files'
|
||||
},
|
||||
{
|
||||
name: 'transcode',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.videoUpload.transcode'
|
||||
},
|
||||
{
|
||||
name: 'transcodePreset',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.videoUpload.transcodePreset'
|
||||
},
|
||||
{
|
||||
name: 'transcodeBitratePercent',
|
||||
type: 'number',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.videoUpload.transcodeBitratePercent'
|
||||
},
|
||||
{
|
||||
name: 'token',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.videoUpload.token'
|
||||
},
|
||||
{
|
||||
name: 'tagNames',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.tagNames'
|
||||
}
|
||||
],
|
||||
curl: `curl -X POST "${baseUrl}/api/videos/upload" \\
|
||||
${auth} \\
|
||||
-F "video=@./demo.mp4" \\
|
||||
-F "transcode=1" \\
|
||||
-F "transcodePreset=compress" \\
|
||||
-F "transcodeBitratePercent=80" \\
|
||||
-F 'tagNames=["博客","视频"]'`,
|
||||
responseExample: `{
|
||||
"success": true,
|
||||
"items": [
|
||||
{
|
||||
"key": "videos/2026/10/abc123.mp4",
|
||||
"url": "https://pic.example.com/videos/2026/10/abc123.mp4",
|
||||
"originalName": "demo.mp4",
|
||||
"contentType": "video/mp4",
|
||||
"size": 10485760,
|
||||
"uploadedAt": "2026-10-17T03:00:00.000Z",
|
||||
"markdown": "[demo.mp4](https://pic.example.com/videos/2026/10/abc123.mp4)",
|
||||
"thumbUrl": "https://pic.example.com/videos/2026/10/abc123.webp",
|
||||
"tags": [
|
||||
{ "id": 3, "name": "博客", "color": "#22c55e" },
|
||||
{ "id": 8, "name": "视频", "color": "#3b82f6" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"accessMode": "public"
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'videoList',
|
||||
category: 'video',
|
||||
method: 'GET',
|
||||
path: '/api/files',
|
||||
titleKey: 'api.docs.videoList.title',
|
||||
descKey: 'api.docs.videoList.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'kind',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.mediaList.kindVideo'
|
||||
},
|
||||
{
|
||||
name: 'page',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.page'
|
||||
},
|
||||
{
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.limit'
|
||||
},
|
||||
{
|
||||
name: 'q',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.q'
|
||||
},
|
||||
{
|
||||
name: 'processing',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.processing'
|
||||
},
|
||||
{
|
||||
name: 'backendId',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.backendId'
|
||||
},
|
||||
{
|
||||
name: 'uploadSource',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.uploadSource'
|
||||
},
|
||||
{
|
||||
name: 'tagIds',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagIds'
|
||||
},
|
||||
{
|
||||
name: 'tagMode',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagMode'
|
||||
},
|
||||
{
|
||||
name: 'untagged',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.untagged'
|
||||
}
|
||||
],
|
||||
curl: `curl "${baseUrl}/api/files?kind=video&page=1&limit=20" \\
|
||||
${auth}`,
|
||||
responseExample: `{
|
||||
"items": [
|
||||
{
|
||||
"key": "videos/2026/10/abc123.mp4",
|
||||
"url": "https://pic.example.com/videos/2026/10/abc123.mp4",
|
||||
"originalName": "demo.mp4",
|
||||
"contentType": "video/mp4",
|
||||
"size": 3580000,
|
||||
"uploadedAt": "2026-10-17T03:00:00.000Z",
|
||||
"transcodeStatus": "done",
|
||||
"transcodeProgress": 100,
|
||||
"transcodePreset": "veryfast",
|
||||
"sourceDeleted": true,
|
||||
"thumbUrl": "https://pic.example.com/videos/2026/10/abc123.webp",
|
||||
"hlsUrl": "https://pic.example.com/videos/2026/10/abc123/index.m3u8",
|
||||
"hlsKey": "videos/2026/10/abc123/index.m3u8"
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"page": 1,
|
||||
"pageSize": 20,
|
||||
"totalPages": 1,
|
||||
"accessMode": "public"
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'videoDelete',
|
||||
category: 'video',
|
||||
method: 'DELETE',
|
||||
path: '/api/files',
|
||||
titleKey: 'api.docs.videoDelete.title',
|
||||
descKey: 'api.docs.videoDelete.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'key',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.videoDelete.key'
|
||||
}
|
||||
],
|
||||
curl: `curl -X DELETE "${baseUrl}/api/files?key=videos/2026/10/abc123.mp4" \\
|
||||
${auth}`,
|
||||
responseExample: `{
|
||||
"success": true
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'videoSearch',
|
||||
category: 'video',
|
||||
method: 'GET',
|
||||
path: '/api/videos/search',
|
||||
titleKey: 'api.docs.videoSearch.title',
|
||||
descKey: 'api.docs.videoSearch.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'q',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.mediaSearch.q'
|
||||
},
|
||||
{
|
||||
name: 'page',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.page'
|
||||
},
|
||||
{
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.limit'
|
||||
},
|
||||
{
|
||||
name: 'backendId',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.backendId'
|
||||
},
|
||||
{
|
||||
name: 'uploadSource',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.uploadSource'
|
||||
},
|
||||
{
|
||||
name: 'tagIds',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagIds'
|
||||
},
|
||||
{
|
||||
name: 'tagMode',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagMode'
|
||||
},
|
||||
{
|
||||
name: 'untagged',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.untagged'
|
||||
},
|
||||
{
|
||||
name: 'processing',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.processing'
|
||||
}
|
||||
],
|
||||
curl: `curl "${baseUrl}/api/videos/search?q=demo&page=1&limit=20" \\
|
||||
${auth}`,
|
||||
responseExample: `{
|
||||
"items": [
|
||||
{
|
||||
"key": "videos/2026/10/demo.mp4",
|
||||
"originalName": "demo.mp4",
|
||||
"contentType": "video/mp4",
|
||||
"size": 10485760,
|
||||
"transcodeStatus": "done",
|
||||
"thumbUrl": "https://pic.example.com/videos/2026/10/demo.webp",
|
||||
"hlsUrl": "https://pic.example.com/videos/2026/10/demo/index.m3u8"
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"page": 1,
|
||||
"pageSize": 20,
|
||||
"totalPages": 1,
|
||||
"accessMode": "public"
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'videoBatchDelete',
|
||||
category: 'video',
|
||||
method: 'POST',
|
||||
path: '/api/files/batch-delete',
|
||||
titleKey: 'api.docs.videoBatchDelete.title',
|
||||
descKey: 'api.docs.videoBatchDelete.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'keys',
|
||||
type: 'string[]',
|
||||
location: 'body',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.videoBatchDelete.keys'
|
||||
}
|
||||
],
|
||||
curl: `curl -X POST "${baseUrl}/api/files/batch-delete" \\
|
||||
${auth} \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"keys":["videos/2026/10/a.mp4","videos/2026/10/b.mp4"]}'`,
|
||||
responseExample: `{
|
||||
"success": true,
|
||||
"deleted": [
|
||||
"videos/2026/10/a.mp4",
|
||||
"videos/2026/10/b.mp4"
|
||||
],
|
||||
"failed": []
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'fileUpload',
|
||||
category: 'file',
|
||||
method: 'POST',
|
||||
path: '/api/files/upload',
|
||||
titleKey: 'api.docs.fileUpload.title',
|
||||
descKey: 'api.docs.fileUpload.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'file',
|
||||
type: 'file',
|
||||
location: 'form-data',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.fileUpload.file'
|
||||
},
|
||||
{
|
||||
name: 'files',
|
||||
type: 'file',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.fileUpload.files'
|
||||
},
|
||||
{
|
||||
name: 'token',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.fileUpload.token'
|
||||
},
|
||||
{
|
||||
name: 'tagNames',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.tagNames'
|
||||
}
|
||||
],
|
||||
curl: `curl -X POST "${baseUrl}/api/files/upload" \\
|
||||
${auth} \\
|
||||
-F "file=@./report.pdf" \\
|
||||
-F 'tagNames=["文档","归档"]'`,
|
||||
responseExample: `{
|
||||
"success": true,
|
||||
"items": [
|
||||
{
|
||||
"key": "files/2026/10/abc123.pdf",
|
||||
"url": "https://pic.example.com/files/2026/10/abc123.pdf",
|
||||
"originalName": "report.pdf",
|
||||
"contentType": "application/pdf",
|
||||
"size": 5242880,
|
||||
"uploadedAt": "2026-10-17T03:00:00.000Z",
|
||||
"markdown": "[report.pdf](https://pic.example.com/files/2026/10/abc123.pdf)",
|
||||
"tags": [
|
||||
{ "id": 4, "name": "文档", "color": "#f59e0b" },
|
||||
{ "id": 9, "name": "归档", "color": "#64748b" }
|
||||
]
|
||||
}
|
||||
],
|
||||
"errors": [],
|
||||
"accessMode": "public"
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'fileList',
|
||||
category: 'file',
|
||||
method: 'GET',
|
||||
path: '/api/files',
|
||||
titleKey: 'api.docs.fileList.title',
|
||||
descKey: 'api.docs.fileList.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'kind',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.mediaList.kindFile'
|
||||
},
|
||||
{
|
||||
name: 'page',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.page'
|
||||
},
|
||||
{
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.limit'
|
||||
},
|
||||
{
|
||||
name: 'q',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.q'
|
||||
},
|
||||
{
|
||||
name: 'backendId',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.backendId'
|
||||
},
|
||||
{
|
||||
name: 'uploadSource',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.uploadSource'
|
||||
},
|
||||
{
|
||||
name: 'tagIds',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagIds'
|
||||
},
|
||||
{
|
||||
name: 'tagMode',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagMode'
|
||||
},
|
||||
{
|
||||
name: 'untagged',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.untagged'
|
||||
}
|
||||
],
|
||||
curl: `curl "${baseUrl}/api/files?kind=file&page=1&limit=20" \\
|
||||
${auth}`,
|
||||
responseExample: `{
|
||||
"items": [
|
||||
{
|
||||
"key": "files/2026/10/abc123.pdf",
|
||||
"url": "https://pic.example.com/files/2026/10/abc123.pdf",
|
||||
"originalName": "report.pdf",
|
||||
"contentType": "application/pdf",
|
||||
"size": 5242880,
|
||||
"uploadedAt": "2026-10-17T03:00:00.000Z",
|
||||
"markdown": "[report.pdf](https://pic.example.com/files/2026/10/abc123.pdf)"
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"page": 1,
|
||||
"pageSize": 20,
|
||||
"totalPages": 1,
|
||||
"accessMode": "public"
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'fileDelete',
|
||||
category: 'file',
|
||||
method: 'DELETE',
|
||||
path: '/api/files',
|
||||
titleKey: 'api.docs.fileDelete.title',
|
||||
descKey: 'api.docs.fileDelete.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'key',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.fileDelete.key'
|
||||
}
|
||||
],
|
||||
curl: `curl -X DELETE "${baseUrl}/api/files?key=files/2026/10/abc123.pdf" \\
|
||||
${auth}`,
|
||||
responseExample: `{
|
||||
"success": true
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'fileBatchDelete',
|
||||
category: 'file',
|
||||
method: 'POST',
|
||||
path: '/api/files/batch-delete',
|
||||
titleKey: 'api.docs.fileBatchDelete.title',
|
||||
descKey: 'api.docs.fileBatchDelete.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'keys',
|
||||
type: 'string[]',
|
||||
location: 'body',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.fileBatchDelete.keys'
|
||||
}
|
||||
],
|
||||
curl: `curl -X POST "${baseUrl}/api/files/batch-delete" \\
|
||||
${auth} \\
|
||||
-H "Content-Type: application/json" \\
|
||||
-d '{"keys":["files/2026/10/a.pdf","files/2026/10/b.zip"]}'`,
|
||||
responseExample: `{
|
||||
"success": true,
|
||||
"deleted": [
|
||||
"files/2026/10/a.pdf",
|
||||
"files/2026/10/b.zip"
|
||||
],
|
||||
"failed": []
|
||||
}`
|
||||
},
|
||||
{
|
||||
id: 'fileSearch',
|
||||
category: 'file',
|
||||
method: 'GET',
|
||||
path: '/api/files/search',
|
||||
titleKey: 'api.docs.fileSearch.title',
|
||||
descKey: 'api.docs.fileSearch.desc',
|
||||
requiresAuth: true,
|
||||
params: [
|
||||
{
|
||||
name: 'kind',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.mediaList.kindFile'
|
||||
},
|
||||
{
|
||||
name: 'q',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: true,
|
||||
descriptionKey: 'api.params.mediaSearch.q'
|
||||
},
|
||||
{
|
||||
name: 'page',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.page'
|
||||
},
|
||||
{
|
||||
name: 'limit',
|
||||
type: 'number',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.limit'
|
||||
},
|
||||
{
|
||||
name: 'backendId',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.backendId'
|
||||
},
|
||||
{
|
||||
name: 'uploadSource',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.uploadSource'
|
||||
},
|
||||
{
|
||||
name: 'tagIds',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagIds'
|
||||
},
|
||||
{
|
||||
name: 'tagMode',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.tagMode'
|
||||
},
|
||||
{
|
||||
name: 'untagged',
|
||||
type: 'string',
|
||||
location: 'query',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.mediaList.untagged'
|
||||
}
|
||||
],
|
||||
curl: `curl "${baseUrl}/api/files/search?kind=file&q=report&page=1&limit=20" \\
|
||||
${auth}`,
|
||||
responseExample: `{
|
||||
"items": [
|
||||
{
|
||||
"key": "files/2026/10/report.pdf",
|
||||
"url": "https://pic.example.com/files/2026/10/report.pdf",
|
||||
"originalName": "report.pdf",
|
||||
"contentType": "application/pdf",
|
||||
"size": 5242880,
|
||||
"uploadedAt": "2026-10-17T03:00:00.000Z",
|
||||
"markdown": "[report.pdf](https://pic.example.com/files/2026/10/report.pdf)"
|
||||
}
|
||||
],
|
||||
"total": 1,
|
||||
"page": 1,
|
||||
"pageSize": 20,
|
||||
"totalPages": 1,
|
||||
"accessMode": "public"
|
||||
}`
|
||||
},
|
||||
{
|
||||
|
||||
+58
-12
@@ -1,3 +1,5 @@
|
||||
import type { LoginVerificationPayload } from '~/types/auth'
|
||||
|
||||
export type AuthStatus = 'checking' | 'authenticated' | 'unauthenticated'
|
||||
|
||||
export type UserRole = 'admin' | 'user'
|
||||
@@ -8,11 +10,18 @@ export interface AuthUser {
|
||||
role: UserRole
|
||||
}
|
||||
|
||||
export interface LoginVerificationPublicConfig {
|
||||
method: 'slider' | 'turnstile' | 'cap'
|
||||
turnstileSiteKey?: string
|
||||
capApiEndpoint?: string
|
||||
}
|
||||
|
||||
export interface AuthStatusResponse {
|
||||
initialized: boolean
|
||||
allowRegistration: boolean
|
||||
legacyMode: boolean
|
||||
needsMigration: boolean
|
||||
loginVerification: LoginVerificationPublicConfig
|
||||
user: AuthUser | null
|
||||
}
|
||||
|
||||
@@ -66,9 +75,19 @@ export function getFetchErrorMessage(error: unknown, fallback: string): string {
|
||||
|
||||
export type AuthActionResult = { ok: true } | { ok: false, error: string }
|
||||
|
||||
export interface LoginCaptchaPayload {
|
||||
captchaId: string
|
||||
captchaPosition: number
|
||||
export type { LoginVerificationPayload }
|
||||
|
||||
function buildVerificationBody(verification: LoginVerificationPayload): Record<string, unknown> {
|
||||
if (verification.method === 'slider') {
|
||||
return {
|
||||
captchaId: verification.captchaId,
|
||||
captchaPosition: verification.captchaPosition
|
||||
}
|
||||
}
|
||||
if (verification.method === 'turnstile') {
|
||||
return { turnstileToken: verification.turnstileToken }
|
||||
}
|
||||
return { capToken: verification.capToken }
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
@@ -123,25 +142,39 @@ export function useAuth() {
|
||||
async function login(
|
||||
credentials: { username: string, password: string }
|
||||
| { secret: string },
|
||||
captcha: LoginCaptchaPayload
|
||||
): Promise<{ ok: boolean, needsMigration?: boolean, error?: string }> {
|
||||
verification: LoginVerificationPayload
|
||||
): Promise<{
|
||||
ok: boolean
|
||||
needsMigration?: boolean
|
||||
needsPasswordReset?: boolean
|
||||
resetUsername?: string
|
||||
error?: string
|
||||
}> {
|
||||
try {
|
||||
const result = await $fetch<{
|
||||
success: boolean
|
||||
needsMigration?: boolean
|
||||
requiresPasswordReset?: boolean
|
||||
username?: string
|
||||
user?: AuthUser
|
||||
}>('/api/auth/login', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: {
|
||||
...credentials,
|
||||
captchaId: captcha.captchaId,
|
||||
captchaPosition: captcha.captchaPosition
|
||||
...buildVerificationBody(verification)
|
||||
}
|
||||
})
|
||||
if (result.needsMigration) {
|
||||
return { ok: true, needsMigration: true }
|
||||
}
|
||||
if (result.requiresPasswordReset) {
|
||||
return {
|
||||
ok: false,
|
||||
needsPasswordReset: true,
|
||||
resetUsername: result.username
|
||||
}
|
||||
}
|
||||
if (result.user) {
|
||||
user.value = result.user
|
||||
}
|
||||
@@ -159,7 +192,8 @@ export function useAuth() {
|
||||
|
||||
async function register(
|
||||
username: string,
|
||||
password: string
|
||||
password: string,
|
||||
verification: LoginVerificationPayload
|
||||
): Promise<AuthActionResult> {
|
||||
const validationError = validateAuthInput(username, password)
|
||||
if (validationError) {
|
||||
@@ -172,7 +206,11 @@ export function useAuth() {
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { username: username.trim(), password }
|
||||
body: {
|
||||
username: username.trim(),
|
||||
password,
|
||||
...buildVerificationBody(verification)
|
||||
}
|
||||
}
|
||||
)
|
||||
user.value = result.user
|
||||
@@ -195,6 +233,8 @@ export function useAuth() {
|
||||
domainSeparation?: boolean
|
||||
siteBaseUrl?: string
|
||||
imageBaseUrl?: string
|
||||
videoBaseUrl?: string
|
||||
fileBaseUrl?: string
|
||||
}): Promise<AuthActionResult> {
|
||||
const validationError = validateAuthInput(input.username, input.password)
|
||||
if (validationError) {
|
||||
@@ -213,7 +253,9 @@ export function useAuth() {
|
||||
allowRegistration: input.allowRegistration,
|
||||
domainSeparation: input.domainSeparation,
|
||||
siteBaseUrl: input.siteBaseUrl,
|
||||
imageBaseUrl: input.imageBaseUrl
|
||||
imageBaseUrl: input.imageBaseUrl,
|
||||
videoBaseUrl: input.videoBaseUrl,
|
||||
fileBaseUrl: input.fileBaseUrl
|
||||
}
|
||||
}
|
||||
)
|
||||
@@ -291,15 +333,19 @@ export function useAuth() {
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await $fetch('/api/auth/logout', { method: 'POST' })
|
||||
await $fetch('/api/auth/logout', { method: 'POST', credentials: 'include' })
|
||||
} catch {
|
||||
// 忽略登出失败
|
||||
} finally {
|
||||
status.value = 'unauthenticated'
|
||||
user.value = null
|
||||
authStatus.value = null
|
||||
hasValidatedOnce.value = true
|
||||
}
|
||||
try {
|
||||
await fetchStatus()
|
||||
} catch {
|
||||
// 保留既有公开配置(loginVerification 等)
|
||||
}
|
||||
}
|
||||
|
||||
function handleAuthError(error: unknown) {
|
||||
|
||||
@@ -0,0 +1,421 @@
|
||||
import type {
|
||||
BackupEstimate,
|
||||
BackupJobItem,
|
||||
BackupPackageItem,
|
||||
BackupRestorePreview,
|
||||
BackendSyncPreview,
|
||||
SiteSyncRequest
|
||||
} from '~/types/backup'
|
||||
|
||||
const jobs = ref<BackupJobItem[]>([])
|
||||
const jobsPage = ref(1)
|
||||
const jobsPageSize = ref(10)
|
||||
const jobsTotal = ref(0)
|
||||
const jobsTotalPages = ref(1)
|
||||
const jobsLoading = ref(false)
|
||||
const showHiddenJobs = ref(false)
|
||||
const activeJobState = ref<BackupJobItem | null>(null)
|
||||
const estimate = ref<BackupEstimate | null>(null)
|
||||
const packages = ref<BackupPackageItem[]>([])
|
||||
const loadingEstimate = ref(false)
|
||||
const polling = ref(false)
|
||||
let pollTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
export function useBackup() {
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) {
|
||||
clearInterval(pollTimer)
|
||||
pollTimer = null
|
||||
}
|
||||
polling.value = false
|
||||
}
|
||||
|
||||
function hasActiveJob(): boolean {
|
||||
return activeJobState.value !== null
|
||||
}
|
||||
|
||||
function getActiveJob(): BackupJobItem | null {
|
||||
return activeJobState.value
|
||||
}
|
||||
|
||||
async function cancelJob(jobId: string) {
|
||||
try {
|
||||
await $fetch(`/api/admin/backup/jobs/${jobId}/cancel`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
})
|
||||
await loadJobs()
|
||||
toast.add({ title: t('storage.backup.cancelDone'), color: 'success' })
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.cancelFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function loadJobs(options?: { page?: number, pageSize?: number }) {
|
||||
if (options?.page !== undefined) jobsPage.value = options.page
|
||||
if (options?.pageSize !== undefined) jobsPageSize.value = options.pageSize
|
||||
jobsLoading.value = true
|
||||
try {
|
||||
const data = await $fetch<{
|
||||
jobs: BackupJobItem[]
|
||||
total: number
|
||||
page: number
|
||||
pageSize: number
|
||||
totalPages: number
|
||||
activeJob: BackupJobItem | null
|
||||
}>('/api/admin/backup/jobs', {
|
||||
credentials: 'include',
|
||||
query: {
|
||||
pageNum: jobsPage.value,
|
||||
pageSize: jobsPageSize.value,
|
||||
includeHidden: showHiddenJobs.value
|
||||
}
|
||||
})
|
||||
jobs.value = data.jobs
|
||||
jobsTotal.value = data.total
|
||||
jobsPage.value = data.page
|
||||
jobsPageSize.value = data.pageSize
|
||||
jobsTotalPages.value = data.totalPages
|
||||
activeJobState.value = data.activeJob
|
||||
if (!data.activeJob) {
|
||||
stopPolling()
|
||||
void loadEstimate().catch(() => {})
|
||||
}
|
||||
return data.jobs
|
||||
} finally {
|
||||
jobsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function setJobsPage(page: number) {
|
||||
jobsPage.value = page
|
||||
return loadJobs()
|
||||
}
|
||||
|
||||
async function setJobsPageSize(pageSize: number) {
|
||||
jobsPageSize.value = pageSize
|
||||
jobsPage.value = 1
|
||||
return loadJobs()
|
||||
}
|
||||
|
||||
async function refreshJobsFirstPage() {
|
||||
jobsPage.value = 1
|
||||
return loadJobs()
|
||||
}
|
||||
|
||||
async function toggleShowHiddenJobs() {
|
||||
showHiddenJobs.value = !showHiddenJobs.value
|
||||
jobsPage.value = 1
|
||||
await loadJobs()
|
||||
}
|
||||
|
||||
async function hideJob(jobId: string, hidden = true) {
|
||||
try {
|
||||
await $fetch('/api/admin/backup/jobs/hide', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { jobId, hidden }
|
||||
})
|
||||
if (hidden) {
|
||||
showHiddenJobs.value = false
|
||||
jobsPage.value = 1
|
||||
}
|
||||
await loadJobs()
|
||||
toast.add({
|
||||
title: hidden
|
||||
? t('storage.backup.jobHidden')
|
||||
: t('storage.backup.jobUnhidden'),
|
||||
color: 'success'
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.hideFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function hideAllJobs(hidden = true) {
|
||||
try {
|
||||
await $fetch('/api/admin/backup/jobs/hide-all', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { hidden }
|
||||
})
|
||||
if (hidden) {
|
||||
showHiddenJobs.value = false
|
||||
}
|
||||
jobsPage.value = 1
|
||||
await loadJobs()
|
||||
toast.add({
|
||||
title: hidden
|
||||
? t('storage.backup.jobsHiddenAll')
|
||||
: t('storage.backup.jobsUnhiddenAll'),
|
||||
color: 'success'
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.hideFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
async function loadEstimate() {
|
||||
loadingEstimate.value = true
|
||||
try {
|
||||
const data = await $fetch<{
|
||||
estimate: BackupEstimate
|
||||
packages: BackupPackageItem[]
|
||||
backupsDir: string
|
||||
}>('/api/admin/backup/estimate', { credentials: 'include' })
|
||||
estimate.value = data.estimate
|
||||
packages.value = data.packages
|
||||
return data
|
||||
} finally {
|
||||
loadingEstimate.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
if (pollTimer) return
|
||||
polling.value = true
|
||||
pollTimer = setInterval(() => {
|
||||
void loadJobs().catch(() => {})
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
async function createExport() {
|
||||
try {
|
||||
const data = await $fetch<{ job: BackupJobItem, estimate: BackupEstimate }>(
|
||||
'/api/admin/backup/export',
|
||||
{ method: 'POST', credentials: 'include' }
|
||||
)
|
||||
estimate.value = data.estimate
|
||||
await refreshJobsFirstPage()
|
||||
startPolling()
|
||||
toast.add({ title: t('storage.backup.exportStarted'), color: 'success' })
|
||||
return data.job
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.exportFailed'))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function previewRestore(input: {
|
||||
file?: File
|
||||
archiveName?: string
|
||||
}): Promise<BackupRestorePreview> {
|
||||
if (input.file) {
|
||||
const data = await $fetch<{ preview: BackupRestorePreview }>(
|
||||
'/api/admin/backup/restore',
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: input.file,
|
||||
headers: {
|
||||
'content-type': 'application/octet-stream',
|
||||
'x-pichost-dry-run': 'true'
|
||||
}
|
||||
}
|
||||
)
|
||||
return data.preview
|
||||
}
|
||||
|
||||
const data = await $fetch<{ preview: BackupRestorePreview }>(
|
||||
'/api/admin/backup/restore',
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: {
|
||||
archiveName: input.archiveName,
|
||||
dryRun: true
|
||||
}
|
||||
}
|
||||
)
|
||||
return data.preview
|
||||
}
|
||||
|
||||
async function confirmRestore(input: {
|
||||
file?: File
|
||||
archiveName?: string
|
||||
conflictMode: 'skip' | 'overwrite'
|
||||
}) {
|
||||
try {
|
||||
if (input.file) {
|
||||
const data = await $fetch<{ job: BackupJobItem }>(
|
||||
'/api/admin/backup/restore',
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: input.file,
|
||||
headers: {
|
||||
'content-type': 'application/octet-stream',
|
||||
'x-pichost-dry-run': 'false',
|
||||
'x-pichost-conflict-mode': input.conflictMode
|
||||
}
|
||||
}
|
||||
)
|
||||
await refreshJobsFirstPage()
|
||||
startPolling()
|
||||
toast.add({ title: t('storage.backup.restoreStarted'), color: 'success' })
|
||||
return data.job
|
||||
}
|
||||
|
||||
const data = await $fetch<{ job: BackupJobItem }>(
|
||||
'/api/admin/backup/restore',
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: {
|
||||
archiveName: input.archiveName,
|
||||
conflictMode: input.conflictMode,
|
||||
dryRun: false
|
||||
}
|
||||
}
|
||||
)
|
||||
await refreshJobsFirstPage()
|
||||
startPolling()
|
||||
toast.add({ title: t('storage.backup.restoreStarted'), color: 'success' })
|
||||
return data.job
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.restoreFailed'))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function previewSync(body: {
|
||||
fromBackendId: string
|
||||
toBackendId: string
|
||||
}): Promise<BackendSyncPreview> {
|
||||
const data = await $fetch<{ preview: BackendSyncPreview }>(
|
||||
'/api/admin/storage/sync',
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { ...body, dryRun: true }
|
||||
}
|
||||
)
|
||||
return data.preview
|
||||
}
|
||||
|
||||
async function startSync(body: {
|
||||
fromBackendId: string
|
||||
toBackendId: string
|
||||
deleteSource?: boolean
|
||||
setDefault?: boolean
|
||||
}) {
|
||||
try {
|
||||
const data = await $fetch<{ job: BackupJobItem }>(
|
||||
'/api/admin/storage/sync',
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body
|
||||
}
|
||||
)
|
||||
await refreshJobsFirstPage()
|
||||
startPolling()
|
||||
toast.add({ title: t('storage.backup.syncStarted'), color: 'success' })
|
||||
return data.job
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.syncFailed'))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function startSiteSync(body: SiteSyncRequest) {
|
||||
try {
|
||||
const data = await $fetch<{ job: BackupJobItem }>(
|
||||
'/api/admin/site-sync',
|
||||
{
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body
|
||||
}
|
||||
)
|
||||
await refreshJobsFirstPage()
|
||||
startPolling()
|
||||
const cleanupPending = Boolean(
|
||||
body.abandonJobId
|
||||
&& data.job.payload.cleanupPending === true
|
||||
)
|
||||
toast.add({
|
||||
title: cleanupPending
|
||||
? t('storage.backup.siteSyncAbandonedPendingCleanup')
|
||||
: body.abandonJobId
|
||||
? t('storage.backup.siteSyncAbandoned')
|
||||
: t('storage.backup.siteSyncStarted'),
|
||||
color: cleanupPending ? 'warning' : 'success'
|
||||
})
|
||||
return data.job
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.siteSyncFailed'))
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async function retryJob(jobId: string) {
|
||||
try {
|
||||
await $fetch(`/api/admin/backup/jobs/${jobId}/retry`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
})
|
||||
await refreshJobsFirstPage()
|
||||
startPolling()
|
||||
toast.add({ title: t('storage.backup.retryStarted'), color: 'success' })
|
||||
} catch (error: unknown) {
|
||||
handleError(error, t('storage.backup.retryFailed'))
|
||||
}
|
||||
}
|
||||
|
||||
function downloadUrl(jobId: string): string {
|
||||
return `/api/admin/backup/jobs/${jobId}/download`
|
||||
}
|
||||
|
||||
function handleError(error: unknown, fallback: string) {
|
||||
const status = typeof error === 'object' && error !== null && 'statusCode' in error
|
||||
? (error as { statusCode: number }).statusCode
|
||||
: 0
|
||||
if (status === 409) {
|
||||
toast.add({ title: t('storage.backup.jobRunning'), color: 'warning' })
|
||||
return
|
||||
}
|
||||
toast.add({ title: fallback, color: 'error' })
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
stopPolling()
|
||||
})
|
||||
|
||||
return {
|
||||
jobs,
|
||||
jobsPage,
|
||||
jobsPageSize,
|
||||
jobsTotal,
|
||||
jobsTotalPages,
|
||||
jobsLoading,
|
||||
showHiddenJobs,
|
||||
estimate,
|
||||
packages,
|
||||
loadingEstimate,
|
||||
polling,
|
||||
hasActiveJob,
|
||||
getActiveJob,
|
||||
loadJobs,
|
||||
toggleShowHiddenJobs,
|
||||
hideJob,
|
||||
hideAllJobs,
|
||||
setJobsPage,
|
||||
setJobsPageSize,
|
||||
loadEstimate,
|
||||
startPolling,
|
||||
stopPolling,
|
||||
createExport,
|
||||
previewRestore,
|
||||
confirmRestore,
|
||||
previewSync,
|
||||
startSync,
|
||||
startSiteSync,
|
||||
retryJob,
|
||||
cancelJob,
|
||||
downloadUrl
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ export function useImageList() {
|
||||
const activeStorageBackend = ref('all')
|
||||
const activeContentType = ref('all')
|
||||
const activeUploadSource = ref('all')
|
||||
const activeTagIds = ref<number[]>([])
|
||||
const activeTagMode = ref<'or' | 'and'>('or')
|
||||
const activeUntaggedOnly = ref(false)
|
||||
const storageBackendOptions = ref<Array<{ id: string, name: string }>>([])
|
||||
|
||||
function storageQueryParams(): Record<string, string> {
|
||||
@@ -38,6 +41,14 @@ export function useImageList() {
|
||||
if (uploadSource && uploadSource !== 'all') {
|
||||
params.uploadSource = uploadSource
|
||||
}
|
||||
if (activeUntaggedOnly.value) {
|
||||
params.untagged = '1'
|
||||
} else if (activeTagIds.value.length) {
|
||||
params.tagIds = activeTagIds.value.join(',')
|
||||
if (activeTagMode.value === 'and' && activeTagIds.value.length > 1) {
|
||||
params.tagMode = 'and'
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
@@ -181,12 +192,48 @@ export function useImageList() {
|
||||
}
|
||||
}
|
||||
|
||||
async function setActiveTagFilter(options: {
|
||||
tagIds?: number[]
|
||||
tagMode?: 'or' | 'and'
|
||||
untaggedOnly?: boolean
|
||||
}) {
|
||||
if (options.tagIds !== undefined) {
|
||||
activeTagIds.value = [...options.tagIds]
|
||||
}
|
||||
if (options.tagMode !== undefined) {
|
||||
activeTagMode.value = options.tagMode
|
||||
}
|
||||
if (options.untaggedOnly !== undefined) {
|
||||
activeUntaggedOnly.value = options.untaggedOnly
|
||||
}
|
||||
page.value = 1
|
||||
if (activeSearch.value) {
|
||||
await Promise.all([fetchSearch(1), fetchTotal()])
|
||||
} else {
|
||||
await Promise.all([fetchList(1), fetchTotal()])
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleTagFilter(tagId: number) {
|
||||
const next = new Set(activeTagIds.value)
|
||||
activeUntaggedOnly.value = false
|
||||
if (next.has(tagId)) {
|
||||
next.delete(tagId)
|
||||
} else {
|
||||
next.add(tagId)
|
||||
}
|
||||
await setActiveTagFilter({ tagIds: [...next] })
|
||||
}
|
||||
|
||||
async function resetFilters() {
|
||||
searchQuery.value = ''
|
||||
activeSearch.value = ''
|
||||
activeStorageBackend.value = 'all'
|
||||
activeContentType.value = 'all'
|
||||
activeUploadSource.value = 'all'
|
||||
activeTagIds.value = []
|
||||
activeTagMode.value = 'or'
|
||||
activeUntaggedOnly.value = false
|
||||
page.value = 1
|
||||
await Promise.all([fetchList(1), fetchTotal()])
|
||||
}
|
||||
@@ -278,6 +325,12 @@ export function useImageList() {
|
||||
return t('stats.summaryTotal', { total: count })
|
||||
})
|
||||
|
||||
function updateItemTags(key: string, tags: ImageItem['tags']) {
|
||||
items.value = items.value.map(item =>
|
||||
item.key === key ? { ...item, tags } : item
|
||||
)
|
||||
}
|
||||
|
||||
return {
|
||||
items,
|
||||
page,
|
||||
@@ -288,6 +341,9 @@ export function useImageList() {
|
||||
activeStorageBackend,
|
||||
activeContentType,
|
||||
activeUploadSource,
|
||||
activeTagIds,
|
||||
activeTagMode,
|
||||
activeUntaggedOnly,
|
||||
storageBackendOptions,
|
||||
searchQuery,
|
||||
activeSearch,
|
||||
@@ -300,12 +356,16 @@ export function useImageList() {
|
||||
setActiveStorageBackend,
|
||||
setActiveContentType,
|
||||
setActiveUploadSource,
|
||||
setActiveTagFilter,
|
||||
toggleTagFilter,
|
||||
resetFilters,
|
||||
loadStorageBackendOptions,
|
||||
submitSearch,
|
||||
goToPage,
|
||||
setPageSize,
|
||||
prependItems,
|
||||
removeItems
|
||||
removeItems,
|
||||
updateItemTags,
|
||||
listQueryParams
|
||||
}
|
||||
}
|
||||
@@ -4,13 +4,16 @@ import type {
|
||||
} from '~/types/image'
|
||||
import { isUnauthorizedError } from './useAuth'
|
||||
import { prepareFilesForUpload } from './useClipboardImage'
|
||||
import { normalizeUploadTagNames } from './useUploadPreferences'
|
||||
import { uploadFormDataWithProgress } from '~/utils/upload-progress'
|
||||
|
||||
const MAX_FILES = 10
|
||||
|
||||
export function useImageUpload() {
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
const { compressEnabled, clientWebpQuality } = useUploadPreferences()
|
||||
const { compressEnabled, clientWebpQuality, uploadTagNames } = useUploadPreferences()
|
||||
const { load: loadUploadPolicy } = useUploadPolicy()
|
||||
const uploading = ref(false)
|
||||
const progressItems = ref<UploadProgressItem[]>([])
|
||||
const lastUploadResult = ref<UploadResponse | null>(null)
|
||||
@@ -42,15 +45,32 @@ export function useImageUpload() {
|
||||
}))
|
||||
|
||||
try {
|
||||
const prepared = await prepareFilesForUpload(files, {
|
||||
const preparedFiles = await prepareFilesForUpload(files, {
|
||||
enabled: compressEnabled.value,
|
||||
quality: clientWebpQuality.value / 100
|
||||
})
|
||||
const currentPolicy = await loadUploadPolicy().catch(() => null)
|
||||
const maxFileSizeMb = currentPolicy?.imageMaxFileSizeMb ?? 10
|
||||
const prepared = preparedFiles.filter((file) => {
|
||||
if (file.size <= maxFileSizeMb * 1024 * 1024) return true
|
||||
toast.add({
|
||||
title: t('files.fileTooLarge', {
|
||||
name: file.name,
|
||||
limit: maxFileSizeMb
|
||||
}),
|
||||
color: 'error'
|
||||
})
|
||||
return false
|
||||
})
|
||||
if (!prepared.length) {
|
||||
progressItems.value = []
|
||||
return
|
||||
}
|
||||
|
||||
progressItems.value = prepared.map((file, index) => ({
|
||||
progressItems.value = prepared.map(file => ({
|
||||
name: file.name,
|
||||
status: 'uploading',
|
||||
progress: Math.round(((index + 1) / prepared.length) * 50)
|
||||
progress: 0
|
||||
}))
|
||||
|
||||
const formData = new FormData()
|
||||
@@ -58,10 +78,21 @@ export function useImageUpload() {
|
||||
formData.append('files', file, file.name)
|
||||
}
|
||||
|
||||
const response = await $fetch<UploadResponse>('/api/images/upload', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
const tagNames = normalizeUploadTagNames(uploadTagNames.value).join(',')
|
||||
if (tagNames) {
|
||||
formData.append('tagNames', tagNames)
|
||||
}
|
||||
|
||||
const response = await uploadFormDataWithProgress<UploadResponse>(
|
||||
'/api/images/upload',
|
||||
formData,
|
||||
(percent) => {
|
||||
progressItems.value = progressItems.value.map(item => ({
|
||||
...item,
|
||||
progress: Math.min(99, percent)
|
||||
}))
|
||||
}
|
||||
)
|
||||
|
||||
lastUploadResult.value = response
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
const STORAGE_KEY = 'pichost.library-view'
|
||||
export type LibraryViewKind = 'image' | 'video' | 'file'
|
||||
|
||||
export type LibraryViewMode = 'grid' | 'list'
|
||||
|
||||
function storageKeyFor(kind: LibraryViewKind): string {
|
||||
return `${STORAGE_KEY}.${kind}`
|
||||
}
|
||||
|
||||
/**
|
||||
* 图库 / 视频库 / 文件库各自的显示方式。
|
||||
* 三个库分别记住(互不影响),且页面切换后保持,不用重新点。
|
||||
*/
|
||||
export function useLibraryView(kind: LibraryViewKind = 'image') {
|
||||
const viewMode = useState<LibraryViewMode>(`library-view-mode-${kind}`, () => 'grid')
|
||||
const loaded = useState(`library-view-loaded-${kind}`, () => false)
|
||||
|
||||
if (import.meta.client && !loaded.value) {
|
||||
try {
|
||||
const stored = localStorage.getItem(storageKeyFor(kind))
|
||||
if (stored === 'grid' || stored === 'list') {
|
||||
viewMode.value = stored
|
||||
}
|
||||
} catch {
|
||||
// 读取失败保持默认
|
||||
}
|
||||
loaded.value = true
|
||||
}
|
||||
|
||||
watch(viewMode, (value) => {
|
||||
if (!import.meta.client) return
|
||||
try {
|
||||
localStorage.setItem(storageKeyFor(kind), value)
|
||||
} catch {
|
||||
// 写入失败不影响使用
|
||||
}
|
||||
})
|
||||
|
||||
return { viewMode }
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
import type { UploadProgressItem } from '~/types/image'
|
||||
import type { FileItem, FileListResponse, FileUploadResponse } from '~/types/file'
|
||||
import type { CopyFormat, UploadMediaKind } from './useUploadPreferences'
|
||||
import { isUnauthorizedError } from './useAuth'
|
||||
import { normalizeUploadTagNames } from './useUploadPreferences'
|
||||
import { uploadFormDataWithProgress } from '~/utils/upload-progress'
|
||||
|
||||
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 {
|
||||
load: loadUploadPolicy
|
||||
} = useUploadPolicy()
|
||||
const {
|
||||
autoCopyMarkdown,
|
||||
copyFormat,
|
||||
transcodeToHls,
|
||||
uploadTagNames,
|
||||
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 '/video-placeholder.svg'
|
||||
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
|
||||
|
||||
const currentPolicy = await loadUploadPolicy().catch(() => null)
|
||||
const acceptedFiles = files.filter((file) => {
|
||||
const extension = file.name.split('.').pop()?.toLowerCase() ?? ''
|
||||
if (
|
||||
kind === 'video'
|
||||
&& currentPolicy
|
||||
&& !currentPolicy.allowedVideoExtensions.includes(extension)
|
||||
) {
|
||||
toast.add({
|
||||
title: `${file.name}:${t('files.videoFormatBlocked', {
|
||||
format: extension ? extension.toUpperCase() : '—'
|
||||
})}`,
|
||||
color: 'error'
|
||||
})
|
||||
return false
|
||||
}
|
||||
if (
|
||||
kind === 'file'
|
||||
&& currentPolicy?.forbiddenFileExtensions.includes(extension)
|
||||
) {
|
||||
toast.add({
|
||||
title: `${file.name}:${t('files.fileFormatBlocked', {
|
||||
format: extension.toUpperCase()
|
||||
})}`,
|
||||
color: 'error'
|
||||
})
|
||||
return false
|
||||
}
|
||||
const maxFileSizeMb = kind === 'video'
|
||||
? (currentPolicy?.videoMaxFileSizeMb ?? 500)
|
||||
: (currentPolicy?.fileMaxFileSizeMb ?? 100)
|
||||
if (file.size > maxFileSizeMb * 1024 * 1024) {
|
||||
toast.add({
|
||||
title: t('files.fileTooLarge', {
|
||||
name: file.name,
|
||||
limit: maxFileSizeMb
|
||||
}),
|
||||
color: 'error'
|
||||
})
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
if (!acceptedFiles.length) return
|
||||
|
||||
if (acceptedFiles.length > MAX_FILES) {
|
||||
toast.add({ title: t('files.maxFiles', { n: MAX_FILES }), color: 'warning' })
|
||||
return
|
||||
}
|
||||
|
||||
uploading.value = true
|
||||
progressItems.value = acceptedFiles.map(file => ({
|
||||
name: file.name,
|
||||
status: 'pending',
|
||||
progress: 0
|
||||
}))
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
for (const file of acceptedFiles) {
|
||||
formData.append('files', file, file.name)
|
||||
}
|
||||
|
||||
if (kind === 'video' && transcodeToHls.value) {
|
||||
formData.append('transcode', '1')
|
||||
}
|
||||
const tagNames = normalizeUploadTagNames(uploadTagNames.value).join(',')
|
||||
if (tagNames) {
|
||||
formData.append('tagNames', tagNames)
|
||||
}
|
||||
|
||||
progressItems.value = progressItems.value.map(item => ({
|
||||
...item,
|
||||
status: 'uploading',
|
||||
progress: 0
|
||||
}))
|
||||
|
||||
const response = await uploadFormDataWithProgress<FileUploadResponse>(
|
||||
endpoint,
|
||||
formData,
|
||||
(percent) => {
|
||||
progressItems.value = progressItems.value.map(item => ({
|
||||
...item,
|
||||
progress: Math.min(99, percent)
|
||||
}))
|
||||
}
|
||||
)
|
||||
|
||||
lastResult.value = response
|
||||
accessMode.value = response.accessMode
|
||||
if (response.accessMode === 'token' && !apiToken.value) {
|
||||
await loadApiToken()
|
||||
}
|
||||
|
||||
progressItems.value = acceptedFiles.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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
const STORAGE_KEY = 'pichost.recent-tag-ids'
|
||||
const MAX_RECENT = 12
|
||||
|
||||
function readRecentIds(): number[] {
|
||||
if (import.meta.server) return []
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return []
|
||||
const parsed = JSON.parse(raw)
|
||||
if (!Array.isArray(parsed)) return []
|
||||
return parsed.filter((id: unknown): id is number => Number.isInteger(id) && (id as number) > 0)
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
function writeRecentIds(ids: number[]) {
|
||||
if (import.meta.server) return
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(ids))
|
||||
}
|
||||
|
||||
export function useRecentTags() {
|
||||
const recentIds = useState<number[]>('recent-tag-ids', () => [])
|
||||
|
||||
function loadRecentIds() {
|
||||
recentIds.value = readRecentIds()
|
||||
}
|
||||
|
||||
if (import.meta.client && !recentIds.value.length) {
|
||||
loadRecentIds()
|
||||
}
|
||||
|
||||
function recordRecent(tagIds: number[]) {
|
||||
if (!tagIds.length) return
|
||||
const merged = [
|
||||
...tagIds,
|
||||
...recentIds.value.filter(id => !tagIds.includes(id))
|
||||
].slice(0, MAX_RECENT)
|
||||
recentIds.value = merged
|
||||
writeRecentIds(merged)
|
||||
}
|
||||
|
||||
return {
|
||||
recentIds,
|
||||
loadRecentIds,
|
||||
recordRecent
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import type { ImageTag } from '~/types/image'
|
||||
|
||||
export interface TagListResponse {
|
||||
items: ImageTag[]
|
||||
}
|
||||
|
||||
export interface TagResponse {
|
||||
tag: ImageTag
|
||||
}
|
||||
|
||||
export function useTags() {
|
||||
const items = useState<ImageTag[]>('tags-list', () => [])
|
||||
const loading = ref(false)
|
||||
const loaded = ref(false)
|
||||
|
||||
async function fetchTags(force = false) {
|
||||
if (loaded.value && !force) return items.value
|
||||
loading.value = true
|
||||
try {
|
||||
const data = await $fetch<TagListResponse>('/api/tags', {
|
||||
credentials: 'include'
|
||||
})
|
||||
items.value = data.items
|
||||
loaded.value = true
|
||||
return data.items
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function createTag(name: string, color?: string | null) {
|
||||
const data = await $fetch<TagResponse>('/api/tags', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { name, color }
|
||||
})
|
||||
await fetchTags(true)
|
||||
return data.tag
|
||||
}
|
||||
|
||||
async function updateTag(id: number, patch: { name?: string, color?: string | null }) {
|
||||
const data = await $fetch<TagResponse>(`/api/tags/${id}`, {
|
||||
method: 'PATCH',
|
||||
credentials: 'include',
|
||||
body: patch
|
||||
})
|
||||
await fetchTags(true)
|
||||
return data.tag
|
||||
}
|
||||
|
||||
async function deleteTag(id: number) {
|
||||
await $fetch(`/api/tags/${id}`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include'
|
||||
})
|
||||
await fetchTags(true)
|
||||
}
|
||||
|
||||
async function mergeTags(sourceIds: number[], targetId: number) {
|
||||
const data = await $fetch<TagResponse>('/api/tags/merge', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { sourceIds, targetId }
|
||||
})
|
||||
await fetchTags(true)
|
||||
return data.tag
|
||||
}
|
||||
|
||||
async function addTagsToImage(key: string, tagIds: number[]) {
|
||||
const data = await $fetch<{ tags: ImageTag[] }>('/api/images/tags', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { key, tagIds }
|
||||
})
|
||||
return data.tags
|
||||
}
|
||||
|
||||
async function setImageTags(key: string, tagIds: number[]) {
|
||||
const data = await $fetch<{ tags: ImageTag[] }>('/api/images/tags', {
|
||||
method: 'PATCH',
|
||||
credentials: 'include',
|
||||
body: { key, tagIds }
|
||||
})
|
||||
return data.tags
|
||||
}
|
||||
|
||||
async function removeTagFromImage(key: string, tagId: number) {
|
||||
const data = await $fetch<{ tags: ImageTag[] }>('/api/images/tags', {
|
||||
method: 'DELETE',
|
||||
credentials: 'include',
|
||||
body: { key, tagId }
|
||||
})
|
||||
return data.tags
|
||||
}
|
||||
|
||||
async function batchUpdateTags(
|
||||
keys: string[],
|
||||
tagIds: number[],
|
||||
action: 'add' | 'remove' = 'add'
|
||||
) {
|
||||
return $fetch<{ success: boolean, updated: number }>('/api/images/batch-tags', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { keys, tagIds, action }
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
items,
|
||||
loading,
|
||||
loaded,
|
||||
fetchTags,
|
||||
createTag,
|
||||
updateTag,
|
||||
deleteTag,
|
||||
mergeTags,
|
||||
addTagsToImage,
|
||||
setImageTags,
|
||||
removeTagFromImage,
|
||||
batchUpdateTags
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export function useTranscodeFailureLabel() {
|
||||
const { t } = useI18n()
|
||||
|
||||
return (error?: string) => {
|
||||
const reason = error === 'ffmpeg-missing'
|
||||
? t('library.video.transcodeErrorFfmpegMissing')
|
||||
: error === 'permission-denied'
|
||||
? t('library.video.transcodeErrorPermissionDenied')
|
||||
: t('library.video.transcodeErrorUnknown')
|
||||
return `${t('library.transcodeFailed')} · ${reason}`
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
interface TranscodeSettingsResponse {
|
||||
concurrency: number
|
||||
threads: number
|
||||
preset: string
|
||||
bitratePercent: number
|
||||
maxConcurrency: number
|
||||
maxThreads: number
|
||||
minBitratePercent: number
|
||||
maxBitratePercent: number
|
||||
presets: string[]
|
||||
memoryBytes: number
|
||||
lowMemoryThresholdBytes: number
|
||||
lowMemory: boolean
|
||||
}
|
||||
|
||||
/** 服务端转码参数:并发任务数与单任务 CPU 核心数(仅管理员可改) */
|
||||
export function useTranscodeSettings() {
|
||||
const { isAuthenticated, isAdmin, handleAuthError } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
const concurrency = ref(1)
|
||||
const threads = ref(1)
|
||||
const maxConcurrency = ref(8)
|
||||
const maxThreads = ref(64)
|
||||
const preset = ref('veryfast')
|
||||
const presets = ref<string[]>(['veryfast', 'medium', 'slow'])
|
||||
const bitratePercent = ref(80)
|
||||
const minBitratePercent = ref(10)
|
||||
const maxBitratePercent = ref(100)
|
||||
const loaded = ref(false)
|
||||
const hydrated = ref(false)
|
||||
const memoryBytes = ref(0)
|
||||
const lowMemoryThresholdBytes = ref(2 * 1024 * 1024 * 1024)
|
||||
const lowMemory = ref(false)
|
||||
|
||||
let saveTimer: ReturnType<typeof setTimeout> | null = null
|
||||
|
||||
function apply(data: TranscodeSettingsResponse) {
|
||||
hydrated.value = false
|
||||
concurrency.value = data.concurrency
|
||||
threads.value = data.threads
|
||||
preset.value = data.preset
|
||||
bitratePercent.value = data.bitratePercent
|
||||
minBitratePercent.value = data.minBitratePercent ?? 10
|
||||
maxBitratePercent.value = data.maxBitratePercent ?? 100
|
||||
if (data.presets?.length) presets.value = data.presets
|
||||
maxConcurrency.value = data.maxConcurrency
|
||||
maxThreads.value = data.maxThreads
|
||||
memoryBytes.value = data.memoryBytes ?? 0
|
||||
lowMemoryThresholdBytes.value = data.lowMemoryThresholdBytes
|
||||
?? 2 * 1024 * 1024 * 1024
|
||||
lowMemory.value = data.lowMemory === true
|
||||
loaded.value = true
|
||||
nextTick(() => {
|
||||
hydrated.value = true
|
||||
})
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (!isAuthenticated.value) return
|
||||
try {
|
||||
apply(await $fetch<TranscodeSettingsResponse>('/api/videos/transcode-settings', {
|
||||
credentials: 'include'
|
||||
}))
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('preferences.transcodeLoadFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
if (!hydrated.value || !isAdmin.value) return
|
||||
try {
|
||||
const data = await $fetch<TranscodeSettingsResponse>('/api/videos/transcode-settings', {
|
||||
method: 'PATCH',
|
||||
credentials: 'include',
|
||||
body: {
|
||||
concurrency: concurrency.value,
|
||||
threads: threads.value,
|
||||
preset: preset.value,
|
||||
bitratePercent: bitratePercent.value
|
||||
}
|
||||
})
|
||||
hydrated.value = false
|
||||
concurrency.value = data.concurrency
|
||||
threads.value = data.threads
|
||||
preset.value = data.preset
|
||||
bitratePercent.value = data.bitratePercent
|
||||
nextTick(() => {
|
||||
hydrated.value = true
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('preferences.transcodeSaveFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
watch([concurrency, threads, preset, bitratePercent], () => {
|
||||
if (!hydrated.value || !isAdmin.value) return
|
||||
if (saveTimer) clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => {
|
||||
void save()
|
||||
}, 600)
|
||||
})
|
||||
|
||||
return {
|
||||
concurrency,
|
||||
threads,
|
||||
preset,
|
||||
bitratePercent,
|
||||
minBitratePercent,
|
||||
maxBitratePercent,
|
||||
presets,
|
||||
maxConcurrency,
|
||||
maxThreads,
|
||||
memoryBytes,
|
||||
lowMemoryThresholdBytes,
|
||||
lowMemory,
|
||||
loaded,
|
||||
load
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
interface UploadPolicy {
|
||||
allowedMimeTypes: string[]
|
||||
allowedVideoExtensions: string[]
|
||||
forbiddenFileExtensions: string[]
|
||||
imageMaxFileSizeMb: number
|
||||
videoMaxFileSizeMb: number
|
||||
fileMaxFileSizeMb: number
|
||||
}
|
||||
|
||||
const policy = ref<UploadPolicy | null>(null)
|
||||
const loading = ref(false)
|
||||
let pending: Promise<UploadPolicy> | null = null
|
||||
|
||||
export function useUploadPolicy() {
|
||||
async function load(force = false): Promise<UploadPolicy> {
|
||||
if (policy.value && !force) return policy.value
|
||||
if (pending && !force) return pending
|
||||
|
||||
loading.value = true
|
||||
pending = $fetch<UploadPolicy>('/api/upload-policy', {
|
||||
credentials: 'include'
|
||||
})
|
||||
.then((data) => {
|
||||
policy.value = {
|
||||
allowedMimeTypes: [...data.allowedMimeTypes],
|
||||
allowedVideoExtensions: [...data.allowedVideoExtensions],
|
||||
forbiddenFileExtensions: [...data.forbiddenFileExtensions],
|
||||
imageMaxFileSizeMb: data.imageMaxFileSizeMb,
|
||||
videoMaxFileSizeMb: data.videoMaxFileSizeMb,
|
||||
fileMaxFileSizeMb: data.fileMaxFileSizeMb
|
||||
}
|
||||
return policy.value
|
||||
})
|
||||
.finally(() => {
|
||||
loading.value = false
|
||||
pending = null
|
||||
})
|
||||
return pending
|
||||
}
|
||||
|
||||
return {
|
||||
policy,
|
||||
loading,
|
||||
load
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,41 @@
|
||||
const STORAGE_KEY = 'pichost.upload-preferences'
|
||||
|
||||
export type CopyFormat = 'url' | 'markdown' | 'html'
|
||||
export type CopyFormat = 'url' | 'markdown' | 'html' | 'bbcode'
|
||||
export type UploadMediaKind = 'image' | 'video' | 'file'
|
||||
|
||||
/** 每种上传页各存一份偏好,互不影响 */
|
||||
function storageKeyFor(kind: UploadMediaKind): string {
|
||||
return kind === 'image' ? STORAGE_KEY : `${STORAGE_KEY}.${kind}`
|
||||
}
|
||||
|
||||
export interface UploadPreferences {
|
||||
compressEnabled: boolean
|
||||
autoCopyMarkdown: boolean
|
||||
copyFormat: CopyFormat
|
||||
clientWebpQuality: number
|
||||
uploadTagNames: string[]
|
||||
/** 视频床专属:上传后转码为 HLS(m3u8 + 分片) */
|
||||
transcodeToHls: boolean
|
||||
}
|
||||
|
||||
const DEFAULTS: UploadPreferences = {
|
||||
compressEnabled: false,
|
||||
autoCopyMarkdown: false,
|
||||
copyFormat: 'markdown',
|
||||
clientWebpQuality: 80
|
||||
clientWebpQuality: 80,
|
||||
uploadTagNames: [],
|
||||
transcodeToHls: false
|
||||
}
|
||||
|
||||
export function normalizeUploadTagNames(value: string | readonly string[]): string[] {
|
||||
const parts = typeof value === 'string'
|
||||
? value.split(/[,,\n]/)
|
||||
: value.flatMap(item => String(item).split(/[,,\n]/))
|
||||
return [...new Set(
|
||||
parts
|
||||
.map(name => name.trim())
|
||||
.filter(name => Boolean(name) && name.length <= 32)
|
||||
)]
|
||||
}
|
||||
|
||||
function clampQuality(value: unknown): number {
|
||||
@@ -23,45 +45,58 @@ function clampQuality(value: unknown): number {
|
||||
}
|
||||
|
||||
function isCopyFormat(value: unknown): value is CopyFormat {
|
||||
return value === 'url' || value === 'markdown' || value === 'html'
|
||||
return value === 'url' || value === 'markdown' || value === 'html' || value === 'bbcode'
|
||||
}
|
||||
|
||||
function readStored(): UploadPreferences {
|
||||
function readStored(kind: UploadMediaKind): UploadPreferences {
|
||||
if (import.meta.server) return { ...DEFAULTS }
|
||||
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
const raw = localStorage.getItem(storageKeyFor(kind))
|
||||
if (!raw) return { ...DEFAULTS }
|
||||
const parsed = JSON.parse(raw) as Partial<UploadPreferences>
|
||||
return {
|
||||
compressEnabled: parsed.compressEnabled === true,
|
||||
autoCopyMarkdown: parsed.autoCopyMarkdown === true,
|
||||
copyFormat: isCopyFormat(parsed.copyFormat) ? parsed.copyFormat : DEFAULTS.copyFormat,
|
||||
clientWebpQuality: clampQuality(parsed.clientWebpQuality)
|
||||
clientWebpQuality: clampQuality(parsed.clientWebpQuality),
|
||||
/** 标签输入只在当前页面会话内生效,刷新后默认为空。 */
|
||||
uploadTagNames: [...DEFAULTS.uploadTagNames],
|
||||
transcodeToHls: parsed.transcodeToHls === true
|
||||
}
|
||||
} catch {
|
||||
return { ...DEFAULTS }
|
||||
}
|
||||
}
|
||||
|
||||
function writeStored(prefs: UploadPreferences) {
|
||||
function writeStored(kind: UploadMediaKind, prefs: UploadPreferences) {
|
||||
if (import.meta.server) return
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs))
|
||||
localStorage.setItem(storageKeyFor(kind), JSON.stringify(prefs))
|
||||
}
|
||||
|
||||
export function useUploadPreferences() {
|
||||
const compressEnabled = useState('upload-pref-compress', () => DEFAULTS.compressEnabled)
|
||||
const autoCopyMarkdown = useState('upload-pref-auto-md', () => DEFAULTS.autoCopyMarkdown)
|
||||
const copyFormat = useState<CopyFormat>('upload-pref-copy-format', () => DEFAULTS.copyFormat)
|
||||
const clientWebpQuality = useState('upload-pref-webp-quality', () => DEFAULTS.clientWebpQuality)
|
||||
const loaded = useState('upload-pref-loaded', () => false)
|
||||
export function useUploadPreferences(kind: UploadMediaKind = 'image') {
|
||||
const compressEnabled = useState(`upload-pref-compress-${kind}`, () => DEFAULTS.compressEnabled)
|
||||
const autoCopyMarkdown = useState(`upload-pref-auto-md-${kind}`, () => DEFAULTS.autoCopyMarkdown)
|
||||
const copyFormat = useState<CopyFormat>(`upload-pref-copy-format-${kind}`, () => DEFAULTS.copyFormat)
|
||||
const clientWebpQuality = useState(`upload-pref-webp-quality-${kind}`, () => DEFAULTS.clientWebpQuality)
|
||||
const uploadTagNames = useState<string[]>(
|
||||
`upload-pref-tag-names-${kind}`,
|
||||
() => [...DEFAULTS.uploadTagNames]
|
||||
)
|
||||
const transcodeToHls = useState(`upload-pref-transcode-${kind}`, () => DEFAULTS.transcodeToHls)
|
||||
const loaded = useState(`upload-pref-loaded-${kind}`, () => false)
|
||||
|
||||
function loadPreferences() {
|
||||
const stored = readStored()
|
||||
const firstLoad = !loaded.value
|
||||
const stored = readStored(kind)
|
||||
compressEnabled.value = stored.compressEnabled
|
||||
autoCopyMarkdown.value = stored.autoCopyMarkdown
|
||||
copyFormat.value = stored.copyFormat
|
||||
clientWebpQuality.value = stored.clientWebpQuality
|
||||
if (firstLoad) {
|
||||
uploadTagNames.value = [...stored.uploadTagNames]
|
||||
}
|
||||
transcodeToHls.value = stored.transcodeToHls
|
||||
loaded.value = true
|
||||
}
|
||||
|
||||
@@ -70,27 +105,46 @@ export function useUploadPreferences() {
|
||||
}
|
||||
|
||||
function savePreferences() {
|
||||
writeStored({
|
||||
writeStored(kind, {
|
||||
compressEnabled: compressEnabled.value,
|
||||
autoCopyMarkdown: autoCopyMarkdown.value,
|
||||
copyFormat: copyFormat.value,
|
||||
clientWebpQuality: clampQuality(clientWebpQuality.value)
|
||||
clientWebpQuality: clampQuality(clientWebpQuality.value),
|
||||
uploadTagNames: [...DEFAULTS.uploadTagNames],
|
||||
transcodeToHls: transcodeToHls.value
|
||||
})
|
||||
}
|
||||
|
||||
watch([compressEnabled, autoCopyMarkdown, copyFormat, clientWebpQuality], () => {
|
||||
function resetToDefaults() {
|
||||
compressEnabled.value = DEFAULTS.compressEnabled
|
||||
autoCopyMarkdown.value = DEFAULTS.autoCopyMarkdown
|
||||
copyFormat.value = DEFAULTS.copyFormat
|
||||
clientWebpQuality.value = DEFAULTS.clientWebpQuality
|
||||
uploadTagNames.value = [...DEFAULTS.uploadTagNames]
|
||||
transcodeToHls.value = DEFAULTS.transcodeToHls
|
||||
savePreferences()
|
||||
}
|
||||
|
||||
watch(
|
||||
[compressEnabled, autoCopyMarkdown, copyFormat, clientWebpQuality, transcodeToHls],
|
||||
() => {
|
||||
if (loaded.value) {
|
||||
savePreferences()
|
||||
}
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
kind,
|
||||
compressEnabled,
|
||||
autoCopyMarkdown,
|
||||
copyFormat,
|
||||
clientWebpQuality,
|
||||
uploadTagNames,
|
||||
transcodeToHls,
|
||||
loaded,
|
||||
loadPreferences,
|
||||
savePreferences
|
||||
savePreferences,
|
||||
resetToDefaults
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<script setup lang="ts">
|
||||
const { isChecking, isAuthenticated, user, checkSession, fetchStatus, handleAuthError } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
const username = ref('')
|
||||
const saving = ref(false)
|
||||
|
||||
watch(user, (value) => {
|
||||
if (value) username.value = value.username
|
||||
}, { immediate: true })
|
||||
|
||||
async function save() {
|
||||
if (saving.value) return
|
||||
saving.value = true
|
||||
try {
|
||||
const data = await $fetch<{ user: { username: string } }>('/api/user/profile', {
|
||||
method: 'PATCH',
|
||||
credentials: 'include',
|
||||
body: { username: username.value.trim() }
|
||||
})
|
||||
await checkSession()
|
||||
toast.add({ title: t('profile.saved'), color: 'success' })
|
||||
username.value = data.user.username
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
const message = (error as { data?: { message?: string } })?.data?.message
|
||||
toast.add({ title: message ?? t('profile.saveFailed'), color: 'error' })
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const status = await fetchStatus()
|
||||
if (!status.initialized && !status.legacyMode) {
|
||||
await navigateTo('/setup')
|
||||
return
|
||||
}
|
||||
await checkSession()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen">
|
||||
<div
|
||||
v-if="isChecking"
|
||||
class="flex min-h-screen items-center justify-center"
|
||||
>
|
||||
<UIcon
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-8 animate-spin text-muted"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<AdminLoginGate v-else-if="!isAuthenticated" />
|
||||
|
||||
<AppShell v-else>
|
||||
<div class="mx-auto max-w-md space-y-4">
|
||||
<div>
|
||||
<h1 class="text-2xl font-semibold tracking-tight">
|
||||
{{ t('profile.title') }}
|
||||
</h1>
|
||||
<p class="text-sm text-muted">
|
||||
{{ t('profile.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<form
|
||||
class="space-y-3 rounded-xl border border-default bg-elevated p-5"
|
||||
@submit.prevent="save"
|
||||
>
|
||||
<label class="block text-sm font-medium">
|
||||
{{ t('profile.username') }}
|
||||
</label>
|
||||
<UInput
|
||||
v-model="username"
|
||||
class="w-full"
|
||||
:placeholder="t('profile.username')"
|
||||
/>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('profile.usernameHint') }}
|
||||
</p>
|
||||
<UButton
|
||||
type="submit"
|
||||
:loading="saving"
|
||||
:label="t('common.save')"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</AppShell>
|
||||
</div>
|
||||
</template>
|
||||
+17
-29
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
interface SettingsResponse {
|
||||
interface UserTokenResponse {
|
||||
apiUploadToken: string
|
||||
tokenSource: 'env' | 'db' | 'none'
|
||||
envTokenOverride: boolean
|
||||
@@ -8,6 +8,8 @@ interface SettingsResponse {
|
||||
refererConfigured: boolean
|
||||
siteBaseUrl: string
|
||||
imageBaseUrl: string
|
||||
videoBaseUrl: string
|
||||
fileBaseUrl: string
|
||||
appVersion: string
|
||||
}
|
||||
}
|
||||
@@ -16,7 +18,7 @@ const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus,
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
const settings = ref<SettingsResponse | null>(null)
|
||||
const tokenSettings = ref<UserTokenResponse | null>(null)
|
||||
const loading = ref(false)
|
||||
const regenerating = ref(false)
|
||||
const confirmRegenerateOpen = ref(false)
|
||||
@@ -25,17 +27,17 @@ const newToken = ref('')
|
||||
const activeEndpointId = ref('upload')
|
||||
|
||||
const baseUrl = computed(() => {
|
||||
const configured = settings.value?.env.siteBaseUrl
|
||||
const configured = tokenSettings.value?.env.siteBaseUrl
|
||||
if (configured) return configured
|
||||
if (import.meta.client) {
|
||||
return window.location.origin
|
||||
}
|
||||
return settings.value?.env.imageBaseUrl ?? ''
|
||||
return tokenSettings.value?.env.imageBaseUrl ?? ''
|
||||
})
|
||||
|
||||
const tokenDisplay = computed(() => settings.value?.apiUploadToken ?? '')
|
||||
const tokenDisplay = computed(() => tokenSettings.value?.apiUploadToken ?? '')
|
||||
const hasToken = computed(() => tokenDisplay.value.length > 0)
|
||||
const canRegenerate = computed(() => !settings.value?.envTokenOverride && !loading.value)
|
||||
const canRegenerate = computed(() => !loading.value)
|
||||
|
||||
const authHeader = computed(() =>
|
||||
hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN'
|
||||
@@ -52,11 +54,10 @@ const activeEndpoint = computed(() =>
|
||||
apiDocs.value.find(endpoint => endpoint.id === activeEndpointId.value) ?? apiDocs.value[0]
|
||||
)
|
||||
|
||||
async function loadSettings() {
|
||||
async function loadTokenSettings() {
|
||||
loading.value = true
|
||||
try {
|
||||
const endpoint = isAdmin.value ? '/api/settings' : '/api/user/api-token'
|
||||
settings.value = await $fetch<SettingsResponse>(endpoint, {
|
||||
tokenSettings.value = await $fetch<UserTokenResponse>('/api/user/api-token', {
|
||||
credentials: 'include'
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
@@ -64,6 +65,7 @@ async function loadSettings() {
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('api.loadFailed'), color: 'error' })
|
||||
}
|
||||
tokenSettings.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -78,31 +80,18 @@ async function confirmRegenerate() {
|
||||
confirmRegenerateOpen.value = false
|
||||
regenerating.value = true
|
||||
try {
|
||||
const endpoint = isAdmin.value
|
||||
? '/api/settings/api-token/regenerate'
|
||||
: '/api/user/api-token/regenerate'
|
||||
const response = await $fetch<{ apiUploadToken: string }>(
|
||||
endpoint,
|
||||
'/api/user/api-token/regenerate',
|
||||
{ method: 'POST', credentials: 'include' }
|
||||
)
|
||||
newToken.value = response.apiUploadToken
|
||||
regenerateResultOpen.value = true
|
||||
await loadSettings()
|
||||
await loadTokenSettings()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
const status = typeof error === 'object' && error !== null && 'statusCode' in error
|
||||
? (error as { statusCode: number }).statusCode
|
||||
: 0
|
||||
if (status === 409) {
|
||||
toast.add({
|
||||
title: t('api.regenerateEnvBlocked'),
|
||||
color: 'warning'
|
||||
})
|
||||
} else {
|
||||
toast.add({ title: t('api.regenerateFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
regenerating.value = false
|
||||
}
|
||||
@@ -124,16 +113,16 @@ onMounted(async () => {
|
||||
}
|
||||
await checkSession()
|
||||
if (isAuthenticated.value) {
|
||||
await loadSettings()
|
||||
await loadTokenSettings()
|
||||
}
|
||||
})
|
||||
|
||||
watch(isAuthenticated, async (authed, prev) => {
|
||||
if (authed && prev === false) {
|
||||
await nextTick()
|
||||
await loadSettings()
|
||||
await loadTokenSettings()
|
||||
} else {
|
||||
settings.value = null
|
||||
tokenSettings.value = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -172,8 +161,7 @@ watch(isAuthenticated, async (authed, prev) => {
|
||||
:loading="loading"
|
||||
:regenerating="regenerating"
|
||||
:can-regenerate="canRegenerate"
|
||||
:token-source="settings?.tokenSource"
|
||||
:env-token-override="settings?.envTokenOverride"
|
||||
token-source="db"
|
||||
:is-admin="isAdmin"
|
||||
@regenerate="requestRegenerate"
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
<script setup lang="ts">
|
||||
import FileLibraryPanel from '~/components/FileLibraryPanel.vue'
|
||||
|
||||
const { isChecking, isAuthenticated, checkSession, fetchStatus } = useAuth()
|
||||
const { t } = useI18n()
|
||||
|
||||
const panelRef = ref<{ refresh: () => Promise<void> } | null>(null)
|
||||
|
||||
async function loadPanel() {
|
||||
if (isAuthenticated.value) {
|
||||
await panelRef.value?.refresh()
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const status = await fetchStatus()
|
||||
if (!status.initialized && !status.legacyMode) {
|
||||
await navigateTo('/setup')
|
||||
return
|
||||
}
|
||||
await checkSession()
|
||||
await loadPanel()
|
||||
})
|
||||
|
||||
watch(isAuthenticated, async (authed, prev) => {
|
||||
if (authed && prev === false) {
|
||||
await nextTick()
|
||||
await loadPanel()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen">
|
||||
<div
|
||||
v-if="isChecking"
|
||||
class="flex min-h-screen items-center justify-center"
|
||||
>
|
||||
<div class="flex flex-col items-center gap-3 text-muted">
|
||||
<UIcon
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-8 animate-spin"
|
||||
/>
|
||||
<p class="text-sm">
|
||||
{{ t('common.loadingSession') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AdminLoginGate v-else-if="!isAuthenticated" />
|
||||
|
||||
<AppShell v-else>
|
||||
<FileLibraryPanel
|
||||
ref="panelRef"
|
||||
kind="file"
|
||||
/>
|
||||
</AppShell>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,38 @@
|
||||
<script setup lang="ts">
|
||||
const { isChecking, isAuthenticated, checkSession, fetchStatus } = useAuth()
|
||||
const { t } = useI18n()
|
||||
|
||||
onMounted(async () => {
|
||||
const status = await fetchStatus()
|
||||
if (!status.initialized && !status.legacyMode) {
|
||||
await navigateTo('/setup')
|
||||
return
|
||||
}
|
||||
await checkSession()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="min-h-screen">
|
||||
<div
|
||||
v-if="isChecking"
|
||||
class="flex min-h-screen items-center justify-center"
|
||||
>
|
||||
<div class="flex flex-col items-center gap-3 text-muted">
|
||||
<UIcon
|
||||
name="i-lucide-loader-circle"
|
||||
class="size-8 animate-spin"
|
||||
/>
|
||||
<p class="text-sm">
|
||||
{{ t('common.loadingSession') }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<AdminLoginGate v-else-if="!isAuthenticated" />
|
||||
|
||||
<AppShell v-else>
|
||||
<MediaUploadPanel kind="file" />
|
||||
</AppShell>
|
||||
</div>
|
||||
</template>
|
||||
+139
-8
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageItem } from '~/types/image'
|
||||
import SiteSyncSelectedDialog from '~/components/storage/SiteSyncSelectedDialog.vue'
|
||||
|
||||
interface StatsResponse {
|
||||
uploadToday: number
|
||||
@@ -46,10 +47,17 @@ const {
|
||||
activeUploadSource,
|
||||
setActiveUploadSource,
|
||||
resetFilters,
|
||||
loadStorageBackendOptions
|
||||
loadStorageBackendOptions,
|
||||
activeTagIds,
|
||||
activeTagMode,
|
||||
activeUntaggedOnly,
|
||||
setActiveTagFilter,
|
||||
toggleTagFilter
|
||||
} = useImageList()
|
||||
|
||||
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth()
|
||||
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
|
||||
|
||||
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, getFetchErrorMessage } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -65,7 +73,9 @@ const batchDeleting = ref(false)
|
||||
const showScrollTop = ref(false)
|
||||
const previewOpen = ref(false)
|
||||
const previewImage = ref<ImageItem | null>(null)
|
||||
const viewMode = ref<'grid' | 'list'>('grid')
|
||||
const { viewMode } = useLibraryView('image')
|
||||
const batchTagOpen = ref(false)
|
||||
const syncOpen = ref(false)
|
||||
|
||||
const currentUploadSource = ref('all')
|
||||
const currentStorageBackend = ref('all')
|
||||
@@ -85,6 +95,7 @@ const storageBackendItems = computed(() => [
|
||||
])
|
||||
|
||||
const selectedCount = computed(() => selectedKeys.value.size)
|
||||
const syncKeys = computed(() => [...selectedKeys.value])
|
||||
|
||||
function onWindowScroll() {
|
||||
showScrollTop.value = window.scrollY > 400
|
||||
@@ -95,8 +106,9 @@ function scrollToTop() {
|
||||
}
|
||||
|
||||
async function fetchStats() {
|
||||
stats.value = await $fetch<StatsResponse>('/api/stats', {
|
||||
credentials: 'include'
|
||||
stats.value = await $fetch<StatsResponse>('/api/library/stats', {
|
||||
credentials: 'include',
|
||||
query: { kind: 'image' }
|
||||
})
|
||||
}
|
||||
|
||||
@@ -131,7 +143,8 @@ async function refreshAll() {
|
||||
await Promise.all([
|
||||
fetchStats(),
|
||||
reloadGallery(),
|
||||
loadStorageBackendOptions()
|
||||
loadStorageBackendOptions(),
|
||||
fetchTags()
|
||||
])
|
||||
currentUploadSource.value = activeUploadSource.value
|
||||
currentStorageBackend.value = activeStorageBackend.value
|
||||
@@ -174,11 +187,92 @@ async function handleResetFilters() {
|
||||
currentStorageBackend.value = 'all'
|
||||
try {
|
||||
await resetFilters()
|
||||
await fetchStats()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTagIdsChange(tagIds: number[]) {
|
||||
if (!isAuthenticated.value) return
|
||||
selectedKeys.value = new Set()
|
||||
try {
|
||||
await setActiveTagFilter({ tagIds, untaggedOnly: false })
|
||||
await fetchStats()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTagModeChange(tagMode: 'or' | 'and') {
|
||||
if (!isAuthenticated.value) return
|
||||
try {
|
||||
await setActiveTagFilter({ tagMode })
|
||||
await fetchStats()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUntaggedOnlyChange(untaggedOnly: boolean) {
|
||||
if (!isAuthenticated.value) return
|
||||
selectedKeys.value = new Set()
|
||||
try {
|
||||
await setActiveTagFilter({ untaggedOnly, tagIds: [] })
|
||||
await fetchStats()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTagFilterClick(tagId: number) {
|
||||
if (!isAuthenticated.value) return
|
||||
selectedKeys.value = new Set()
|
||||
try {
|
||||
await toggleTagFilter(tagId)
|
||||
await fetchStats()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function handleUntaggedFilterClick() {
|
||||
if (!isAuthenticated.value) return
|
||||
selectedKeys.value = new Set()
|
||||
try {
|
||||
await setActiveTagFilter({ untaggedOnly: true, tagIds: [] })
|
||||
await fetchStats()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
}
|
||||
|
||||
async function confirmBatchTags(tagIds: number[], action: 'add' | 'remove') {
|
||||
const keys = Array.from(selectedKeys.value)
|
||||
if (!keys.length || !tagIds.length) return
|
||||
try {
|
||||
await batchUpdateTags(keys, tagIds, action)
|
||||
batchTagOpen.value = false
|
||||
selectedKeys.value = new Set()
|
||||
toast.add({ title: t('tags.batchSuccess'), color: 'success' })
|
||||
await Promise.all([reloadGallery(), fetchStats(), fetchTags(true)])
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
toast.add({
|
||||
title: getFetchErrorMessage(error, t('tags.batchFailed')),
|
||||
color: 'error'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function goToTagSettings() {
|
||||
void navigateTo({ path: '/settings', query: { tab: 'tags' } })
|
||||
}
|
||||
|
||||
function openSync() {
|
||||
syncOpen.value = true
|
||||
}
|
||||
|
||||
function updateSelectedKeys(keys: Set<string>) {
|
||||
selectedKeys.value = keys
|
||||
}
|
||||
@@ -378,7 +472,8 @@ watch(isAuthenticated, async (authed, prev) => {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<GalleryStatsOverview
|
||||
<LibraryStatsPanel
|
||||
kind="image"
|
||||
:stats="stats"
|
||||
:loading="statsLoading"
|
||||
/>
|
||||
@@ -398,15 +493,28 @@ watch(isAuthenticated, async (authed, prev) => {
|
||||
:storage-backend-items="storageBackendItems"
|
||||
:upload-source="currentUploadSource"
|
||||
:upload-source-items="uploadSourceItems"
|
||||
:tag-ids="activeTagIds"
|
||||
:tag-mode="activeTagMode"
|
||||
:untagged-only="activeUntaggedOnly"
|
||||
:tags="tagItems"
|
||||
:view-mode="viewMode"
|
||||
:selected-count="selectedCount"
|
||||
:loading="galleryLoading"
|
||||
:show-batch-delete="true"
|
||||
:show-batch-tags="selectedCount > 0"
|
||||
:show-batch-sync="selectedCount > 0"
|
||||
@update:storage-backend="handleStorageBackendChange"
|
||||
@update:upload-source="handleUploadSourceChange"
|
||||
@update:tag-ids="handleTagIdsChange"
|
||||
@update:tag-mode="handleTagModeChange"
|
||||
@update:untagged-only="handleUntaggedOnlyChange"
|
||||
@update:view-mode="viewMode = $event"
|
||||
@search="handleSearch"
|
||||
@reset="handleResetFilters"
|
||||
@batch-delete="requestBatchDelete"
|
||||
@batch-tags="batchTagOpen = true"
|
||||
@batch-sync="openSync"
|
||||
@manage-tags="goToTagSettings"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -428,30 +536,40 @@ watch(isAuthenticated, async (authed, prev) => {
|
||||
gallery
|
||||
:show-key="false"
|
||||
show-storage
|
||||
show-tags
|
||||
:items="items"
|
||||
:selected-keys="selectedKeys"
|
||||
selectable
|
||||
:selectable="true"
|
||||
:allow-delete="true"
|
||||
@update:selected-keys="updateSelectedKeys"
|
||||
@preview="openPreview"
|
||||
@delete="(image) => requestDelete(image.key)"
|
||||
@tag-click="handleTagFilterClick"
|
||||
@untagged-click="handleUntaggedFilterClick"
|
||||
/>
|
||||
|
||||
<GalleryImageList
|
||||
v-else
|
||||
show-storage
|
||||
show-tags
|
||||
:items="items"
|
||||
:selected-keys="selectedKeys"
|
||||
:selectable="true"
|
||||
:show-delete="true"
|
||||
@update:selected-keys="updateSelectedKeys"
|
||||
@preview="openPreview"
|
||||
@delete="(image) => requestDelete(image.key)"
|
||||
@tag-click="handleTagFilterClick"
|
||||
@untagged-click="handleUntaggedFilterClick"
|
||||
/>
|
||||
|
||||
<ImagePreviewModal
|
||||
v-model:open="previewOpen"
|
||||
:image="previewImage"
|
||||
show-storage
|
||||
show-tags
|
||||
:deleting="previewImage ? deletingKeys.has(previewImage.key) : false"
|
||||
:allow-delete="true"
|
||||
@delete="requestPreviewDelete"
|
||||
/>
|
||||
|
||||
@@ -475,6 +593,19 @@ watch(isAuthenticated, async (authed, prev) => {
|
||||
@confirm="confirmDelete"
|
||||
/>
|
||||
|
||||
<BatchTagModal
|
||||
v-model:open="batchTagOpen"
|
||||
:tags="tagItems"
|
||||
:selected-count="selectedCount"
|
||||
@confirm="confirmBatchTags"
|
||||
/>
|
||||
|
||||
<SiteSyncSelectedDialog
|
||||
v-model:open="syncOpen"
|
||||
:keys="syncKeys"
|
||||
scope="image"
|
||||
/>
|
||||
|
||||
<UButton
|
||||
v-show="showScrollTop"
|
||||
icon="i-lucide-arrow-up"
|
||||
|
||||
+91
-2
@@ -1,7 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import type { ImageItem } from '~/types/image'
|
||||
import type { ImageItem, ImageTag } from '~/types/image'
|
||||
import { buildImageBbcode } from '~/utils/image-display'
|
||||
|
||||
const { uploading, progressItems, uploadFiles } = useImageUpload()
|
||||
const { policy: uploadPolicy, load: loadUploadPolicy } = useUploadPolicy()
|
||||
|
||||
const {
|
||||
autoCopyMarkdown,
|
||||
@@ -9,14 +11,23 @@ const {
|
||||
loadPreferences
|
||||
} = useUploadPreferences()
|
||||
|
||||
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
|
||||
const { recordRecent } = useRecentTags()
|
||||
|
||||
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
const imageFormats = computed(() =>
|
||||
t('upload.formats', { size: uploadPolicy.value?.imageMaxFileSizeMb ?? 10 })
|
||||
)
|
||||
const sessionItems = ref<ImageItem[]>([])
|
||||
const deletingKeys = ref<Set<string>>(new Set())
|
||||
const emptySelection = ref(new Set<string>())
|
||||
const previewOpen = ref(false)
|
||||
const previewImage = ref<ImageItem | null>(null)
|
||||
const tagModalOpen = ref(false)
|
||||
const tagModalImage = ref<ImageItem | null>(null)
|
||||
const batchTagOpen = ref(false)
|
||||
|
||||
const showProgress = computed(
|
||||
() =>
|
||||
@@ -32,6 +43,7 @@ const showProgress = computed(
|
||||
async function loadPage() {
|
||||
try {
|
||||
loadPreferences()
|
||||
await loadUploadPolicy().catch(() => {})
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
}
|
||||
@@ -47,7 +59,7 @@ onMounted(async () => {
|
||||
await checkSession()
|
||||
}
|
||||
if (isAuthenticated.value) {
|
||||
await loadPage()
|
||||
await Promise.all([loadPage(), fetchTags()])
|
||||
}
|
||||
})
|
||||
|
||||
@@ -66,6 +78,8 @@ function copyFormatLabel() {
|
||||
return t('copy.url')
|
||||
case 'html':
|
||||
return t('copy.html')
|
||||
case 'bbcode':
|
||||
return t('copy.bbcode')
|
||||
default:
|
||||
return t('copy.markdown')
|
||||
}
|
||||
@@ -108,6 +122,8 @@ async function handleUpload(files: File[]) {
|
||||
? first.url
|
||||
: copyFormat.value === 'html'
|
||||
? first.html
|
||||
: copyFormat.value === 'bbcode'
|
||||
? buildImageBbcode(first.url)
|
||||
: first.markdown
|
||||
if (text) await copyUploadLink(text)
|
||||
}
|
||||
@@ -148,6 +164,50 @@ function requestPreviewDelete() {
|
||||
if (!previewImage.value) return
|
||||
void handleDelete(previewImage.value.key)
|
||||
}
|
||||
|
||||
function openTagModal(image: ImageItem) {
|
||||
tagModalImage.value = image
|
||||
tagModalOpen.value = true
|
||||
}
|
||||
|
||||
function updateSessionItemTags(key: string, tags: ImageItem['tags']) {
|
||||
sessionItems.value = sessionItems.value.map(item =>
|
||||
item.key === key ? { ...item, tags } : item
|
||||
)
|
||||
if (previewImage.value?.key === key) {
|
||||
previewImage.value = { ...previewImage.value, tags }
|
||||
}
|
||||
if (tagModalImage.value?.key === key) {
|
||||
tagModalImage.value = { ...tagModalImage.value, tags }
|
||||
}
|
||||
}
|
||||
|
||||
function handleTagSaved(tags: ImageTag[]) {
|
||||
if (!tagModalImage.value) return
|
||||
updateSessionItemTags(tagModalImage.value.key, tags)
|
||||
}
|
||||
|
||||
async function confirmBatchTags(tagIds: number[]) {
|
||||
const keys = sessionItems.value.map(item => item.key)
|
||||
if (!keys.length || !tagIds.length) return
|
||||
|
||||
try {
|
||||
await batchUpdateTags(keys, tagIds, 'add')
|
||||
batchTagOpen.value = false
|
||||
recordRecent(tagIds)
|
||||
toast.add({ title: t('tags.batchSuccess'), color: 'success' })
|
||||
await fetchTags(true)
|
||||
const addedTags = tagItems.value.filter(tag => tagIds.includes(tag.id))
|
||||
sessionItems.value = sessionItems.value.map((item) => {
|
||||
const merged = new Map((item.tags ?? []).map(tag => [tag.id, tag]))
|
||||
for (const tag of addedTags) merged.set(tag.id, tag)
|
||||
return { ...item, tags: [...merged.values()] }
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
toast.add({ title: t('tags.batchFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -172,6 +232,7 @@ function requestPreviewDelete() {
|
||||
<AppShell v-else>
|
||||
<UploadFlipCard
|
||||
:disabled="uploading"
|
||||
:formats="imageFormats"
|
||||
@upload="handleUpload"
|
||||
/>
|
||||
|
||||
@@ -189,6 +250,14 @@ function requestPreviewDelete() {
|
||||
{{ t('upload.sessionTitle') }}
|
||||
<span class="ml-1 text-sm font-normal text-muted">({{ sessionItems.length }})</span>
|
||||
</h2>
|
||||
<UButton
|
||||
icon="i-lucide-tags"
|
||||
variant="outline"
|
||||
color="primary"
|
||||
size="sm"
|
||||
:label="t('tags.batchTagAll')"
|
||||
@click="() => { batchTagOpen = true }"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<ImageGrid
|
||||
@@ -196,9 +265,13 @@ function requestPreviewDelete() {
|
||||
:selected-keys="emptySelection"
|
||||
:selectable="false"
|
||||
:show-key="false"
|
||||
:allow-delete="true"
|
||||
show-tag-action
|
||||
:empty-text="t('upload.sessionEmpty')"
|
||||
@update:selected-keys="() => {}"
|
||||
@preview="openPreview"
|
||||
@delete="(image) => handleDelete(image.key)"
|
||||
@edit-tags="openTagModal"
|
||||
/>
|
||||
</section>
|
||||
|
||||
@@ -206,8 +279,24 @@ function requestPreviewDelete() {
|
||||
v-model:open="previewOpen"
|
||||
:image="previewImage"
|
||||
:deleting="previewImage ? deletingKeys.has(previewImage.key) : false"
|
||||
:allow-delete="true"
|
||||
@delete="requestPreviewDelete"
|
||||
/>
|
||||
|
||||
<ImageTagModal
|
||||
v-model:open="tagModalOpen"
|
||||
:image="tagModalImage"
|
||||
:tags="tagItems"
|
||||
@saved="handleTagSaved"
|
||||
/>
|
||||
|
||||
<BatchTagModal
|
||||
v-model:open="batchTagOpen"
|
||||
:tags="tagItems"
|
||||
:selected-count="sessionItems.length"
|
||||
add-only
|
||||
@confirm="(tagIds) => confirmBatchTags(tagIds)"
|
||||
/>
|
||||
</AppShell>
|
||||
</div>
|
||||
</template>
|
||||
+39
-4
@@ -2,9 +2,10 @@
|
||||
import logoLight from '~/assets/image/logo-light.png'
|
||||
import logoDark from '~/assets/image/logo-dark.png'
|
||||
import { isPasswordValid } from '~/utils/password-strength'
|
||||
import type { LoginVerificationPayload } from '~/types/auth'
|
||||
|
||||
const router = useRouter()
|
||||
const { register, fetchStatus } = useAuth()
|
||||
const { register, fetchStatus, authStatus } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -12,14 +13,34 @@ const username = ref('')
|
||||
const password = ref('')
|
||||
const confirmPassword = ref('')
|
||||
const loading = ref(false)
|
||||
const verificationRef = ref<{ reset: () => Promise<void> } | null>(null)
|
||||
const verificationPayload = ref<LoginVerificationPayload | null>(null)
|
||||
|
||||
const loginVerification = computed(() =>
|
||||
authStatus.value?.loginVerification ?? { method: 'slider' as const }
|
||||
)
|
||||
|
||||
const canSubmit = computed(() =>
|
||||
Boolean(username.value && password.value && confirmPassword.value)
|
||||
Boolean(verificationPayload.value)
|
||||
&& Boolean(username.value && password.value && confirmPassword.value)
|
||||
&& password.value === confirmPassword.value
|
||||
&& isPasswordValid(password.value)
|
||||
&& AUTH_USERNAME_PATTERN.test(username.value.trim())
|
||||
)
|
||||
|
||||
function onVerificationVerified(payload: LoginVerificationPayload) {
|
||||
verificationPayload.value = payload
|
||||
}
|
||||
|
||||
function onVerificationCleared() {
|
||||
verificationPayload.value = null
|
||||
}
|
||||
|
||||
async function resetVerification() {
|
||||
verificationPayload.value = null
|
||||
await verificationRef.value?.reset()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const status = await fetchStatus()
|
||||
if (!status.initialized && !status.legacyMode) {
|
||||
@@ -32,7 +53,7 @@ onMounted(async () => {
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
if (!canSubmit.value || loading.value) return
|
||||
if (!canSubmit.value || loading.value || !verificationPayload.value) return
|
||||
|
||||
if (password.value !== confirmPassword.value) {
|
||||
toast.add({ title: t('auth.passwordMismatch'), color: 'error' })
|
||||
@@ -41,11 +62,16 @@ async function submit() {
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const result = await register(username.value.trim(), password.value)
|
||||
const result = await register(
|
||||
username.value.trim(),
|
||||
password.value,
|
||||
verificationPayload.value
|
||||
)
|
||||
if (result.ok) {
|
||||
toast.add({ title: t('auth.registerSuccess'), color: 'success' })
|
||||
await router.replace('/')
|
||||
} else {
|
||||
await resetVerification()
|
||||
toast.add({ title: result.error, color: 'error' })
|
||||
}
|
||||
} finally {
|
||||
@@ -142,6 +168,15 @@ async function submit() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
<LoginVerification
|
||||
ref="verificationRef"
|
||||
:method="loginVerification.method"
|
||||
:turnstile-site-key="loginVerification.turnstileSiteKey"
|
||||
:cap-api-endpoint="loginVerification.capApiEndpoint"
|
||||
@verified="onVerificationVerified"
|
||||
@cleared="onVerificationCleared"
|
||||
/>
|
||||
|
||||
<UButton
|
||||
type="submit"
|
||||
:label="t('auth.register')"
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
<script setup lang="ts">
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
const { checkSession } = useAuth()
|
||||
|
||||
const username = ref(String(route.query.username ?? ''))
|
||||
const password = ref('')
|
||||
const confirm = ref('')
|
||||
const loading = ref(false)
|
||||
|
||||
async function submit() {
|
||||
if (loading.value) return
|
||||
if (password.value.length < 6) {
|
||||
toast.add({ title: t('reset.tooShort'), color: 'warning' })
|
||||
return
|
||||
}
|
||||
if (password.value !== confirm.value) {
|
||||
toast.add({ title: t('reset.mismatch'), color: 'warning' })
|
||||
return
|
||||
}
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
await $fetch('/api/auth/reset-password', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
body: { username: username.value.trim(), password: password.value }
|
||||
})
|
||||
await checkSession()
|
||||
toast.add({ title: t('reset.success'), color: 'success' })
|
||||
await router.replace('/')
|
||||
} catch (error: unknown) {
|
||||
toast.add({
|
||||
title: error instanceof Error ? error.message : t('reset.failed'),
|
||||
color: 'error'
|
||||
})
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex min-h-screen items-center justify-center p-4">
|
||||
<form
|
||||
class="w-full max-w-sm space-y-4 rounded-xl border border-default bg-elevated p-6"
|
||||
@submit.prevent="submit"
|
||||
>
|
||||
<div>
|
||||
<h1 class="text-xl font-semibold tracking-tight">
|
||||
{{ t('reset.title') }}
|
||||
</h1>
|
||||
<p class="mt-1 text-sm text-muted">
|
||||
{{ t('reset.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<UInput
|
||||
v-model="username"
|
||||
:placeholder="t('auth.username')"
|
||||
class="w-full"
|
||||
/>
|
||||
<UInput
|
||||
v-model="password"
|
||||
type="password"
|
||||
:placeholder="t('reset.newPassword')"
|
||||
class="w-full"
|
||||
/>
|
||||
<UInput
|
||||
v-model="confirm"
|
||||
type="password"
|
||||
:placeholder="t('reset.confirmPassword')"
|
||||
class="w-full"
|
||||
/>
|
||||
|
||||
<UButton
|
||||
type="submit"
|
||||
block
|
||||
:loading="loading"
|
||||
:label="t('reset.submit')"
|
||||
/>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
+660
-197
File diff suppressed because it is too large.
Load diff
+248
-2
@@ -2,6 +2,7 @@
|
||||
import logoLight from '~/assets/image/logo-light.png'
|
||||
import logoDark from '~/assets/image/logo-dark.png'
|
||||
import { isPasswordValid } from '~/utils/password-strength'
|
||||
import { willActivateDomainSeparation } from '~/utils/domain-separation'
|
||||
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
@@ -25,7 +26,104 @@ const allowRegistration = ref(false)
|
||||
const domainSeparation = ref(false)
|
||||
const siteBaseUrl = ref('')
|
||||
const imageBaseUrl = ref('')
|
||||
const videoBaseUrl = ref('')
|
||||
const fileBaseUrl = ref('')
|
||||
const loading = ref(false)
|
||||
const domainSeparationConfirmOpen = ref(false)
|
||||
|
||||
const setupMode = ref<'init' | 'restore'>('init')
|
||||
const restoreFile = ref<File | null>(null)
|
||||
const restoreFileInput = ref<HTMLInputElement | null>(null)
|
||||
const restoreLoading = ref(false)
|
||||
const restoreJobId = ref<string | null>(null)
|
||||
const restoreProgress = ref({ progress: 0, total: 0, message: '' })
|
||||
let restorePollTimer: ReturnType<typeof setInterval> | null = null
|
||||
|
||||
function stopRestorePolling() {
|
||||
if (restorePollTimer) {
|
||||
clearInterval(restorePollTimer)
|
||||
restorePollTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
function pickRestoreFile() {
|
||||
restoreFileInput.value?.click()
|
||||
}
|
||||
|
||||
function onRestoreFileChange(event: Event) {
|
||||
const input = event.target as HTMLInputElement
|
||||
restoreFile.value = input.files?.[0] ?? null
|
||||
if (input) input.value = ''
|
||||
}
|
||||
|
||||
async function pollRestoreJob(jobId: string) {
|
||||
try {
|
||||
const data = await $fetch<{ job: { status: string, progress: number, total: number, message: string, error: string | null } }>(
|
||||
`/api/setup/restore/${jobId}`
|
||||
)
|
||||
restoreProgress.value = {
|
||||
progress: data.job.progress,
|
||||
total: data.job.total,
|
||||
message: data.job.message
|
||||
}
|
||||
if (data.job.status === 'done') {
|
||||
stopRestorePolling()
|
||||
restoreLoading.value = false
|
||||
toast.add({
|
||||
title: t('setup.restoreSuccess'),
|
||||
description: t('setup.restoreSecretsHint'),
|
||||
color: 'success'
|
||||
})
|
||||
await router.replace('/')
|
||||
return
|
||||
}
|
||||
if (data.job.status === 'failed') {
|
||||
stopRestorePolling()
|
||||
restoreLoading.value = false
|
||||
toast.add({
|
||||
title: t('setup.restoreFailed'),
|
||||
description: data.job.error ?? data.job.message,
|
||||
color: 'error'
|
||||
})
|
||||
}
|
||||
} catch {
|
||||
stopRestorePolling()
|
||||
restoreLoading.value = false
|
||||
toast.add({ title: t('setup.restoreFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
async function submitRestore() {
|
||||
if (!restoreFile.value || restoreLoading.value) return
|
||||
restoreLoading.value = true
|
||||
try {
|
||||
const data = await $fetch<{ job: { id: string } }>('/api/setup/restore', {
|
||||
method: 'POST',
|
||||
body: restoreFile.value,
|
||||
headers: { 'content-type': 'application/octet-stream' }
|
||||
})
|
||||
restoreJobId.value = data.job.id
|
||||
restorePollTimer = setInterval(() => {
|
||||
void pollRestoreJob(data.job.id)
|
||||
}, 1500)
|
||||
await pollRestoreJob(data.job.id)
|
||||
} catch {
|
||||
restoreLoading.value = false
|
||||
toast.add({ title: t('setup.restoreFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
|
||||
onUnmounted(() => {
|
||||
stopRestorePolling()
|
||||
})
|
||||
|
||||
const domainSeparationWouldActivate = computed(() =>
|
||||
willActivateDomainSeparation(
|
||||
domainSeparation.value,
|
||||
siteBaseUrl.value,
|
||||
imageBaseUrl.value
|
||||
)
|
||||
)
|
||||
|
||||
const canSubmit = computed(() => {
|
||||
if (!username.value || !password.value || !confirmPassword.value) return false
|
||||
@@ -33,7 +131,7 @@ const canSubmit = computed(() => {
|
||||
if (!isPasswordValid(password.value)) return false
|
||||
if (!AUTH_USERNAME_PATTERN.test(username.value.trim())) return false
|
||||
if (domainSeparation.value) {
|
||||
return Boolean(siteBaseUrl.value.trim() && imageBaseUrl.value.trim())
|
||||
if (!siteBaseUrl.value.trim() || !imageBaseUrl.value.trim()) return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
@@ -63,6 +161,18 @@ async function submit() {
|
||||
return
|
||||
}
|
||||
|
||||
if (domainSeparationWouldActivate.value) {
|
||||
domainSeparationConfirmOpen.value = true
|
||||
return
|
||||
}
|
||||
|
||||
await performSubmit()
|
||||
}
|
||||
|
||||
async function performSubmit() {
|
||||
domainSeparationConfirmOpen.value = false
|
||||
if (!canSubmit.value || loading.value) return
|
||||
|
||||
loading.value = true
|
||||
try {
|
||||
const payload = {
|
||||
@@ -71,7 +181,9 @@ async function submit() {
|
||||
allowRegistration: allowRegistration.value,
|
||||
domainSeparation: domainSeparation.value,
|
||||
siteBaseUrl: domainSeparation.value ? siteBaseUrl.value.trim() : undefined,
|
||||
imageBaseUrl: domainSeparation.value ? imageBaseUrl.value.trim() : undefined
|
||||
imageBaseUrl: domainSeparation.value ? imageBaseUrl.value.trim() : undefined,
|
||||
videoBaseUrl: domainSeparation.value ? videoBaseUrl.value.trim() : undefined,
|
||||
fileBaseUrl: domainSeparation.value ? fileBaseUrl.value.trim() : undefined
|
||||
}
|
||||
const result = isMigrate.value
|
||||
? await migrate(payload)
|
||||
@@ -127,7 +239,28 @@ async function submit() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-6 flex rounded-lg border border-default p-1">
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors"
|
||||
:class="setupMode === 'init' ? 'bg-primary text-inverted' : 'text-muted hover:text-default'"
|
||||
@click="setupMode = 'init'"
|
||||
>
|
||||
{{ t('setup.modeInit') }}
|
||||
</button>
|
||||
<button
|
||||
v-if="!isMigrate"
|
||||
type="button"
|
||||
class="flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors"
|
||||
:class="setupMode === 'restore' ? 'bg-primary text-inverted' : 'text-muted hover:text-default'"
|
||||
@click="setupMode = 'restore'"
|
||||
>
|
||||
{{ t('setup.modeRestore') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<form
|
||||
v-if="setupMode === 'init'"
|
||||
class="flex w-full flex-col gap-5"
|
||||
@submit.prevent="submit"
|
||||
>
|
||||
@@ -233,6 +366,28 @@ async function submit() {
|
||||
class="w-full font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm">{{ t('setup.videoBaseUrl') }}</label>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('setup.videoBaseUrlHint') }}
|
||||
</p>
|
||||
<UInput
|
||||
v-model="videoBaseUrl"
|
||||
:placeholder="t('setup.videoBaseUrlPlaceholder')"
|
||||
class="w-full font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-2">
|
||||
<label class="text-sm">{{ t('setup.fileBaseUrl') }}</label>
|
||||
<p class="text-xs text-muted">
|
||||
{{ t('setup.fileBaseUrlHint') }}
|
||||
</p>
|
||||
<UInput
|
||||
v-model="fileBaseUrl"
|
||||
:placeholder="t('setup.fileBaseUrlPlaceholder')"
|
||||
class="w-full font-mono text-sm"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
@@ -247,6 +402,97 @@ async function submit() {
|
||||
:disabled="!canSubmit"
|
||||
/>
|
||||
</form>
|
||||
|
||||
<div
|
||||
v-else
|
||||
class="flex w-full flex-col gap-5"
|
||||
>
|
||||
<div class="space-y-1.5">
|
||||
<label class="text-xs text-muted">{{ t('storage.backup.restoreUploadLabel') }}</label>
|
||||
<button
|
||||
type="button"
|
||||
class="flex w-full flex-col items-center gap-1.5 rounded-lg border-2 border-dashed px-3 py-4 text-center transition-colors disabled:cursor-not-allowed disabled:opacity-60"
|
||||
:class="restoreFile
|
||||
? 'border-primary/50 bg-primary/5'
|
||||
: 'border-warning/40 bg-warning/5 hover:border-warning/60 hover:bg-warning/10'"
|
||||
:disabled="restoreLoading"
|
||||
@click="pickRestoreFile"
|
||||
>
|
||||
<div
|
||||
class="flex size-8 items-center justify-center rounded-full"
|
||||
:class="restoreFile ? 'bg-primary/15 text-primary' : 'bg-warning/15 text-warning'"
|
||||
>
|
||||
<UIcon
|
||||
:name="restoreFile ? 'i-lucide-check' : 'i-lucide-upload'"
|
||||
class="size-4.5"
|
||||
/>
|
||||
</div>
|
||||
<span class="max-w-full truncate text-sm font-medium text-default">
|
||||
{{ restoreFile?.name ?? t('storage.backup.restoreUpload') }}
|
||||
</span>
|
||||
<span
|
||||
v-if="!restoreFile"
|
||||
class="text-xs text-muted"
|
||||
>
|
||||
{{ t('storage.backup.restoreUploadHint') }}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class="rounded-lg bg-muted/15 px-3 py-2.5 text-xs leading-relaxed text-muted">
|
||||
{{ t('setup.restoreHint') }}
|
||||
</div>
|
||||
|
||||
<StorageBackupJobProgress
|
||||
v-if="restoreLoading"
|
||||
:message="restoreProgress.message || t('setup.restoreSubmit')"
|
||||
:progress="restoreProgress.progress"
|
||||
:total="restoreProgress.total"
|
||||
/>
|
||||
|
||||
<UButton
|
||||
:label="t('setup.restoreSubmit')"
|
||||
icon="i-lucide-upload"
|
||||
size="lg"
|
||||
block
|
||||
class="w-full"
|
||||
:loading="restoreLoading"
|
||||
:disabled="!restoreFile"
|
||||
@click="submitRestore"
|
||||
/>
|
||||
|
||||
<input
|
||||
ref="restoreFileInput"
|
||||
type="file"
|
||||
accept=".phost.tar.gz,.tar.gz"
|
||||
class="hidden"
|
||||
@change="onRestoreFileChange"
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<UModal
|
||||
:open="domainSeparationConfirmOpen"
|
||||
:title="t('domainSeparationConfirm.title')"
|
||||
:description="t('domainSeparationConfirm.description')"
|
||||
@update:open="(v) => { if (!v) domainSeparationConfirmOpen = false }"
|
||||
>
|
||||
<template #footer>
|
||||
<div class="flex justify-end gap-2">
|
||||
<UButton
|
||||
:label="t('common.cancel')"
|
||||
color="neutral"
|
||||
variant="outline"
|
||||
@click="() => { domainSeparationConfirmOpen = false }"
|
||||
/>
|
||||
<UButton
|
||||
:label="t('domainSeparationConfirm.confirm')"
|
||||
color="warning"
|
||||
:loading="loading"
|
||||
@click="performSubmit"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
</UModal>
|
||||
</div>
|
||||
</template>
|
||||
Loaded 100 of 372 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user