7 Commits
Author SHA1 Message Date
O96u cc19dc6435 release: v1.4.3
GitHub Release / release (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
Add a Telegram channel or group storage backend, with proxied image URLs and an optional API proxy.
2026-10-09 15:39:24 +08:00
O96u 4ed4692f5e release: v1.4.2
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
Fix batch tagging and upload token auth; single API token and tagNames-only upload; tag management sort and responsive layout.
2026-09-23 15:38:46 +08:00
O96u 6cc4f27f7d release: v1.4.1 — 上传策略设置、保留原图与上传 tagNames
GitHub Release / release (push) Canceled after 0s
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
管理员可在设置页配置上传大小、格式、限流与保留原图;上传 API 支持按标签名称打标。
2026-09-16 10:03:05 +08:00
O96u d0eb364645 fix: host-isolation 单测显式传入 hideFolder 避免 CI 锁库
并行跑测时不再通过 isHideFolderInUrl 打开本地 SQLite。
2026-09-09 15:08:27 +08:00
O96u 91d71a1b40 fix: 修复 CI 活动日志冒烟测试在空数据库下失败
listActivityLogs 会 JOIN storage_backends;CI 无 data/ 目录时需在查询前初始化存储 schema。
2026-09-09 14:57:11 +08:00
O96u 737235acff release: v1.4.0 — 标签系统、操作日志扩展与文档截图更新
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
- 每用户标签与彩色打标,图库 OR/AND 筛选与批量打标
- 操作日志记录登录、删除、设置与标签操作
- API 标签/打标接口;README 与文档站截图同步
2026-09-09 14:46:52 +08:00
O96u f17d79b236 release: v1.3.0 — 整站备份恢复、跨后端同步与任务中心
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
2026-09-07 17:05:12 +08:00
188 changed files with 13542 additions and 1657 deletions

No files matched your search

+10
View File
@@ -30,6 +30,16 @@
# 服务端 WebP 压缩质量 1-100(默认 80;也可在设置页配置)
# WEBP_QUALITY=80
# 上传限制(也可在设置 → 访问控制配置;环境变量优先级更高)
# UPLOAD_MAX_FILE_SIZE_MB=10
# 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
+76 -1
View File
@@ -4,6 +4,82 @@
## [Unreleased]
## [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
### 改进
@@ -119,7 +195,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)
### 改进
+7 -1
View File
@@ -23,10 +23,16 @@ ENV NODE_ENV=production \
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
+20 -6
View File
@@ -31,20 +31,34 @@
**main** has no public demo. **cloudflare** branch live demo: [pic.roven.cc](https://pic.roven.cc)
| API | Gallery |
| :--: | :-----: |
| ![API](docs/screenshots/api.png) | ![Gallery](docs/screenshots/gallery.png) |
| Upload | Gallery |
| :----: | :-----: |
| ![Upload](docs/screenshots/upload.png) | ![Gallery](docs/screenshots/gallery.png) |
| API | Tag management |
| :-: | :------------: |
| ![API](docs/screenshots/api.png) | ![Tags](docs/screenshots/tags.png) |
| Storage | Settings |
| :-----: | :-------: |
| ![Storage](docs/screenshots/storage.png) | ![Settings](docs/screenshots/settings-en.png) |
| First-time setup | Restore from backup |
| :--------------: | :-----------------: |
| ![Setup](docs/screenshots/setup.png) | ![Setup restore](docs/screenshots/setup-restore.png) |
| Activity log |
| :----------: |
| ![Activity log](docs/screenshots/logs.png) |
## Features
- **Drag, click, or Ctrl+V paste** — server-side WebP, Referer hotlink protection
- **Multi-user** — login with slider, Turnstile, or Cap verification; 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
- **Multi-backend storage** — local disk + S3-compatible (R2 / COS / OSS / AWS) + Telegram channel/group; hybrid `proxy` / `public` URLs
- **Gallery** — browse, search, filter by storage/source/tags, grid/list views, batch delete and batch tagging; stats overview and source breakdown; image detail modal with link formats
- **Tags** — per-user colored tags; tag on upload (single or batch); manage in Settings (create, recolor, merge, delete); API supports `tagIds` and batch tagging
- **Backup & migration** — full-site export/restore (`.phost.tar.gz`), cross-backend sync; restore from backup on uninitialized `/setup`
- **API & Twikoo** — global / per-user tokens; `POST /api/index.php` compatible
- **Zero-config Docker** — first-run web wizard, no secrets upfront
@@ -56,7 +70,7 @@
| 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.) |
| Storage | Local disk · S3-compatible ([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS, etc.) · Telegram channel/group |
| 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 |
+20 -6
View File
@@ -31,20 +31,34 @@
**main** 分支暂无公网演示;**cloudflare** 分支在线体验:[pic.roven.cc](https://pic.roven.cc)
| API | 图库 |
| 上传 | 图库 |
| :--: | :--: |
| ![API](docs/screenshots/api.png) | ![图库](docs/screenshots/gallery.png) |
| ![上传](docs/screenshots/upload.png) | ![图库](docs/screenshots/gallery.png) |
| API | 标签管理 |
| :--: | :------: |
| ![API](docs/screenshots/api.png) | ![标签管理](docs/screenshots/tags.png) |
| 存储 | 设置 |
| :--: | :--: |
| ![存储](docs/screenshots/storage.png) | ![设置](docs/screenshots/settings.png) |
| 首次设置 | 从备份恢复 |
| :--: | :--: |
| ![首次设置](docs/screenshots/setup.png) | ![从备份恢复](docs/screenshots/setup-restore.png) |
| 操作日志 |
| :------: |
| ![操作日志](docs/screenshots/logs.png) |
## 特性
- **拖拽 / 点击 / Ctrl+V 粘贴**上传;服务端 WebP 压缩、Referer 防盗链
- **多用户**:账号密码登录(滑块 / Turnstile / Cap 人机验证)、可选开放注册;普通用户仅见自己的图片
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public`
- **图库**:浏览、搜索、按存储/来源筛选、网格/列表切换、批量删除;统计概览与来源分布
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS)+ Telegram 频道/群组;混合直链 `proxy` / `public`
- **图库**:浏览、搜索、按存储/来源/标签筛选、网格/列表切换、批量删除与批量打标;统计概览与来源分布;点击图片查看详情与多格式链接
- **标签**:每用户独立标签、彩色标记;上传后单张/批量打标;设置页管理(新建、改色、合并、删除);API 支持 `tagIds` 与批量打标
- **备份与迁移**:整站导出/恢复(`.phost.tar.gz`)、跨后端同步;setup 未初始化时可从备份恢复
- **API 与 Twikoo**:全局 / 个人 Token;`POST /api/index.php` 兼容
- **Docker 零配置**:首次访问 Web 引导创建管理员
@@ -56,7 +70,7 @@
| 后端 | [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 等) |
| 存储 | 本地磁盘 · S3 兼容([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS 等)· Telegram 频道/群组 |
| 国际化 | [@nuxtjs/i18n](https://i18n.nuxtjs.org)(简体中文 / English) |
| 质量与文档 | [Vitest](https://vitest.dev) · [VitePress](https://vitepress.dev) 文档站 |
| 部署 | Docker · Node.js 22 |
@@ -74,7 +88,7 @@ docker run -d \
浏览器打开 `http://<主机IP>:6892`,按引导完成设置即可。
**详细说明**(环境变量、升级迁移、双域名、API、Twikoo、反向代理、本地开发等)见 **[用户文档](https://o96u.github.io/PicHost/)**。
**详细说明**(环境变量、双域名、API、Twikoo、反向代理、本地开发等)见 **[用户文档](https://o96u.github.io/PicHost/)**。
| 分支 | 说明 |
| ---- | ---- |
+112
View File
@@ -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>
+150 -10
View File
@@ -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
@@ -11,19 +12,26 @@ const props = withDefaults(defineProps<{
compact?: boolean
gallery?: boolean
allowDelete?: boolean
showTags?: boolean
showTagAction?: boolean
}>(), {
selectable: true,
showKey: true,
showStorage: false,
compact: false,
gallery: false,
allowDelete: true
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()
@@ -79,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(() => {
@@ -96,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
}
@@ -107,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')
}
@@ -127,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)
}
@@ -210,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"
@@ -231,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>
@@ -302,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)]"
@@ -371,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>
@@ -396,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"
+13 -1
View File
@@ -13,6 +13,8 @@ const props = withDefaults(defineProps<{
/** 图库:5 列 × 2 行,缩略图略扁 */
gallery?: boolean
allowDelete?: boolean
showTags?: boolean
showTagAction?: boolean
}>(), {
selectable: true,
showKey: true,
@@ -20,7 +22,9 @@ const props = withDefaults(defineProps<{
dense: false,
compact: false,
gallery: false,
allowDelete: true
allowDelete: true,
showTags: false,
showTagAction: false
})
const gridClass = computed(() => {
@@ -37,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()
@@ -68,9 +75,14 @@ function updateSelection(key: string, selected: boolean) {
: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
+53 -10
View File
@@ -1,18 +1,18 @@
<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,
showTags: false,
allowDelete: true
})
@@ -22,6 +22,7 @@ const emit = defineEmits<{
}>()
const toast = useToast()
const { formatFileSize } = useFileSize()
const { t, locale } = useI18n()
const { copyFormat } = useUploadPreferences()
@@ -30,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 },
@@ -65,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(() => {
@@ -110,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
@@ -128,11 +140,9 @@ watch(() => props.open, (open) => {
}
})
function selectEmbedFormat(value: EmbedFormat) {
function selectEmbedFormat(value: CopyFormat) {
embedFormat.value = value
if (value !== 'bbcode') {
copyFormat.value = value
}
copyFormat.value = value
}
async function copyText(text: string, successTitle: string) {
@@ -288,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"
@@ -296,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>
+102
View File
@@ -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>
+296
View File
@@ -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 = 12
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>
+61
View File
@@ -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>
+127
View File
@@ -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>
+158
View File
@@ -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>
+49
View File
@@ -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
+233
View File
@@ -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>
+3 -2
View File
@@ -23,7 +23,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 +33,7 @@ const clientQualityLevel = computed(() => {
return t('preferences.qualityLow')
})
function setCopyFormat(value: 'url' | 'markdown' | 'html') {
function setCopyFormat(value: 'url' | 'markdown' | 'html' | 'bbcode') {
copyFormat.value = value
}
+16 -9
View File
@@ -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>
-9
View File
@@ -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"
+42 -1
View File
@@ -5,24 +5,39 @@ 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
}>(), {
selectedCount: 0,
loading: false,
showBatchDelete: true
showBatchDelete: true,
showBatchTags: 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': []
'manage-tags': []
}>()
const { t } = useI18n()
@@ -74,6 +89,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"
@@ -100,6 +127,20 @@ function viewButtonClass(active: boolean) {
{{ t('stats.resetFilters') }}
</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"
+140 -28
View File
@@ -1,16 +1,18 @@
<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,
showTags: false,
showDelete: true
})
@@ -18,11 +20,15 @@ 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(() =>
@@ -76,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>
@@ -88,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"
@@ -101,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>
@@ -125,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)"
>
@@ -152,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"
@@ -217,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>
+1 -1
View File
@@ -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>
+319 -316
View File
@@ -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 publicPathFromKey(key: string) {
if (hideFolderInUrl.value) {
const slash = key.lastIndexOf('/')
return slash >= 0 ? key.slice(slash + 1) : key
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`
}
const prefix = 'images/'
return key.startsWith(prefix) ? key.slice(prefix.length) : key
}
function imageUrl(key: string) {
const base = imageLinkBase.value.replace(/\/$/, '')
const path = publicPathFromKey(key)
if (!base) return `/${path}`
return `${base}/${path}`
function statusLabel(status: LogStatus) {
return status === 'failure' ? t('logs.resultFailure') : t('logs.resultSuccess')
}
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 statusDotClass(status: LogStatus) {
return status === 'failure' ? 'bg-error' : 'bg-success'
}
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">
{{ t('logs.pageTitle') }}
</h2>
<p class="mt-0.5 text-xs text-muted">
{{ isAdmin ? t('logs.pageSubtitleAdmin') : t('logs.pageSubtitle') }}
<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>
</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,263 +349,209 @@ 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
v-if="loading"
class="p-4 sm:p-6"
>
<div class="space-y-3 sm:hidden">
<USkeleton
v-for="n in 6"
:key="`mobile-${n}`"
class="h-24 rounded-lg"
/>
</div>
<div class="hidden space-y-2 sm:block">
<USkeleton
v-for="n in 8"
:key="`desktop-${n}`"
class="h-12 rounded-lg"
/>
</div>
</div>
<template v-else-if="listData && listData.items.length">
<div class="min-w-0 sm:hidden">
<div class="divide-y divide-default">
<article
v-for="row in listData.items"
:key="row.id"
class="min-w-0 px-4 py-3.5"
>
<div class="flex items-start justify-between gap-3">
<time class="text-xs text-muted">
{{ formatTimeShort(row.createdAt) }}
</time>
<span class="shrink-0 text-xs tabular-nums text-muted">
{{ formatFileSize(row.size) }}
</span>
</div>
<div class="mt-2 flex min-w-0 max-w-full flex-wrap items-center gap-1.5">
<span :class="actionBadgeClass(row.action)">
<UIcon
:name="actionIcon(row.action)"
class="size-3 shrink-0"
/>
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }}
</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">
{{ sourceLabel(row.source) }}
</span>
<span
v-if="isAdmin"
class="text-xs text-muted"
>
{{ 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
class="mt-2 truncate text-sm"
:title="row.originalName"
>
{{ 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>
<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')"
/>
</div>
</article>
<div class="overflow-hidden rounded-xl border border-default bg-default">
<div
v-if="loading"
class="p-4 sm:p-6"
>
<div class="space-y-3 sm:hidden">
<USkeleton
v-for="n in 6"
:key="`mobile-${n}`"
class="h-24 rounded-lg"
/>
</div>
<div class="hidden space-y-2 sm:block">
<USkeleton
v-for="n in 8"
:key="`desktop-${n}`"
class="h-12 rounded-lg"
/>
</div>
</div>
<div class="hidden min-w-0 sm:block">
<table class="w-full table-fixed 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">
{{ t('logs.colTime') }}
</th>
<th
v-if="isAdmin"
class="w-20 px-4 py-3 font-medium"
>
{{ t('logs.colUser') }}
</th>
<th class="w-20 whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colAction') }}
</th>
<th class="w-16 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">
{{ t('logs.colFile') }}
</th>
<th class="w-20 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>
</tr>
</thead>
<tbody class="divide-y divide-default">
<tr
<template v-else-if="listData && listData.items.length">
<div class="min-w-0 sm:hidden">
<div class="divide-y divide-default">
<article
v-for="row in listData.items"
:key="row.id"
class="hover:bg-muted/20"
class="min-w-0 px-4 py-3.5"
>
<td class="px-4 py-3 text-xs text-muted sm:px-6">
<span class="block truncate">{{ formatTime(row.createdAt) }}</span>
</td>
<td
v-if="isAdmin"
class="px-4 py-3 text-xs"
>
<span class="block truncate">{{ row.username ?? '—' }}</span>
</td>
<td class="whitespace-nowrap px-4 py-3">
<div class="flex items-start justify-between gap-3">
<time class="text-xs text-muted">
{{ formatTimeShort(row.createdAt) }}
</time>
<span class="shrink-0 text-xs tabular-nums text-muted">
{{ formatSize(row.action, row.size) }}
</span>
</div>
<div class="mt-2 flex min-w-0 max-w-full flex-wrap items-center gap-1.5">
<span :class="actionBadgeClass(row.action)">
<UIcon
: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"
v-if="isAdmin"
class="text-xs text-muted"
>
<UIcon
:name="storageIcon(row.storage)"
class="size-3.5 shrink-0 opacity-70"
/>
<span class="truncate">{{ row.storage.name }}</span>
{{ row.username ?? '—' }}
</span>
<span
v-else
class="text-muted"
>—</span>
</td>
<td
class="hidden max-w-0 truncate px-4 py-3 md:table-cell"
</div>
<p
class="mt-2 truncate text-sm"
:title="row.originalName"
>
{{ row.originalName }}
</td>
<td class="whitespace-nowrap px-4 py-3 tabular-nums text-muted">
{{ formatFileSize(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>
</p>
<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 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>
</td>
</tr>
</tbody>
</table>
{{ statusLabel(row.status) }}
</span>
</div>
</article>
</div>
</div>
<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="whitespace-nowrap px-4 py-3 font-medium sm:px-5">
{{ t('logs.colTime') }}
</th>
<th
v-if="isAdmin"
class="whitespace-nowrap px-4 py-3 font-medium"
>
{{ t('logs.colUser') }}
</th>
<th class="whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colAction') }}
</th>
<th class="whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colSource') }}
</th>
<th class="px-4 py-3 font-medium">
{{ t('logs.colFile') }}
</th>
<th class="whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colSize') }}
</th>
<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>
<tbody class="divide-y divide-default">
<tr
v-for="row in listData.items"
:key="row.id"
class="hover:bg-muted/20"
>
<td class="whitespace-nowrap px-4 py-3 text-xs text-muted sm:px-5">
{{ formatTime(row.createdAt) }}
</td>
<td
v-if="isAdmin"
class="whitespace-nowrap px-4 py-3 text-xs"
>
{{ row.username ?? '—' }}
</td>
<td class="whitespace-nowrap px-4 py-3">
<span :class="actionBadgeClass(row.action)">
<UIcon
:name="actionIcon(row.action)"
class="size-3 shrink-0"
/>
{{ actionLabel(row.action) }}
</span>
</td>
<td class="whitespace-nowrap px-4 py-3">
<span :class="sourceBadgeClass(row.source)">
<UIcon
:name="sourceIcon(row.source)"
class="size-3 shrink-0"
/>
{{ sourceLabel(row.source) }}
</span>
</td>
<td
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">
{{ formatSize(row.action, row.size) }}
</td>
<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
class="size-1.5 rounded-full"
:class="statusDotClass(row.status)"
/>
{{ statusLabel(row.status) }}
</span>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<div
v-else
class="px-4 py-16 text-center text-sm text-muted sm:px-6"
>
{{ t('logs.empty') }}
</div>
</template>
<div
v-else
class="px-4 py-16 text-center text-sm text-muted sm:px-6"
>
{{ t('logs.empty') }}
</div>
<div
v-if="listData && listData.total > 0"
class="border-t border-default px-4 py-4 sm:px-6"
>
<PaginationBar
:page="listData.page"
:total-pages="listData.totalPages"
:total="listData.total"
:unit="t('logs.entriesUnit')"
:loading="loading"
@update:page="handlePageChange"
/>
<div
v-if="listData && listData.total > 0"
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>
+2 -4
View File
@@ -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">
<slot />
</div>
<div class="mt-6 space-y-4">
<slot />
</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>
+5 -3
View File
@@ -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>
<slot />
<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"
+40 -12
View File
@@ -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"
+39 -7
View File
@@ -4,32 +4,64 @@ defineProps<{
updateAvailable: boolean
latestVersion: string | null
releaseUrl: string | null
checking: boolean
}>()
const emit = 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>
@@ -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,329 @@
<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'
defineProps<{
part: 'upload-preference' | 'image-processing' | 'login-rate'
uploadMaxFileSizeMbSource?: PolicySource
allowedMimeTypesSource?: PolicySource
uploadRateIpMaxSource?: PolicySource
uploadRateTokenMaxSource?: PolicySource
uploadRateWindowMinutesSource?: PolicySource
loginRateMaxSource?: PolicySource
loginRateWindowMinutesSource?: PolicySource
preserveOriginalUploadSource?: PolicySource
mimeTypeOptions?: ReadonlyArray<{ mime: MimeType, label: string }>
}>()
const uploadMaxFileSizeMbDraft = defineModel<number>('uploadMaxFileSizeMb')
const allowedMimeTypesDraft = defineModel<MimeType[]>('allowedMimeTypes')
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 { 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 clampUploadMaxFileSizeMb(value: unknown): number {
const num = Number(value)
if (!Number.isFinite(num)) return uploadMaxFileSizeMbDraft.value ?? 10
return Math.min(100, Math.max(1, Math.round(num)))
}
function onUploadMaxFileSizeInput(event: Event) {
uploadMaxFileSizeMbDraft.value = clampUploadMaxFileSizeMb(
(event.target as HTMLInputElement).value
)
}
function onUploadMaxFileSizeNumberInput(value: string | number) {
uploadMaxFileSizeMbDraft.value = clampUploadMaxFileSizeMb(value)
}
</script>
<template>
<template v-if="part === 'upload-preference'">
<div class="py-4">
<div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-highlighted">
{{ t('settings.uploadMaxFileSize') }}
</p>
<UBadge
v-if="uploadMaxFileSizeMbSource"
:color="sourceBadge(uploadMaxFileSizeMbSource).color"
variant="subtle"
size="xs"
>
{{ sourceBadge(uploadMaxFileSizeMbSource).label }}
</UBadge>
</div>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('settings.uploadMaxFileSizeHint') }}
</p>
<div
class="mt-3 flex items-center gap-3"
:class="uploadMaxFileSizeMbSource === 'env' ? 'pointer-events-none opacity-60' : ''"
>
<input
type="range"
min="1"
max="100"
:value="uploadMaxFileSizeMbDraft"
class="h-1.5 min-w-0 flex-1 cursor-pointer appearance-none rounded-full bg-muted accent-primary"
:disabled="uploadMaxFileSizeMbSource === 'env'"
@input="onUploadMaxFileSizeInput"
>
<div class="flex shrink-0 items-center gap-1.5">
<UInput
:model-value="uploadMaxFileSizeMbDraft"
type="number"
:min="1"
:max="100"
size="xs"
class="w-14 tabular-nums"
:disabled="uploadMaxFileSizeMbSource === 'env'"
@update:model-value="onUploadMaxFileSizeNumberInput"
/>
<span class="text-xs text-muted">MB</span>
</div>
</div>
</div>
<div class="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="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,4 +1,8 @@
<script setup lang="ts">
defineProps<{
part: 'upload-preference' | 'image-processing'
}>()
const {
compressEnabled,
autoCopyMarkdown,
@@ -19,16 +23,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 +36,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,105 +48,107 @@ onMounted(() => {
</script>
<template>
<SettingsSection :title="t('preferences.processing')">
<SettingsGroup>
<SettingsToggleRow
v-model="compressEnabled"
:title="t('preferences.clientCompress')"
:hint="t('preferences.clientCompressHint')"
<template v-if="part === 'image-processing'">
<SettingsToggleRow
v-model="compressEnabled"
:title="t('preferences.clientCompress')"
:hint="t('preferences.clientCompressHint')"
/>
<div
v-if="userSettings"
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">
<span>{{ t('preferences.autoDeletePrefix') }}</span>
<UInput
v-model.number="userAutoDeleteDaysDraft"
type="number"
min="1"
max="3650"
size="xs"
class="w-14 tabular-nums"
:class="userAutoDeleteEnabled ? '' : 'pointer-events-none opacity-40'"
/>
<span>{{ t('preferences.autoDeleteSuffix') }}</span>
</p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('preferences.autoDeleteHint') }}
</p>
</div>
<USwitch
v-model="userAutoDeleteEnabled"
class="mt-0.5 shrink-0"
/>
<div
v-if="userSettings"
class="flex items-start justify-between gap-4 px-4 py-4 sm:px-5"
>
<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">
<span>{{ t('preferences.autoDeletePrefix') }}</span>
<UInput
v-model.number="userAutoDeleteDaysDraft"
type="number"
min="1"
max="3650"
size="xs"
class="w-14 tabular-nums"
:class="userAutoDeleteEnabled ? '' : 'pointer-events-none opacity-40'"
/>
<span>{{ t('preferences.autoDeleteSuffix') }}</span>
</p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('preferences.autoDeleteHint') }}
</p>
</div>
<USwitch
v-model="userAutoDeleteEnabled"
class="mt-0.5 shrink-0"
/>
</div>
<div
v-else
class="flex justify-center py-4"
>
<UIcon
name="i-lucide-loader-circle"
class="size-5 animate-spin text-muted"
/>
</div>
<div class="py-4">
<div class="min-w-0">
<p class="text-sm font-medium text-highlighted">
{{ t('preferences.webpQuality') }}
</p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('preferences.webpQualityHint') }}
</p>
</div>
<div
v-else
class="flex justify-center py-4"
>
<UIcon
name="i-lucide-loader-circle"
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">
<p class="text-sm font-medium text-highlighted">
{{ t('preferences.webpQuality') }}
</p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ 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>
<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">
<p class="text-sm font-medium text-highlighted">
{{ t('settings.defaultCopyFormat') }}
</p>
<div
class="flex w-full max-w-xs gap-1 rounded-lg border border-default p-0.5 sm:w-auto"
: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]"
:variant="copyFormat === item.value ? 'solid' : 'ghost'"
:color="copyFormat === item.value ? 'primary' : 'neutral'"
:label="item.label"
@click="setCopyFormat(item.value)"
/>
</div>
<template v-else>
<SettingsToggleRow
v-model="autoCopyMarkdown"
:title="t('preferences.autoCopy')"
:hint="t('preferences.autoCopyHint')"
/>
<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="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"
:variant="copyFormat === item.value ? 'solid' : 'ghost'"
:color="copyFormat === item.value ? 'primary' : 'neutral'"
:label="item.label"
@click="setCopyFormat(item.value)"
/>
</div>
</SettingsGroup>
</SettingsSection>
</div>
</template>
</template>
+444
View File
@@ -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>
+141
View File
@@ -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>
+257
View File
@@ -0,0 +1,257 @@
<script setup lang="ts">
import type { BackupJobItem } from '~/types/backup'
defineProps<{
jobs: BackupJobItem[]
polling: boolean
page: number
totalPages: number
total: number
pageSize: number
loading?: boolean
}>()
const emit = defineEmits<{
'retry': [jobId: string]
'download': [jobId: string]
'cancel': [jobId: string]
'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')
}
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 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 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>
<UIcon
v-if="polling"
name="i-lucide-loader-circle"
class="size-4 shrink-0 animate-spin text-muted"
/>
</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.colCreated') }}
</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-32 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="shrink-0 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>
</div>
</td>
<td class="px-4 py-3.5 whitespace-nowrap text-xs text-muted sm:px-5">
{{ formatTime(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)"
/>
</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,305 @@
<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 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 {
toast.add({ title: t('storage.backup.previewFailed'), 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>
+37 -7
View File
@@ -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')"
+190 -92
View File
@@ -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,21 +130,44 @@ function detectProvider(config: StorageBackendItem['config']): StorageProvider {
return 'custom'
}
function resetCreateDefaults() {
name.value = ''
provider.value = 'r2'
applyProviderTemplate('r2')
bucket.value = ''
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 || backend.type !== 's3') {
if (props.createMode) {
name.value = ''
provider.value = 'r2'
applyProviderTemplate('r2')
bucket.value = ''
prefix.value = ''
accessKeyId.value = ''
secretAccessKey.value = ''
servingMode.value = 'proxy'
publicUrl.value = ''
quotaValue.value = ''
quotaUnit.value = 'GB'
}
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,105 +246,158 @@ function handleSubmit() {
/>
</div>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.endpoint') }}</label>
<UInput
v-model="endpoint"
class="w-full font-mono text-sm"
/>
</div>
<div class="grid gap-3 sm:grid-cols-2">
<div class="space-y-2">
<label class="text-sm">{{ t('storage.region') }}</label>
<UInput
v-model="region"
class="w-full font-mono text-sm"
/>
</div>
<template v-if="isTelegram">
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.bucket') }}
{{ t('storage.telegramChatId') }}
<span class="text-error">*</span>
</label>
<UInput
v-model="bucket"
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>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.prefix') }}</label>
<UInput
v-model="prefix"
:placeholder="t('storage.prefixPlaceholder')"
class="w-full font-mono text-sm"
/>
</div>
<label class="flex cursor-pointer items-center gap-2">
<UCheckbox v-model="forcePathStyle" />
<span class="text-sm">{{ t('storage.forcePathStyle') }}</span>
</label>
<div class="grid gap-3 sm:grid-cols-2">
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.accessKey') }}
{{ t('storage.telegramBotToken') }}
<span
v-if="createMode"
class="text-error"
>*</span>
</label>
<UInput
v-model="accessKeyId"
:placeholder="backend?.secretsMasked.accessKeyId || ''"
class="w-full font-mono text-sm"
:required="createMode"
/>
</div>
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.secretKey') }}
<span
v-if="createMode"
class="text-error"
>*</span>
</label>
<UInput
v-model="secretAccessKey"
v-model="botToken"
type="password"
:placeholder="backend?.secretsMasked.secretAccessKey || ''"
:placeholder="backend?.secretsMasked.botToken || ''"
class="w-full font-mono text-sm"
:required="createMode"
/>
</div>
</div>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.servingMode') }}</label>
<URadioGroup
v-model="servingMode"
:items="servingModeOptions"
/>
<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.servingHint') }}
{{ t('storage.telegramServingHint') }}
</p>
</div>
</template>
<div
v-if="servingMode === 'public'"
class="space-y-2"
>
<label class="text-sm">{{ t('storage.publicUrl') }}</label>
<UInput
v-model="publicUrl"
:placeholder="t('storage.publicUrlPlaceholder')"
class="w-full font-mono text-sm"
/>
</div>
<template v-else>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.endpoint') }}</label>
<UInput
v-model="endpoint"
class="w-full font-mono text-sm"
/>
</div>
<div class="grid gap-3 sm:grid-cols-2">
<div class="space-y-2">
<label class="text-sm">{{ t('storage.region') }}</label>
<UInput
v-model="region"
class="w-full font-mono text-sm"
/>
</div>
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.bucket') }}
<span class="text-error">*</span>
</label>
<UInput
v-model="bucket"
class="w-full font-mono text-sm"
required
/>
</div>
</div>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.prefix') }}</label>
<UInput
v-model="prefix"
:placeholder="t('storage.prefixPlaceholder')"
class="w-full font-mono text-sm"
/>
</div>
<label class="flex cursor-pointer items-center gap-2">
<UCheckbox v-model="forcePathStyle" />
<span class="text-sm">{{ t('storage.forcePathStyle') }}</span>
</label>
<div class="grid gap-3 sm:grid-cols-2">
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.accessKey') }}
<span
v-if="createMode"
class="text-error"
>*</span>
</label>
<UInput
v-model="accessKeyId"
:placeholder="backend?.secretsMasked.accessKeyId || ''"
class="w-full font-mono text-sm"
:required="createMode"
/>
</div>
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.secretKey') }}
<span
v-if="createMode"
class="text-error"
>*</span>
</label>
<UInput
v-model="secretAccessKey"
type="password"
:placeholder="backend?.secretsMasked.secretAccessKey || ''"
class="w-full font-mono text-sm"
:required="createMode"
/>
</div>
</div>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.servingMode') }}</label>
<URadioGroup
v-model="servingMode"
:items="servingModeOptions"
/>
<p class="text-xs text-muted">
{{ t('storage.servingHint') }}
</p>
</div>
<div
v-if="servingMode === 'public'"
class="space-y-2"
>
<label class="text-sm">{{ t('storage.publicUrl') }}</label>
<UInput
v-model="publicUrl"
:placeholder="t('storage.publicUrlPlaceholder')"
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,178 @@
<script setup lang="ts">
import type { BackupJobItem, 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,
estimate,
packages,
loadingEstimate,
polling,
hasActiveJob,
getActiveJob,
loadJobs,
setJobsPage,
setJobsPageSize,
loadEstimate,
startPolling,
createExport,
previewRestore,
confirmRestore,
previewSync,
startSync,
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 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 onSync(body: {
fromBackendId: string
toBackendId: string
deleteSource: boolean
setDefault: boolean
}) {
await startSync(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>
<StorageBackupJobTable
:jobs="jobs"
:polling="polling"
:page="jobsPage"
:total-pages="jobsTotalPages"
:total="jobsTotal"
:page-size="jobsPageSize"
:loading="jobsLoading"
@update:page="setJobsPage"
@update:page-size="setJobsPageSize"
@download="onDownload"
@retry="onRetry"
@cancel="onCancel"
@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>
+9 -1
View File
@@ -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": [
+319
View File
@@ -0,0 +1,319 @@
import type {
BackupEstimate,
BackupJobItem,
BackupPackageItem,
BackupRestorePreview,
BackendSyncPreview
} 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 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
}
})
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 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 form = new FormData()
form.append('file', input.file)
form.append('dryRun', 'true')
const data = await $fetch<{ preview: BackupRestorePreview }>(
'/api/admin/backup/restore',
{ method: 'POST', credentials: 'include', body: form }
)
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 form = new FormData()
form.append('file', input.file)
form.append('conflictMode', input.conflictMode)
const data = await $fetch<{ job: BackupJobItem }>(
'/api/admin/backup/restore',
{ method: 'POST', credentials: 'include', body: form }
)
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 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,
estimate,
packages,
loadingEstimate,
polling,
hasActiveJob,
getActiveJob,
loadJobs,
setJobsPage,
setJobsPageSize,
loadEstimate,
startPolling,
stopPolling,
createExport,
previewRestore,
confirmRestore,
previewSync,
startSync,
retryJob,
cancelJob,
downloadUrl
}
}
+61 -1
View File
@@ -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
}
}
+14 -2
View File
@@ -10,14 +10,15 @@ const MAX_FILES = 10
export function useImageUpload() {
const toast = useToast()
const { t } = useI18n()
const { compressEnabled, clientWebpQuality } = useUploadPreferences()
const { compressEnabled, clientWebpQuality, lastTagIds } = useUploadPreferences()
const { items: tagItems } = useTags()
const uploading = ref(false)
const progressItems = ref<UploadProgressItem[]>([])
const lastUploadResult = ref<UploadResponse | null>(null)
async function uploadFiles(
files: File[],
options?: { notify?: boolean }
options?: { notify?: boolean, tagIds?: number[] }
) {
if (uploading.value) return
@@ -58,6 +59,17 @@ export function useImageUpload() {
formData.append('files', file, file.name)
}
const tagIds = options?.tagIds ?? lastTagIds.value
if (tagIds.length) {
const names = tagIds
.map(id => tagItems.value.find(tag => tag.id === id)?.name)
.filter((name): name is string => Boolean(name))
if (names.length) {
formData.append('tagNames', JSON.stringify(names))
}
lastTagIds.value = tagIds
}
const response = await $fetch<UploadResponse>('/api/images/upload', {
method: 'POST',
body: formData
+48
View File
@@ -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
}
}
+122
View File
@@ -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
}
}
+25 -7
View File
@@ -1,19 +1,21 @@
const STORAGE_KEY = 'pichost.upload-preferences'
export type CopyFormat = 'url' | 'markdown' | 'html'
export type CopyFormat = 'url' | 'markdown' | 'html' | 'bbcode'
export interface UploadPreferences {
compressEnabled: boolean
autoCopyMarkdown: boolean
copyFormat: CopyFormat
clientWebpQuality: number
lastTagIds: number[]
}
const DEFAULTS: UploadPreferences = {
compressEnabled: false,
autoCopyMarkdown: false,
copyFormat: 'markdown',
clientWebpQuality: 80
clientWebpQuality: 80,
lastTagIds: []
}
function clampQuality(value: unknown): number {
@@ -23,7 +25,7 @@ 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 {
@@ -37,7 +39,10 @@ function readStored(): UploadPreferences {
compressEnabled: parsed.compressEnabled === true,
autoCopyMarkdown: parsed.autoCopyMarkdown === true,
copyFormat: isCopyFormat(parsed.copyFormat) ? parsed.copyFormat : DEFAULTS.copyFormat,
clientWebpQuality: clampQuality(parsed.clientWebpQuality)
clientWebpQuality: clampQuality(parsed.clientWebpQuality),
lastTagIds: Array.isArray(parsed.lastTagIds)
? parsed.lastTagIds.filter(id => Number.isInteger(id) && id > 0)
: DEFAULTS.lastTagIds
}
} catch {
return { ...DEFAULTS }
@@ -54,6 +59,7 @@ export function useUploadPreferences() {
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 lastTagIds = useState<number[]>('upload-pref-last-tag-ids', () => DEFAULTS.lastTagIds)
const loaded = useState('upload-pref-loaded', () => false)
function loadPreferences() {
@@ -62,6 +68,7 @@ export function useUploadPreferences() {
autoCopyMarkdown.value = stored.autoCopyMarkdown
copyFormat.value = stored.copyFormat
clientWebpQuality.value = stored.clientWebpQuality
lastTagIds.value = stored.lastTagIds
loaded.value = true
}
@@ -74,11 +81,20 @@ export function useUploadPreferences() {
compressEnabled: compressEnabled.value,
autoCopyMarkdown: autoCopyMarkdown.value,
copyFormat: copyFormat.value,
clientWebpQuality: clampQuality(clientWebpQuality.value)
clientWebpQuality: clampQuality(clientWebpQuality.value),
lastTagIds: lastTagIds.value
})
}
watch([compressEnabled, autoCopyMarkdown, copyFormat, clientWebpQuality], () => {
function resetToDefaults() {
compressEnabled.value = DEFAULTS.compressEnabled
autoCopyMarkdown.value = DEFAULTS.autoCopyMarkdown
copyFormat.value = DEFAULTS.copyFormat
clientWebpQuality.value = DEFAULTS.clientWebpQuality
savePreferences()
}
watch([compressEnabled, autoCopyMarkdown, copyFormat, clientWebpQuality, lastTagIds], () => {
if (loaded.value) {
savePreferences()
}
@@ -89,8 +105,10 @@ export function useUploadPreferences() {
autoCopyMarkdown,
copyFormat,
clientWebpQuality,
lastTagIds,
loaded,
loadPreferences,
savePreferences
savePreferences,
resetToDefaults
}
}
+16 -32
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
interface SettingsResponse {
interface UserTokenResponse {
apiUploadToken: string
tokenSource: 'env' | 'db' | 'none'
envTokenOverride: boolean
@@ -16,7 +16,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,19 +25,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'
@@ -54,11 +52,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) {
@@ -66,6 +63,7 @@ async function loadSettings() {
if (isAuthenticated.value) {
toast.add({ title: t('api.loadFailed'), color: 'error' })
}
tokenSettings.value = null
} finally {
loading.value = false
}
@@ -80,30 +78,17 @@ 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' })
}
toast.add({ title: t('api.regenerateFailed'), color: 'error' })
}
} finally {
regenerating.value = false
@@ -126,16 +111,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>
@@ -174,8 +159,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"
/>
+116 -4
View File
@@ -46,10 +46,18 @@ const {
activeUploadSource,
setActiveUploadSource,
resetFilters,
loadStorageBackendOptions
loadStorageBackendOptions,
activeTagIds,
activeTagMode,
activeUntaggedOnly,
setActiveTagFilter,
toggleTagFilter,
listQueryParams
} = 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()
@@ -66,6 +74,7 @@ const showScrollTop = ref(false)
const previewOpen = ref(false)
const previewImage = ref<ImageItem | null>(null)
const viewMode = ref<'grid' | 'list'>('grid')
const batchTagOpen = ref(false)
const currentUploadSource = ref('all')
const currentStorageBackend = ref('all')
@@ -96,7 +105,8 @@ function scrollToTop() {
async function fetchStats() {
stats.value = await $fetch<StatsResponse>('/api/stats', {
credentials: 'include'
credentials: 'include',
query: listQueryParams()
})
}
@@ -131,7 +141,8 @@ async function refreshAll() {
await Promise.all([
fetchStats(),
reloadGallery(),
loadStorageBackendOptions()
loadStorageBackendOptions(),
fetchTags()
])
currentUploadSource.value = activeUploadSource.value
currentStorageBackend.value = activeStorageBackend.value
@@ -174,11 +185,88 @@ 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 updateSelectedKeys(keys: Set<string>) {
selectedKeys.value = keys
}
@@ -398,16 +486,26 @@ 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"
@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"
@manage-tags="goToTagSettings"
/>
</div>
@@ -429,6 +527,7 @@ watch(isAuthenticated, async (authed, prev) => {
gallery
:show-key="false"
show-storage
show-tags
:items="items"
:selected-keys="selectedKeys"
:selectable="true"
@@ -436,11 +535,14 @@ watch(isAuthenticated, async (authed, prev) => {
@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"
@@ -448,12 +550,15 @@ watch(isAuthenticated, async (authed, prev) => {
@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"
@@ -479,6 +584,13 @@ watch(isAuthenticated, async (authed, prev) => {
@confirm="confirmDelete"
/>
<BatchTagModal
v-model:open="batchTagOpen"
:tags="tagItems"
:selected-count="selectedCount"
@confirm="confirmBatchTags"
/>
<UButton
v-show="showScrollTop"
icon="i-lucide-arrow-up"
+85 -3
View File
@@ -1,5 +1,6 @@
<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()
@@ -9,6 +10,9 @@ 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()
@@ -17,6 +21,9 @@ 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(
() =>
@@ -47,7 +54,7 @@ onMounted(async () => {
await checkSession()
}
if (isAuthenticated.value) {
await loadPage()
await Promise.all([loadPage(), fetchTags()])
}
})
@@ -66,6 +73,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,7 +117,9 @@ async function handleUpload(files: File[]) {
? first.url
: copyFormat.value === 'html'
? first.html
: first.markdown
: copyFormat.value === 'bbcode'
? buildImageBbcode(first.url)
: first.markdown
if (text) await copyUploadLink(text)
}
}
@@ -148,6 +159,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>
@@ -189,6 +244,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 +259,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>
@@ -209,6 +276,21 @@ function requestPreviewDelete() {
: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>
+337 -188
View File
@@ -2,10 +2,14 @@
import type { SettingsTab } from '~/types/settings'
import { ADMIN_SETTINGS_TABS, USER_SETTINGS_TABS } from '~/types/settings'
import { willActivateDomainSeparation } from '~/utils/domain-separation'
import SettingsUserPreferencesFields from '~/components/settings/SettingsUserPreferencesFields.vue'
import SettingsUploadPolicyFields from '~/components/settings/SettingsUploadPolicyFields.vue'
type SettingSource = 'env' | 'db' | 'none'
type WebpQualitySource = 'env' | 'db' | 'default'
type PolicySource = 'env' | 'db' | 'default'
type LoginVerificationMethod = 'slider' | 'turnstile' | 'cap'
type MimeType = 'image/jpeg' | 'image/png' | 'image/webp' | 'image/gif' | 'image/svg+xml' | 'image/x-icon'
interface SettingsResponse {
apiUploadToken: string
@@ -41,6 +45,23 @@ interface SettingsResponse {
capApiEndpoint: string
capSecret: string
appVersion: string
uploadMaxFileSizeMb: number
uploadMaxFileSizeMbSource: PolicySource
allowedMimeTypes: MimeType[]
allowedMimeTypesSource: PolicySource
uploadRateIpMax: number
uploadRateIpMaxSource: PolicySource
uploadRateTokenMax: number
uploadRateTokenMaxSource: PolicySource
uploadRateWindowMinutes: number
uploadRateWindowMinutesSource: PolicySource
loginRateMax: number
loginRateMaxSource: PolicySource
loginRateWindowMinutes: number
loginRateWindowMinutesSource: PolicySource
preserveOriginalUpload: boolean
preserveOriginalUploadSource: PolicySource
mimeTypeOptions: ReadonlyArray<{ mime: MimeType, label: string }>
}
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
@@ -51,7 +72,7 @@ const router = useRouter()
const allowedTabs = computed(() => (isAdmin.value ? ADMIN_SETTINGS_TABS : USER_SETTINGS_TABS))
const defaultTab = computed<SettingsTab>(() => (isAdmin.value ? 'basic' : 'logs'))
const defaultTab = computed<SettingsTab>(() => (isAdmin.value ? 'basic' : 'tags'))
function parseTab(value: unknown): SettingsTab | null {
if (typeof value !== 'string') return null
@@ -69,26 +90,53 @@ const activeTab = computed<SettingsTab>({
const sidebarItems = computed(() => {
const labels: Record<SettingsTab, { label: string, icon: string }> = {
basic: { label: t('settings.navBasic'), icon: 'i-lucide-sliders-horizontal' },
basic: { label: t('settings.navBasic'), icon: 'i-lucide-settings' },
domains: { label: t('settings.navDomains'), icon: 'i-lucide-globe' },
access: { label: t('settings.navAccess'), icon: 'i-lucide-shield' },
tags: { label: t('settings.navTags'), icon: 'i-lucide-tags' },
logs: { label: t('settings.navLogs'), icon: 'i-lucide-scroll-text' }
}
return allowedTabs.value.map(id => ({ id, ...labels[id] }))
})
const tabPageHeader = computed(() => {
const headers: Record<SettingsTab, { icon: string, title: string, subtitle: string }> = {
basic: {
icon: 'i-lucide-settings',
title: t('settings.navBasic'),
subtitle: t('settings.pageSubtitleBasic')
},
domains: {
icon: 'i-lucide-globe',
title: t('settings.navDomains'),
subtitle: t('settings.pageSubtitleDomains')
},
access: {
icon: 'i-lucide-shield',
title: t('settings.navAccess'),
subtitle: t('settings.pageSubtitleAccess')
},
tags: {
icon: 'i-lucide-tags',
title: t('settings.navTags'),
subtitle: t('settings.pageSubtitleTags')
},
logs: {
icon: 'i-lucide-scroll-text',
title: t('settings.navLogs'),
subtitle: t('settings.pageSubtitleLogs')
}
}
return headers[activeTab.value]
})
const showSaveBar = computed(() =>
isAdmin.value && ['basic', 'domains', 'access'].includes(activeTab.value)
)
const pageSubtitle = computed(() => {
if (activeTab.value === 'basic') {
return t('settings.pageSubtitleBasic')
}
return t('settings.pageSubtitle')
})
const checkingRelease = ref(false)
const { resetToDefaults: resetUploadPreferences } = useUploadPreferences()
const { load: reloadUserSettings } = useUserAutoDeleteSettings()
const domainSeparationDocUrl = computed(() =>
locale.value === 'en'
@@ -115,6 +163,15 @@ const disableDomainSeparationOpen = ref(false)
const pendingDomainSeparationDisable = ref(false)
const domainSeparationSaveConfirmOpen = ref(false)
const uploadMaxFileSizeMbDraft = ref(10)
const allowedMimeTypesDraft = ref<MimeType[]>([])
const uploadRateIpMaxDraft = ref(60)
const uploadRateTokenMaxDraft = ref(120)
const uploadRateWindowMinutesDraft = ref(15)
const loginRateMaxDraft = ref(10)
const loginRateWindowMinutesDraft = ref(15)
const preserveOriginalUploadDraft = ref(false)
interface ReleaseCheckResponse {
currentVersion: string
latestVersion: string | null
@@ -124,6 +181,10 @@ interface ReleaseCheckResponse {
const releaseCheck = ref<ReleaseCheckResponse | null>(null)
function mimeListsEqual(left: readonly string[], right: readonly string[]): boolean {
return left.slice().sort().join(',') === right.slice().sort().join(',')
}
const hasServerChanges = computed(() => {
if (!settings.value) return false
return refererDraft.value !== settings.value.allowedRefererHosts
@@ -138,6 +199,14 @@ const hasServerChanges = computed(() => {
|| turnstileSecretKeyDraft.value !== settings.value.turnstileSecretKey
|| capApiEndpointDraft.value !== settings.value.capApiEndpoint
|| capSecretDraft.value !== settings.value.capSecret
|| uploadMaxFileSizeMbDraft.value !== settings.value.uploadMaxFileSizeMb
|| !mimeListsEqual(allowedMimeTypesDraft.value, settings.value.allowedMimeTypes)
|| uploadRateIpMaxDraft.value !== settings.value.uploadRateIpMax
|| uploadRateTokenMaxDraft.value !== settings.value.uploadRateTokenMax
|| uploadRateWindowMinutesDraft.value !== settings.value.uploadRateWindowMinutes
|| loginRateMaxDraft.value !== settings.value.loginRateMax
|| loginRateWindowMinutesDraft.value !== settings.value.loginRateWindowMinutes
|| preserveOriginalUploadDraft.value !== settings.value.preserveOriginalUpload
})
const domainSeparationWouldActivate = computed(() =>
@@ -193,6 +262,14 @@ function applySettings(data: SettingsResponse) {
capApiEndpointDraft.value = data.capApiEndpoint
capSecretDraft.value = data.capSecret
domainSeparationDraft.value = data.domainSeparation
uploadMaxFileSizeMbDraft.value = data.uploadMaxFileSizeMb
allowedMimeTypesDraft.value = [...data.allowedMimeTypes]
uploadRateIpMaxDraft.value = data.uploadRateIpMax
uploadRateTokenMaxDraft.value = data.uploadRateTokenMax
uploadRateWindowMinutesDraft.value = data.uploadRateWindowMinutes
loginRateMaxDraft.value = data.loginRateMax
loginRateWindowMinutesDraft.value = data.loginRateWindowMinutes
preserveOriginalUploadDraft.value = data.preserveOriginalUpload
}
async function patchSettings(body: Record<string, unknown>) {
@@ -268,6 +345,11 @@ async function performSaveServerSettings() {
savingServer.value = true
try {
if (allowedMimeTypesDraft.value.length === 0) {
toast.add({ title: t('settings.allowedMimeTypesHint'), color: 'error' })
return
}
await patchSettings({
allowedRefererHosts: refererDraft.value,
domainSeparation: domainSeparationDraft.value,
@@ -280,7 +362,15 @@ async function performSaveServerSettings() {
turnstileSiteKey: turnstileSiteKeyDraft.value,
turnstileSecretKey: turnstileSecretKeyDraft.value,
capApiEndpoint: capApiEndpointDraft.value,
capSecret: capSecretDraft.value
capSecret: capSecretDraft.value,
uploadMaxFileSizeMb: uploadMaxFileSizeMbDraft.value,
allowedMimeTypes: allowedMimeTypesDraft.value,
uploadRateIpMax: uploadRateIpMaxDraft.value,
uploadRateTokenMax: uploadRateTokenMaxDraft.value,
uploadRateWindowMinutes: uploadRateWindowMinutesDraft.value,
loginRateMax: loginRateMaxDraft.value,
loginRateWindowMinutes: loginRateWindowMinutesDraft.value,
preserveOriginalUpload: preserveOriginalUploadDraft.value
})
toast.add({ title: t('settings.saved'), color: 'success' })
} catch (error: unknown) {
@@ -339,21 +429,33 @@ async function checkLatestRelease(options: { notify?: boolean, refresh?: boolean
}
const loginVerificationOptions = computed(() => [
{ value: 'slider' as const, label: t('settings.loginVerificationSlider') },
{ value: 'turnstile' as const, label: t('settings.loginVerificationTurnstile') },
{ value: 'cap' as const, label: t('settings.loginVerificationCap') }
{
value: 'slider' as const,
label: t('settings.loginVerificationSlider'),
description: t('settings.loginVerificationSliderHint')
},
{
value: 'turnstile' as const,
label: t('settings.loginVerificationTurnstile'),
description: t('settings.loginVerificationTurnstileHint')
},
{
value: 'cap' as const,
label: t('settings.loginVerificationCap'),
description: t('settings.loginVerificationCapHint')
}
])
const loginVerificationHint = computed(() => {
switch (loginVerificationMethodDraft.value) {
case 'turnstile':
return t('settings.loginVerificationTurnstileHint')
case 'cap':
return t('settings.loginVerificationCapHint')
default:
return t('settings.loginVerificationSliderHint')
function restoreDefaults() {
if (activeTab.value === 'basic') {
resetUploadPreferences()
void reloadUserSettings()
}
})
if (settings.value) {
applySettings(settings.value)
}
toast.add({ title: t('settings.restoredDefaults'), color: 'success' })
}
async function loadPage() {
if (isAdmin.value) {
@@ -427,23 +529,22 @@ watch(isAdmin, () => {
<SettingsSidebar
v-model="activeTab"
:items="sidebarItems"
:title="t('settings.pageTitle')"
:subtitle="pageSubtitle"
/>
<div class="flex min-w-0 flex-1 flex-col bg-default">
<div
class="flex-1"
:class="activeTab === 'logs' ? '' : 'p-4 sm:p-5'"
>
<div class="flex-1 p-5 text-sm sm:p-6">
<SettingsPageHeader
v-if="activeTab !== 'logs'"
:icon="tabPageHeader.icon"
:title="tabPageHeader.title"
:subtitle="tabPageHeader.subtitle"
/>
<div
v-if="activeTab === 'basic' && isAdmin"
>
<SettingsPanel v-if="settings">
<SettingsSection
:title="t('settings.featureToggles')"
:hint="t('settings.featureTogglesHint')"
>
<SettingsSection :title="t('settings.featureToggles')">
<SettingsGroup>
<SettingsToggleRow
v-model="allowRegistrationDraft"
@@ -453,33 +554,54 @@ watch(isAdmin, () => {
</SettingsGroup>
</SettingsSection>
<SettingsUserPreferencesFields />
<SettingsSection
:title="t('preferences.title')"
:hint="t('settings.uploadLimitsHint')"
>
<SettingsGroup>
<SettingsUploadPolicyFields
v-model:upload-max-file-size-mb="uploadMaxFileSizeMbDraft"
v-model:allowed-mime-types="allowedMimeTypesDraft"
v-model:upload-rate-ip-max="uploadRateIpMaxDraft"
v-model:upload-rate-token-max="uploadRateTokenMaxDraft"
v-model:upload-rate-window-minutes="uploadRateWindowMinutesDraft"
part="upload-preference"
:upload-max-file-size-mb-source="settings.uploadMaxFileSizeMbSource"
:allowed-mime-types-source="settings.allowedMimeTypesSource"
:upload-rate-ip-max-source="settings.uploadRateIpMaxSource"
:upload-rate-token-max-source="settings.uploadRateTokenMaxSource"
:upload-rate-window-minutes-source="settings.uploadRateWindowMinutesSource"
:mime-type-options="settings.mimeTypeOptions"
/>
<SettingsUserPreferencesFields part="upload-preference" />
</SettingsGroup>
</SettingsSection>
<SettingsSection
:title="t('settings.systemInfo')"
:hint="t('settings.systemInfoHint')"
:title="t('preferences.processing')"
:hint="t('settings.imageProcessingHint')"
>
<template
v-if="isAdmin"
#action
>
<UButton
:label="t('settings.checkUpdate')"
icon="i-lucide-refresh-cw"
variant="outline"
color="neutral"
size="sm"
class="shrink-0"
:loading="checkingRelease"
@click="checkLatestRelease({ notify: true, refresh: true })"
<SettingsGroup>
<SettingsUploadPolicyFields
v-model:preserve-original-upload="preserveOriginalUploadDraft"
part="image-processing"
:preserve-original-upload-source="settings.preserveOriginalUploadSource"
/>
</template>
<SettingsSystemInfo
:app-version="settings.appVersion"
:update-available="!!releaseCheck?.updateAvailable"
:latest-version="releaseCheck?.latestVersion ?? null"
:release-url="releaseCheck?.releaseUrl ?? null"
/>
<SettingsUserPreferencesFields part="image-processing" />
</SettingsGroup>
</SettingsSection>
<SettingsSection :title="t('settings.systemInfo')">
<SettingsGroup>
<SettingsSystemInfo
:app-version="settings.appVersion"
:update-available="!!releaseCheck?.updateAvailable"
:latest-version="releaseCheck?.latestVersion ?? null"
:release-url="releaseCheck?.releaseUrl ?? null"
:checking="checkingRelease"
@check-update="checkLatestRelease({ notify: true, refresh: true })"
/>
</SettingsGroup>
</SettingsSection>
</SettingsPanel>
<div
@@ -498,50 +620,60 @@ watch(isAdmin, () => {
>
<SettingsPanel v-if="settings">
<SettingsSection :title="t('settings.domainSettings')">
<p
v-if="settings.runtime.currentOrigin"
class="mb-3 pl-3 text-xs text-primary"
>
{{ t('settings.runtimeDetected', { url: settings.runtime.currentOrigin }) }}
</p>
<SettingsGroup>
<div class="divide-y divide-default">
<p
v-if="settings.runtime.currentOrigin"
class="py-4 text-xs text-primary"
>
<span class="rounded-lg bg-primary/5 px-3 py-2 inline-block">
{{ t('settings.runtimeDetected', { url: settings.runtime.currentOrigin }) }}
</span>
</p>
<SettingsToggleRow
:model-value="domainSeparationDraft"
:title="t('setup.domainSeparation')"
:hint="t('setup.domainSeparationHint')"
@update:model-value="onDomainSeparationDraftChange"
/>
</SettingsGroup>
<div
v-if="domainSeparationDraft"
class="py-4"
>
<div class="flex flex-col gap-3 rounded-xl border border-warning/30 bg-warning/5 px-4 py-3 sm:flex-row sm:items-start">
<UIcon
name="i-lucide-triangle-alert"
class="mt-0.5 size-4 shrink-0 text-warning"
/>
<div class="min-w-0 flex-1">
<p class="text-sm font-medium text-warning">
{{ t('settings.domainSeparationProxyTitle') }}
</p>
<p class="mt-1 text-xs leading-relaxed text-warning/90">
{{ t('settings.domainSeparationProxyBody') }}
</p>
</div>
<a
:href="domainSeparationDocUrl"
target="_blank"
rel="noopener noreferrer"
class="shrink-0 text-xs text-primary hover:underline sm:pt-0.5"
>
{{ t('setup.domainSeparationProxyExample') }} →
</a>
</div>
<UAlert
v-if="settings.runtime.hostRole === 'unknown'"
color="warning"
variant="subtle"
icon="i-lucide-triangle-alert"
:title="t('settings.hostRoleUnknown')"
class="mt-4"
/>
</div>
</div>
</SettingsSection>
<p
v-if="domainSeparationDraft"
class="rounded-xl border border-warning/25 bg-warning/5 px-4 py-3 text-xs leading-relaxed text-warning"
>
{{ t('setup.domainSeparationProxyHint') }}
<a
:href="domainSeparationDocUrl"
target="_blank"
rel="noopener noreferrer"
class="text-primary hover:underline"
>
{{ t('setup.domainSeparationProxyExample') }}
</a>
</p>
<UAlert
v-if="domainSeparationDraft && settings.runtime.hostRole === 'unknown'"
color="warning"
variant="subtle"
icon="i-lucide-triangle-alert"
:title="t('settings.hostRoleUnknown')"
class="mb-4"
/>
<SettingsSection
:title="t('settings.pathAndLink')"
:hint="t('settings.pathAndLinkHint')"
>
<SettingsSection :title="t('settings.pathAndLink')">
<SettingsGroup>
<SettingsToggleRow
:model-value="hideFolderInUrlDraft"
@@ -590,33 +722,34 @@ watch(isAdmin, () => {
</SettingsGroup>
</SettingsSection>
<SettingsSection :title="t('settings.imageBaseUrl')">
<SettingsSection :title="t('settings.imageDomainSection')">
<div
v-if="domainSeparationDraft"
class="grid gap-4 sm:grid-cols-2"
class="grid gap-4 sm:grid-cols-2 sm:divide-x sm:divide-default"
>
<SettingsGroup>
<div class="space-y-3 px-4 py-4 sm:px-5">
<div class="space-y-3 py-4 sm:pr-4">
<div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-highlighted">
{{ t('settings.siteBaseUrl') }}
</p>
<UBadge
:color="sourceBadge(settings.siteBaseUrlSource).color"
color="success"
variant="subtle"
size="xs"
>
{{ sourceBadge(settings.siteBaseUrlSource).label }}
{{ t('settings.badgeEnabled') }}
</UBadge>
</div>
<p class="text-xs leading-relaxed text-muted">
{{ t('settings.siteBaseUrlHint') }}
{{ t('settings.siteBaseUrlRoleHint') }}
</p>
<div class="flex gap-2">
<UInput
v-model="siteBaseUrlDraft"
size="sm"
:placeholder="t('settings.siteBaseUrlPlaceholder')"
class="min-w-0 flex-1 font-mono text-sm"
class="min-w-0 flex-1 font-mono"
/>
<UButton
v-if="settings.runtime.currentOrigin"
@@ -630,7 +763,7 @@ watch(isAdmin, () => {
</div>
<p
v-if="settings.effectiveSiteBaseUrl"
class="truncate text-xs text-muted"
class="truncate rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted"
:title="settings.effectiveSiteBaseUrl"
>
{{ t('settings.siteBaseUrlActive', { url: settings.effectiveSiteBaseUrl }) }}
@@ -639,30 +772,31 @@ watch(isAdmin, () => {
</SettingsGroup>
<SettingsGroup>
<div class="space-y-3 px-4 py-4 sm:px-5">
<div class="space-y-3 py-4 sm:pl-4">
<div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-highlighted">
{{ t('settings.imageBaseUrl') }}
</p>
<UBadge
:color="sourceBadge(settings.imageBaseUrlSource).color"
color="success"
variant="subtle"
size="xs"
>
{{ sourceBadge(settings.imageBaseUrlSource).label }}
{{ t('settings.badgeEnabled') }}
</UBadge>
</div>
<p class="text-xs leading-relaxed text-muted">
{{ t('settings.imageBaseUrlHint') }}
{{ t('settings.imageBaseUrlRoleHint') }}
</p>
<UInput
v-model="imageBaseUrlDraft"
size="sm"
:placeholder="t('settings.imageBaseUrlPlaceholder')"
class="w-full font-mono text-sm"
class="w-full font-mono"
/>
<p
v-if="settings.effectiveImageBaseUrl"
class="truncate text-xs text-muted"
class="truncate rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted"
:title="settings.effectiveImageBaseUrl"
>
{{ t('settings.imageBaseUrlActive', { url: settings.effectiveImageBaseUrl }) }}
@@ -672,7 +806,7 @@ watch(isAdmin, () => {
</div>
<SettingsGroup v-else>
<div class="space-y-3 px-4 py-4 sm:px-5">
<div class="space-y-3 py-4">
<div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-highlighted">
{{ t('settings.imageBaseUrl') }}
@@ -698,12 +832,13 @@ watch(isAdmin, () => {
</p>
<UInput
v-model="imageBaseUrlDraft"
size="sm"
:placeholder="t('settings.imageBaseUrlPlaceholder')"
class="w-full font-mono text-sm"
class="w-full font-mono"
/>
<p
v-if="settings.effectiveImageBaseUrl"
class="truncate text-xs text-muted"
class="truncate rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted"
:title="settings.effectiveImageBaseUrl"
>
{{ t('settings.imageBaseUrlActive', { url: settings.effectiveImageBaseUrl }) }}
@@ -728,98 +863,89 @@ watch(isAdmin, () => {
class="settings-referer-section"
>
<SettingsPanel v-if="settings">
<div class="flex items-start gap-3">
<div class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10">
<UIcon
name="i-lucide-shield"
class="size-4 text-primary"
/>
</div>
<div class="min-w-0 flex-1">
<div class="flex flex-wrap items-center gap-2">
<h2 class="text-sm font-semibold text-highlighted">
{{ t('settings.accessControl') }}
</h2>
<UBadge
:color="refererDraft.trim() ? 'success' : 'neutral'"
variant="subtle"
size="xs"
>
{{ refererDraft.trim() ? t('settings.refererEnabled') : t('settings.refererUnrestricted') }}
</UBadge>
</div>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('settings.refererHint') }}
</p>
</div>
</div>
<SettingsPlainSection
:title="t('settings.refererProtection')"
:hint="t('settings.refererHint')"
>
<template #badge>
<UBadge
:color="refererDraft.trim() ? 'success' : 'neutral'"
variant="subtle"
size="xs"
>
{{ refererDraft.trim() ? t('settings.refererEnabled') : t('settings.refererUnrestricted') }}
</UBadge>
</template>
<div class="mt-5 grid gap-5 lg:grid-cols-[minmax(0,1fr)_12rem] xl:grid-cols-[minmax(0,1fr)_14rem]">
<div class="min-w-0 space-y-2">
<label class="text-sm font-medium text-highlighted">
{{ t('settings.refererDomainsLabel') }}
</label>
<UTextarea
v-model="refererDraft"
:placeholder="t('settings.refererPlaceholder')"
:rows="7"
:autoresize="false"
class="settings-referer-field w-full font-mono text-sm"
/>
<div class="flex gap-2 rounded-lg border border-info/20 bg-info/5 px-3 py-2.5 text-xs leading-relaxed text-muted">
<UIcon
name="i-lucide-info"
class="mt-0.5 size-3.5 shrink-0 text-info"
<div class="grid gap-5 lg:grid-cols-[minmax(0,1fr)_12rem] xl:grid-cols-[minmax(0,1fr)_14rem]">
<div class="min-w-0 space-y-3">
<label class="block text-sm font-medium text-highlighted">
{{ t('settings.refererDomainsLabel') }}
</label>
<UTextarea
v-model="refererDraft"
size="sm"
:placeholder="t('settings.refererPlaceholder')"
:rows="7"
:autoresize="false"
class="settings-referer-field w-full font-mono"
/>
<span>{{ t('settings.refererTip') }}</span>
<div class="flex gap-2 rounded-lg border border-info/20 bg-info/5 px-3 py-2.5 text-xs leading-relaxed text-muted">
<UIcon
name="i-lucide-info"
class="mt-0.5 size-3.5 shrink-0 text-info"
/>
<span>{{ t('settings.refererTip') }}</span>
</div>
</div>
</div>
<div class="space-y-3 border-l border-default pl-4">
<div>
<p class="text-xs font-medium text-highlighted">
{{ t('settings.refererExamplesTitle') }}
</p>
<p class="mt-2 font-mono text-xs text-muted">
{{ t('settings.refererExamplesSample') }}
</p>
</div>
<div>
<p class="text-xs font-medium text-highlighted">
{{ t('settings.refererScenarioTitle') }}
</p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('settings.refererScenarioDesc') }}
</p>
<div class="space-y-4 border-l border-default pl-4">
<div>
<p class="text-sm font-medium text-highlighted">
{{ t('settings.refererExamplesTitle') }}
</p>
<p class="mt-2 font-mono text-xs text-muted">
{{ t('settings.refererExamplesSample') }}
</p>
</div>
<div>
<p class="text-sm font-medium text-highlighted">
{{ t('settings.refererScenarioTitle') }}
</p>
<ul class="mt-2 list-disc space-y-1 pl-4 text-xs leading-relaxed text-muted">
<li>{{ t('settings.refererScenario1') }}</li>
<li>{{ t('settings.refererScenario2') }}</li>
<li>{{ t('settings.refererScenario3') }}</li>
<li>{{ t('settings.refererScenario4') }}</li>
</ul>
</div>
</div>
</div>
</div>
</SettingsPlainSection>
<SettingsSection
:title="t('settings.loginVerification')"
:hint="t('settings.loginVerificationHint')"
>
<SettingsGroup>
<div class="space-y-4 px-4 py-4 sm:px-5">
<URadioGroup
v-model="loginVerificationMethodDraft"
:items="loginVerificationOptions"
/>
<p class="text-xs leading-relaxed text-muted">
{{ loginVerificationHint }}
</p>
<div
v-if="loginVerificationMethodDraft === 'turnstile'"
class="space-y-3 rounded-xl border border-default bg-muted/20 p-4"
>
<SettingsRadioGroup
v-model="loginVerificationMethodDraft"
:items="loginVerificationOptions"
/>
<div
v-if="loginVerificationMethodDraft === 'turnstile'"
class="py-4"
>
<div class="space-y-3 rounded-xl border border-default bg-muted/20 p-4">
<div class="space-y-2">
<label class="text-sm font-medium text-highlighted">
{{ t('settings.turnstileSiteKey') }}
</label>
<UInput
v-model="turnstileSiteKeyDraft"
size="sm"
:placeholder="t('settings.turnstileSiteKeyPlaceholder')"
class="w-full font-mono text-sm"
class="w-full font-mono"
/>
</div>
<div class="space-y-2">
@@ -829,23 +955,27 @@ watch(isAdmin, () => {
<UInput
v-model="turnstileSecretKeyDraft"
type="password"
size="sm"
:placeholder="t('settings.turnstileSecretKeyPlaceholder')"
class="w-full font-mono text-sm"
class="w-full font-mono"
/>
</div>
</div>
<div
v-else-if="loginVerificationMethodDraft === 'cap'"
class="space-y-3 rounded-xl border border-default bg-muted/20 p-4"
>
</div>
<div
v-else-if="loginVerificationMethodDraft === 'cap'"
class="py-4"
>
<div class="space-y-3 rounded-xl border border-default bg-muted/20 p-4">
<div class="space-y-2">
<label class="text-sm font-medium text-highlighted">
{{ t('settings.capApiEndpoint') }}
</label>
<UInput
v-model="capApiEndpointDraft"
size="sm"
:placeholder="t('settings.capApiEndpointPlaceholder')"
class="w-full font-mono text-sm"
class="w-full font-mono"
/>
</div>
<div class="space-y-2">
@@ -855,14 +985,30 @@ watch(isAdmin, () => {
<UInput
v-model="capSecretDraft"
type="password"
size="sm"
:placeholder="t('settings.capSecretKeyPlaceholder')"
class="w-full font-mono text-sm"
class="w-full font-mono"
/>
</div>
</div>
</div>
</SettingsGroup>
</SettingsSection>
<SettingsSection
:title="t('settings.rateLimits')"
:hint="t('settings.loginRateLimitsHint')"
>
<SettingsGroup>
<SettingsUploadPolicyFields
v-model:login-rate-max="loginRateMaxDraft"
v-model:login-rate-window-minutes="loginRateWindowMinutesDraft"
part="login-rate"
:login-rate-max-source="settings.loginRateMaxSource"
:login-rate-window-minutes-source="settings.loginRateWindowMinutesSource"
/>
</SettingsGroup>
</SettingsSection>
</SettingsPanel>
<div
v-else
@@ -875,6 +1021,8 @@ watch(isAdmin, () => {
</div>
</div>
<SettingsTagsPanel v-else-if="activeTab === 'tags'" />
<SettingsLogsPanel v-else-if="activeTab === 'logs'" />
</div>
@@ -883,6 +1031,7 @@ watch(isAdmin, () => {
:has-changes="hasServerChanges"
:saving="savingServer"
@save="saveServerSettings"
@restore="restoreDefaults"
/>
</div>
</div>
+175
View File
@@ -29,6 +29,93 @@ const imageBaseUrl = 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 form = new FormData()
form.append('file', restoreFile.value)
const data = await $fetch<{ job: { id: string } }>('/api/setup/restore', {
method: 'POST',
body: form
})
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,
@@ -149,7 +236,28 @@ async function performSubmit() {
</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"
>
@@ -269,6 +377,73 @@ async function performSubmit() {
: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
+91 -3
View File
@@ -21,6 +21,53 @@ const deleteTarget = ref<StorageBackendItem | null>(null)
const deleteConfirmName = ref('')
const deleting = ref(false)
const backupPanelRef = ref<{ applySyncDraft: (draft: { fromBackendId: string, toBackendId: string }) => void } | null>(null)
function onMigrateIn(backend: StorageBackendItem) {
const defaultBackend = storageData.value?.backends.find(item => item.isDefault)
if (!defaultBackend || defaultBackend.id === backend.id) return
backupPanelRef.value?.applySyncDraft({
fromBackendId: defaultBackend.id,
toBackendId: backend.id
})
}
function onMigrateOut(backend: StorageBackendItem) {
const backends = storageData.value?.backends ?? []
if (backend.isDefault) {
const target = backends.find(item => !item.isDefault && item.enabled)
if (!target) return
backupPanelRef.value?.applySyncDraft({
fromBackendId: backend.id,
toBackendId: target.id
})
return
}
const defaultBackend = backends.find(item => item.isDefault)
if (!defaultBackend) return
backupPanelRef.value?.applySyncDraft({
fromBackendId: backend.id,
toBackendId: defaultBackend.id
})
}
function showMigrateIn(backend: StorageBackendItem): boolean {
const backends = storageData.value?.backends ?? []
return !backend.isDefault
&& backend.enabled
&& backends.some(item => item.isDefault)
}
function showMigrateOut(backend: StorageBackendItem): boolean {
const backends = storageData.value?.backends ?? []
if (backend.usage.count === 0) return false
if (backend.isDefault) {
return backends.some(item => !item.isDefault && item.enabled)
}
return backends.some(item => item.isDefault)
}
const defaultBackendName = computed(() => {
const backend = storageData.value?.backends.find(item => item.isDefault)
return backend?.name ?? t('storage.backendLocal')
@@ -46,16 +93,42 @@ const { quotaToBytes } = useFileSize()
function buildPatchBody(payload: StorageFormPayload) {
const quotaBytes = quotaToBytes(payload.quotaValue, payload.quotaUnit)
if (payload.backendType === 'telegram') {
const body: Record<string, unknown> = {
type: 'telegram',
name: payload.name,
quotaBytes,
config: {
chatId: payload.config.chatId,
apiProxyUrl: payload.config.apiProxyUrl
}
}
if (payload.secrets.botToken) {
body.secrets = { botToken: payload.secrets.botToken }
}
return body
}
const body: Record<string, unknown> = {
type: 's3',
name: payload.name,
provider: payload.provider,
servingMode: payload.servingMode,
publicUrl: payload.publicUrl,
quotaBytes,
config: payload.config
config: {
endpoint: payload.config.endpoint,
region: payload.config.region,
bucket: payload.config.bucket,
prefix: payload.config.prefix,
forcePathStyle: payload.config.forcePathStyle
}
}
if (payload.secrets.accessKeyId || payload.secrets.secretAccessKey) {
body.secrets = payload.secrets
body.secrets = {
accessKeyId: payload.secrets.accessKeyId,
secretAccessKey: payload.secrets.secretAccessKey
}
}
return body
}
@@ -81,7 +154,12 @@ async function onFormSubmit(payload: StorageFormPayload) {
}
if (formMode.value === 'create') {
if (!payload.secrets.accessKeyId || !payload.secrets.secretAccessKey) {
if (payload.backendType === 'telegram') {
if (!payload.secrets.botToken || !payload.config.chatId) {
toast.add({ title: t('storage.telegramSecretsRequired'), color: 'warning' })
return
}
} else if (!payload.secrets.accessKeyId || !payload.secrets.secretAccessKey) {
toast.add({ title: t('storage.secretsRequired'), color: 'warning' })
return
}
@@ -297,14 +375,24 @@ watch(isAuthenticated, async (authed) => {
:backend="backend"
:env-override="storageData.envOverride"
:busy="busyId === backend.id"
:show-migrate-in="showMigrateIn(backend)"
:show-migrate-out="showMigrateOut(backend)"
@set-default="setDefault(backend)"
@edit="openEdit(backend)"
@test="testBackend(backend)"
@toggle-enabled="toggleEnabled(backend)"
@delete="confirmDelete(backend)"
@migrate-in="onMigrateIn(backend)"
@migrate-out="onMigrateOut(backend)"
/>
</div>
<StorageBackupPanel
v-if="!storageData.envOverride"
ref="backupPanelRef"
:backends="storageData.backends"
/>
<StorageSupportedBackends />
</template>
</section>
+53
View File
@@ -0,0 +1,53 @@
export type BackupJobType = 'full_export' | 'full_restore' | 'backend_sync'
export type BackupJobStatus = 'pending' | 'running' | 'done' | 'failed'
export interface BackupJobItem {
id: string
type: BackupJobType
status: BackupJobStatus
progress: number
total: number
message: string
payload: Record<string, unknown>
outputPath: string | null
archiveName: string | null
downloadable: boolean
error: string | null
createdAt: string
finishedAt: string | null
}
export interface BackupEstimate {
imageCount: number
imageBytes: number
databaseBytes: number
totalBytes: number
}
export interface BackupPackageItem {
name: string
bytes: number
modifiedAt: string
}
export interface BackupRestorePreview {
imageCount: number
imageBytes: number
newImages: number
conflictingImages: number
formatVersion: number
appVersion: string
createdAt: string
}
export interface BackendSyncPreview {
imageCount: number
imageBytes: number
fromBackendId: string
toBackendId: string
}
export interface SyncDraft {
fromBackendId: string
toBackendId: string
}
+12 -1
View File
@@ -40,10 +40,21 @@ export interface ImageItem {
storage?: {
id: string
name: string
type: 'local' | 's3'
type: 'local' | 's3' | 'telegram'
}
/** 上传来源:网页或 API(来自活动日志) */
uploadSource?: 'web' | 'api'
/** 图片标签 */
tags?: ImageTag[]
}
export interface ImageTag {
id: number
name: string
color: string
imageCount?: number
createdAt?: string
lastUsedAt?: string | null
}
export interface UploadErrorItem {
+5 -2
View File
@@ -1,5 +1,6 @@
export type LogAction = 'upload' | 'delete'
export type LogSource = 'web' | 'api'
export type LogAction = 'upload' | 'delete' | 'login' | 'edit' | 'settings' | 'tags'
export type LogSource = 'web' | 'api' | 'admin'
export type LogStatus = 'success' | 'failure'
export interface ActivityLogStorage {
id: string
@@ -18,6 +19,8 @@ export interface ActivityLogItem {
userId: number | null
username: string | null
storage: ActivityLogStorage | null
ipAddress: string | null
status: LogStatus
createdAt: string
}
+3 -3
View File
@@ -1,5 +1,5 @@
export type SettingsTab = 'basic' | 'domains' | 'access' | 'logs'
export type SettingsTab = 'basic' | 'domains' | 'access' | 'tags' | 'logs'
export const ADMIN_SETTINGS_TABS: SettingsTab[] = ['basic', 'domains', 'access', 'logs']
export const ADMIN_SETTINGS_TABS: SettingsTab[] = ['basic', 'domains', 'access', 'tags', 'logs']
export const USER_SETTINGS_TABS: SettingsTab[] = ['logs']
export const USER_SETTINGS_TABS: SettingsTab[] = ['tags', 'logs']
+4 -1
View File
@@ -11,17 +11,20 @@ export interface StorageCapacity {
export interface StorageBackendItem {
id: string
name: string
type: 'local' | 's3'
type: 'local' | 's3' | 'telegram'
config: {
endpoint?: string
region?: string
bucket?: string
prefix?: string
forcePathStyle?: boolean
chatId?: string
apiProxyUrl?: string
}
secretsMasked: {
accessKeyId?: string
secretAccessKey?: string
botToken?: string
}
servingMode: ServingMode
publicUrl: string
+4
View File
@@ -22,3 +22,7 @@ export function formatImageDimensions(width: number | null, height: number | nul
if (!width || !height) return null
return `${width} × ${height} px`
}
export function buildImageBbcode(url: string): string {
return `[img]${url}[/img]`
}
+136
View File
@@ -0,0 +1,136 @@
export const TAG_COLOR_PRESETS = [
'#22c55e',
'#3b82f6',
'#f59e0b',
'#ef4444',
'#8b5cf6',
'#06b6d4',
'#ec4899',
'#84cc16',
'#f97316',
'#6366f1',
'#14b8a6',
'#64748b'
] as const
export const TAG_COLOR_CANDIDATE_COUNT = 8
export const TAG_COLOR_EDIT_CANDIDATE_COUNT = 3
export function defaultTagColor(tagId: number): string {
return TAG_COLOR_PRESETS[tagId % TAG_COLOR_PRESETS.length]!
}
function normalizeHexColor(color: string | null | undefined): string | null {
if (!color) return null
const trimmed = color.trim().toLowerCase()
if (!trimmed) return null
const withHash = trimmed.startsWith('#') ? trimmed : `#${trimmed}`
return /^#[0-9a-f]{6}$/.test(withHash) ? withHash : null
}
/** 解析标签展示色,无效时回退到默认色 */
export function resolveTagHexColor(
color: string | null | undefined,
fallback?: string
): string {
return normalizeHexColor(color) ?? fallback ?? TAG_COLOR_PRESETS[0]!
}
export function usedPresetColorSet(usedColors: (string | null | undefined)[]): Set<string> {
const used = new Set<string>()
for (const color of usedColors) {
const normalized = normalizeHexColor(color)
if (!normalized) continue
if (TAG_COLOR_PRESETS.some(preset => preset.toLowerCase() === normalized)) {
used.add(normalized)
}
}
return used
}
function shuffleColors<T extends string>(colors: readonly T[]): T[] {
const items = [...colors]
for (let index = items.length - 1; index > 0; index--) {
const swapIndex = Math.floor(Math.random() * (index + 1))
const current = items[index]!
items[index] = items[swapIndex]!
items[swapIndex] = current
}
return items
}
/**
* 新增标签时的备选色:优先从未占用预设中随机取满 count 个;
* 不足时用其余预设随机补足(保证始终有 7~8 个可选项)。
*/
export function pickTagColorCandidates(
usedColors: (string | null | undefined)[],
count = TAG_COLOR_CANDIDATE_COUNT
): string[] {
const used = usedPresetColorSet(usedColors)
const unused = shuffleColors(TAG_COLOR_PRESETS.filter(preset => !used.has(preset.toLowerCase())))
const usedPresets = shuffleColors(TAG_COLOR_PRESETS.filter(preset => used.has(preset.toLowerCase())))
const candidates: string[] = []
for (const color of unused) {
if (candidates.length >= count) break
candidates.push(color.toLowerCase())
}
for (const color of usedPresets) {
if (candidates.length >= count) break
candidates.push(color.toLowerCase())
}
return candidates.length > 0 ? candidates : shuffleColors(TAG_COLOR_PRESETS).slice(0, count).map(c => c.toLowerCase())
}
/** 从备选色中优先选未占用色作为默认;若均已占用则随机选一 */
export function pickDefaultTagColorFromCandidates(
candidates: string[],
usedColors: (string | null | undefined)[]
): string {
if (!candidates.length) {
return pickRandomUnusedTagColor(usedColors)
}
const used = usedPresetColorSet(usedColors)
const unused = candidates.filter(color => !used.has(color.toLowerCase()))
const pool = unused.length > 0 ? unused : candidates
return pool[Math.floor(Math.random() * pool.length)]!.toLowerCase()
}
/** 从未被占用的预设色中随机取一色;若预设色均已占用则退回全量随机 */
export function pickRandomUnusedTagColor(usedColors: (string | null | undefined)[]): string {
const used = usedPresetColorSet(usedColors)
const available = TAG_COLOR_PRESETS.filter(preset => !used.has(preset.toLowerCase()))
const pool = available.length > 0 ? available : TAG_COLOR_PRESETS
return pool[Math.floor(Math.random() * pool.length)]!.toLowerCase()
}
/** 颜色选择器展示的预设:排除已被其他标签占用的颜色,但保留当前选中色 */
export function visibleTagColorPresets(
usedColors: (string | null | undefined)[],
currentColor?: string | null
): readonly string[] {
const used = usedPresetColorSet(usedColors)
const current = normalizeHexColor(currentColor)
return TAG_COLOR_PRESETS.filter((preset) => {
const lower = preset.toLowerCase()
return !used.has(lower) || lower === current
})
}
export function tagPillStyle(color: string | null | undefined, selected = false, fallback?: string) {
const hex = resolveTagHexColor(color, fallback)
if (selected) {
return {
backgroundColor: hex,
borderColor: hex,
color: '#ffffff'
}
}
return {
borderColor: `${hex}55`,
backgroundColor: `${hex}18`,
color: hex
}
}
+1 -1
View File
@@ -10,7 +10,7 @@ services:
- "6892:6892"
# 首次访问 Web 引导创建管理员,无需预先配置环境变量
# 可选:environment 中设置 API_UPLOAD_TOKEN、ALLOWED_REFERER_HOSTS 等
# 运维:docker exec pichost reset-password | migrate [--apply] | slider | clear-domains [--site]
# 运维:docker exec pichost reset-password | slider | clear-domains | backup-export | backup-restore | storage-sync
volumes:
# 冒号左边改成 NAS 上的实际存图目录(飞牛示例:/vol1/1000/pichost-data)
- ./data:/data
+12 -4
View File
@@ -5,10 +5,6 @@ if [ "$1" = "reset-password" ]; then
exec node /app/server/cli/reset-password.mjs "${@:2}"
fi
if [ "$1" = "migrate" ]; then
exec node /app/server/cli/migrate-to-single-images.mjs "${@:2}"
fi
if [ "$1" = "slider" ]; then
exec node /app/server/cli/slider.mjs "${@:2}"
fi
@@ -17,4 +13,16 @@ if [ "$1" = "clear-domains" ]; then
exec node /app/server/cli/clear-domains.mjs "${@:2}"
fi
if [ "$1" = "backup-export" ]; then
exec node /app/server/cli/backup-export.mjs "${@:2}"
fi
if [ "$1" = "backup-restore" ]; then
exec node /app/server/cli/backup-restore.mjs "${@:2}"
fi
if [ "$1" = "storage-sync" ]; then
exec node /app/server/cli/storage-sync.mjs "${@:2}"
fi
exec node /app/.output/server/index.mjs "$@"
-2
View File
@@ -34,7 +34,6 @@ const zhSidebar = [
text: '升级',
items: [
{ text: '更新日志', link: '/guide/changelog' },
{ text: 'v1.2 迁移', link: '/guide/migration' },
{ text: '常见问题', link: '/guide/faq' }
]
}
@@ -71,7 +70,6 @@ const enSidebar = [
text: 'Upgrade',
items: [
{ text: 'Changelog', link: '/en/guide/changelog' },
{ text: 'v1.2 migration', link: '/en/guide/migration' },
{ text: 'FAQ', link: '/en/guide/faq' }
]
}
+33 -5
View File
@@ -2,6 +2,8 @@
PicHost exposes REST endpoints and a Twikoo-compatible upload. After sign-in, open **API** in the nav: a sidebar lists endpoints and token controls, the center shows parameters and copyable cURL, and the right panel supports **live debugging**.
![API docs and debugger](/screenshots/api.png)
## Authentication
All REST calls use:
@@ -10,10 +12,10 @@ All REST calls use:
Auth-Token: YOUR_TOKEN
```
| Token type | How to obtain | Notes |
| ---------- | ------------- | ----- |
| **Global** | Admin **API** page or `API_UPLOAD_TOKEN` env | Env wins and blocks UI regenerate |
| **Personal** | Each user’s **API** page | Uploads belong to that user |
| Token | How to obtain | Notes |
| ----- | ------------- | ----- |
| **API token** | **API** page after sign-in (one per account, auto-created) | `Auth-Token` header; uploads and tagNames belong to that account |
| **Legacy site token** | `API_UPLOAD_TOKEN` env or old admin setting | Still accepted; uploads belong to the **first admin**. Twikoo form `token` also accepts each user’s API token |
Form uploads may use field `token` (Twikoo protocol).
@@ -28,9 +30,12 @@ Upload one or more images via `image`; also accepts `file`, `files`. Stored unde
```bash
curl -X POST "https://admin.example.com/api/images/upload" \
-H "Auth-Token: YOUR_TOKEN" \
-F "image=@./demo.png"
-F "image=@./demo.png" \
-F 'tagNames=["blog","screenshot"]'
```
Optional form field `tagNames`: JSON array or comma-separated names. Tags apply to the user bound to the token (**global token cannot tag**). Tags do **not** change storage paths under `images/`.
### 2. List images
`GET /api/images`
@@ -42,6 +47,8 @@ curl "https://admin.example.com/api/images?limit=20&page=1" \
-H "Auth-Token: YOUR_TOKEN"
```
Optional query: `tagIds` (comma-separated, OR by default), `tagMode=and`, `untagged=1`. Each item includes a `tags` array.
### 3. Search images
`GET /api/images/search`
@@ -77,6 +84,27 @@ curl -X POST "https://admin.example.com/api/images/batch-delete" \
-d '{"keys":["images/2026/08/a.webp","images/2026/08/b.webp"]}'
```
### 6. Tags
| Method | Path | Description |
| ------ | ---- | ----------- |
| `GET` | `/api/tags` | List current user’s tags |
| `POST` | `/api/tags` | Create `{ "name": "work", "color": "#22c55e" }` |
| `PATCH` | `/api/tags/:id` | Rename or recolor |
| `DELETE` | `/api/tags/:id` | Delete tag (images remain) |
| `POST` | `/api/tags/merge` | Merge tags into a target |
### 7. Image tags
| Method | Path | Description |
| ------ | ---- | ----------- |
| `POST` | `/api/images/tags` | Add tags to an image |
| `PATCH` | `/api/images/tags` | Replace tag set |
| `DELETE` | `/api/images/tags` | Remove one tag |
| `POST` | `/api/images/batch-tags` | Batch add/remove |
`GET /api/stats` accepts the same tag filter query params as the list API.
## Errors
REST responses are JSON with `code` and `message` (`UNAUTHORIZED`, `FORBIDDEN`, `INVALID_REQUEST`, etc.). Twikoo uses EasyImage-compatible JSON.
+46 -4
View File
@@ -4,6 +4,51 @@ Version history and notable changes. The full log is also in the repo root [CHAN
---
## [1.4.3] — 2026-10-09
### Added
- **Telegram storage backend**: store images in a channel or group; public URLs stay on PicHost; optional API proxy
## [1.4.2] — 2026-09-23
### Fixed
- Gallery batch tagging and upload token auth (incl. legacy `API_UPLOAD_TOKEN`)
### Improved
- Single API token per account; upload `tagNames` only; tag management sort/mobile layout; API doc table layout
## [1.4.1] — 2026-09-16
### Added
- **Upload policy (Settings → Basic)**: max size, allowed formats, rate limits, preserve originals; env override
- **Upload API**: optional `tagNames` for tagging by name (create or reuse)
### Improved
- Configurable login rate limits; settings layout updates
## [1.4.0] — 2026-09-09
### Added
- **Tags**: per-user colored tags; Settings management; batch tagging on upload/gallery; OR / AND gallery filters
- **Activity log**: login, delete, settings, tag operations; date and user filters
- **API**: tag and tagging endpoints; upload `tagIds`; list/stats tag filters
### Docs
- Screenshots and README updated for v1.4 UI
## [1.3.0] — 2026-09-07
### Added
- **Site backup / restore / cross-backend sync** with job center; CLI `backup-export`, `backup-restore`, `storage-sync`
## [1.2.8] — 2026-09-04
### Improved
@@ -159,15 +204,12 @@ Version history and notable changes. The full log is also in the repo root [CHAN
### Changed
- All images under `data/images/`; legacy `blog/` / `twikoo/` need migration
- All images under `data/images/`; parallel top-level folders beside `images` are no longer used
### Added
- CLI: `docker exec pichost migrate` / `migrate --apply`
- Startup index sync (disk scan, legacy key normalization, orphan cleanup)
See [v1.2 migration](./migration.md).
---
## [1.1.x] summary
+3 -1
View File
@@ -1,6 +1,8 @@
# Environment variables
Configure PicHost via environment variables (Docker / `.env`) or the in-app **Settings** page. Admins use **Settings** (`/settings`) with sidebar sections **Basic**, **Domains & paths**, **Access control**, and **Activity log**. Most values prefer **SQLite** when saved; some env vars override or lock UI editing.
Configure PicHost via environment variables (Docker / `.env`) or the in-app **Settings** page. Admins use **Settings** (`/settings`) with sidebar sections **Basic**, **Domains & paths**, **Access control**, **Tag management**, and **Activity log**. Most values prefer **SQLite** when saved; some env vars override or lock UI editing.
![Settings](/screenshots/settings-en.png)
## Priority overview
+10 -10
View File
@@ -61,21 +61,21 @@ Recommended: run PicHost on origin; use **proxied DNS** (and optional **R2** sto
- Always open admin on the **site hostname**, not mixed with `localhost`
- See [Dual-domain separation](./domain-separation.md)
## Undeletable gallery items after v1.2 upgrade?
## Undeletable gallery items?
Likely **orphan index** rows (no file on disk). Startup sync removes them on restart. See [v1.2 migration](./migration.md#step-2-startup-index-sync-automatic).
Likely **orphan index** rows (no file on disk). Startup sync removes them on restart; you can also delete them from the gallery.
## Do I still need `data/blog/` after migration?
## How do I back up or migrate the full site?
After `migrate --apply`, files live under `data/images/blog/`. Remove leftover empty dirs after backup if you like; dirs with non-image files are kept by the CLI.
From v1.3.0, use **Storage → Backup & migration**, or CLI:
## Object storage only — run migrate?
```bash
docker exec pichost backup-export
docker exec pichost backup-restore /data/backups/pichost-xxx.phost.tar.gz
docker exec pichost storage-sync --from local --to s3-xxx --dry-run
```
No. Skip the CLI; startup sync focuses on local `data/images/` scanning.
## Replace old image URLs in posts?
Use `data/mapping.json` from `migrate` preview. Keys are **storage paths**, not full legacy URLs. See [Migration](./migration.md#urls).
Packages include the database and all images but **not** cloud storage secrets — re-enter them on the Storage page after restore. See [Storage → Backup & migration](./storage.md#backup--migration-v130).
## Skip login during development?
+12 -8
View File
@@ -33,9 +33,19 @@ See `docker-compose.yml` in the repository.
## First-time setup
1. Open your instance URL (Docker default `http://<host>:6892`).
2. Complete `/setup` with admin username and password.
2. On `/setup`, choose **Create admin** or **Restore backup**:
- **Create admin** — username, password, optional registration and dual-domain options.
- **Restore backup** — upload a `.phost.tar.gz` full-site package (replaces current data; re-enter cloud storage secrets after restore).
3. (Optional) Configure site URL, image URL, Referer rules — see [Environment variables](./configuration.md) and [Dual-domain separation](./domain-separation.md).
4. Upload from the home page; use the top nav for **Gallery**, **Storage** (admin), **Settings**, and **API**.
4. Upload from the home page via **drag-and-drop, file picker, or Ctrl+V**; copy direct/Markdown/HTML/BBCode links from the results panel and use **batch tagging**. Top nav: **Gallery**, **Storage** (admin), **Settings**, **API**.
![Upload](/screenshots/upload.png)
| Create admin | Restore from backup |
| :----------: | :-----------------: |
| ![Setup](/screenshots/setup.png) | ![Setup restore](/screenshots/setup-restore.png) |
For an already-initialized instance, use [Storage → Backup & migration](./storage.md#backup--migration-v130) instead of `/setup`.
## Sign in
@@ -80,12 +90,6 @@ docker exec pichost clear-domains
Local: `npm run clear-domains`. See [FAQ — Admin 404 after dual-domain setup](./faq.md#admin-404--locked-out-after-dual-domain-setup).
## Upgrading to v1.2.0
If `data/` has legacy top-level folders next to `images` (e.g. `blog/`, `twikoo/`), read the [v1.2 migration guide](./migration.md) first.
Object-storage-only or files already under `data/images/` — pull the new image and restart.
## Next steps
- [Local development](./local-dev.md)
+20 -4
View File
@@ -12,16 +12,32 @@ Welcome to the PicHost user guide. This site is the single source of truth; the
## Screenshots
**main** has no public demo. Below are current product screenshots (v1.2.5+).
**main** has no public demo. Below are current product screenshots (v1.4.0+).
| API | Gallery |
| :-: | :-----: |
| ![API](/screenshots/api.png) | ![Gallery](/screenshots/gallery.png) |
| Upload | Batch tagging |
| :----: | :-----------: |
| ![Upload](/screenshots/upload.png) | ![Batch tagging](/screenshots/tags-batch.png) |
| Upload results (tagged) | API |
| :---------------------: | :-: |
| ![Upload results](/screenshots/upload-tags.jpg) | ![API](/screenshots/api.png) |
| Gallery (grid) | Gallery (list) |
| :------------: | :------------: |
| ![Gallery grid](/screenshots/gallery.png) | ![Gallery list](/screenshots/gallery-list.png) |
| Image detail | Tag management |
| :----------: | :------------: |
| ![Image detail](/screenshots/gallery-detail.png) | ![Tag management](/screenshots/tags.png) |
| Storage | Settings |
| :-----: | :-------: |
| ![Storage](/screenshots/storage.png) | ![Settings](/screenshots/settings-en.png) |
| First-time setup | Restore from backup |
| :--------------: | :-----------------: |
| ![Setup](/screenshots/setup.png) | ![Setup restore](/screenshots/setup-restore.png) |
| Activity log |
| :----------: |
| ![Activity log](/screenshots/logs.png) |
+1 -2
View File
@@ -30,7 +30,6 @@ Open `http://localhost:3000/setup` to create the admin account. Data directory d
| `npm run reset-password` | Reset password (optional username) |
| `npm run slider` | Reset login verification to local slider |
| `npm run clear-domains` | Clear site/image URL settings from DB (recover from dual-domain lockout) |
| `npm run migrate` | Preview legacy dir migration (`-- --apply` to run) |
## Dev-only variables
@@ -53,4 +52,4 @@ npm run docs:build
npm run docs:preview
```
Sources live in `docs-site/`; screenshot sources are in `docs/screenshots/` (including `login.png`), copied to `docs-site/public/screenshots/` before build. Live docs: <https://o96u.github.io/PicHost/>
Sources live in `docs-site/`; screenshot sources are in `docs/screenshots/` (including `upload.png`, `gallery.png`, `tags.png`, `api.png`, `storage.png`, `settings.png`, `logs.png`, `setup.png`, etc.), copied to `docs-site/public/screenshots/` before build. Live docs: <https://o96u.github.io/PicHost/>
-129
View File
@@ -1,129 +0,0 @@
# v1.2.0 local disk migration guide
From v1.2.0, **all local image files** live under `data/images/`; SQLite `keys` also start with `images/`. Legacy top-level folders next to `images` (e.g. `data/blog/`, `data/twikoo/`) are no longer used.
Migration is **two steps**: run the **CLI** to move files on disk, then let **startup sync** align the SQLite index.
---
## Migrating from other image hosts (EasyImage, Lsky, Chevereto, …)
There is **no** dedicated “pull from URLs” or “import via vendor API” tool. Moving from **legacy PicHost** or **another self-hosted** install uses the same **local file** workflow:
1. Locate the **image files** on the old server (copy the tree, not just the database).
2. Place them under PicHost `data/` as a **top-level folder** next to `images` (any name — it becomes `images/{name}/...`).
3. Run `migrate` / `migrate --apply`, then restart PicHost.
| Source | Typical path on old server | After copy into PicHost |
| ------ | -------------------------- | ----------------------- |
| PicHost v1.1.x | `data/blog/`, `data/twikoo/` | Already under `data/` → run `migrate` |
| EasyImage(s) | `i/` or `upload/` | e.g. `data/easyimage/` → `migrate` |
| Lsky | `public/uploads/` etc. | e.g. `data/lsky/` → `migrate` |
| Chevereto etc. | `images/` or `content/` | e.g. `data/chevereto/` → `migrate` |
| Custom | your folder name | `data/your-folder/` → `migrate` |
The CLI scans **every top-level directory under `data/` except `images`**, not only `blog` / `twikoo`.
**Limits:** files only — accounts, tokens, and old public URLs are not imported. `mapping.json` maps old **storage keys**, not full old-site URLs. For S3/R2-only legacy hosts, sync blobs to `data/…` or attach the bucket in PicHost **Storage** settings.
---
## Layout before and after
### Before (typical v1.1.x)
```
/data
├── pichost.db
├── blog/
│ └── 2026/08/TeKJ2fD6cB6j.webp
├── twikoo/
└── images/
```
Index keys might look like `blog/2026/08/TeKJ2fD6cB6j.webp`.
### After (v1.2.0)
```
/data
├── pichost.db
├── mapping.json
└── images/
├── blog/
│ └── 2026/08/TeKJ2fD6cB6j.webp
└── twikoo/
```
Index key: `images/blog/2026/08/TeKJ2fD6cB6j.webp`.
---
## Step 1: CLI file migration
Run **before or after** upgrading the image; backup `data/` first.
```bash
docker exec pichost migrate # preview + mapping.json
docker exec pichost migrate --apply # move files
```
Local: `npm run migrate` / `npm run migrate -- --apply`.
| Item | Behavior |
| ---- | -------- |
| Scan | Every top-level directory under `data/` **except `images`** |
| Target | `data/images/{original-top-dir}/{relative-path}` |
| Extensions | jpg, jpeg, png, webp, gif, svg, ico |
| Sidecar | `.meta.json` next to an image is moved if present |
| Other files | Not moved; parent directory kept if anything remains |
| Mapping | `data/mapping.json` — old key → new key |
Script: `server/cli/migrate-to-single-images.mjs`.
---
## Step 2: Startup index sync (automatic)
Runs on every start (`npm run dev`, Docker). No manual command.
```text
[INFO] 开始同步图片索引:扫描本地磁盘 ...
[INFO] 磁盘扫描完成:...
[INFO] 开始归一化遗留图片路径 ...
[INFO] 开始校验索引与磁盘一致性,清理无文件的孤儿记录
[INFO] 图片索引同步结束
```
| Step | Purpose |
| ---- | ------- |
| Scan `data/images/` | Insert missing index rows for files on disk |
| Normalize legacy keys | `blog/...` → `images/blog/...` when files are in place |
| Purge orphans | Remove index rows with no file on disk |
| Repair Content-Type | Fix `application/octet-stream` entries |
The CLI only **moves files**. Index alignment runs at startup — **restart** after `migrate --apply`.
---
## Recommended upgrade flow
1. Backup `data/`.
2. `docker exec pichost migrate` — review output and `mapping.json`.
3. `docker exec pichost migrate --apply`.
4. Deploy v1.2.0 and restart.
5. Check logs for successful index sync.
6. Use `mapping.json` to update external URLs if needed.
Skip step 1 if you only use object storage or everything is already under `data/images/`.
---
## URLs
| Old key | `blog/TeKJ2fD6cB6j.webp` |
| New key | `images/blog/TeKJ2fD6cB6j.webp` |
With “hide folder” mode, short URLs like `/TeKJ2fD6cB6j.webp` may still resolve by filename. Use `mapping.json` for bulk replacements.
Chinese version: [v1.2 迁移指南](/guide/migration)
+64 -8
View File
@@ -1,6 +1,6 @@
# Storage
PicHost supports **local disk** and **S3-compatible object storage** (Cloudflare R2, Tencent COS, Alibaba OSS, AWS S3, etc.). Admins manage backends at **Storage** (`/storage`); new uploads go to the **default** backend. The page shows a **storage overview** (total, used, remaining, usage rate, capacity chart) plus per-backend cards and supported backend types.
PicHost supports **local disk**, **S3-compatible object storage** (Cloudflare R2, Tencent COS, Alibaba OSS, AWS S3, etc.), and a **Telegram channel or group**. Admins manage backends at **Storage** (`/storage`); new uploads go to the **default** backend. The page shows a **storage overview** (total, used, remaining, usage rate, capacity chart) plus per-backend cards and supported backend types.
![Storage management](/screenshots/storage.png)
@@ -18,14 +18,16 @@ PicHost supports **local disk** and **S3-compatible object storage** (Cloudflare
All **keys** start with `images/`. The upload API does **not** accept a `folder` parameter.
**Classification** uses per-user **tags** in SQLite (`tags` / `image_tags`); disk paths are unchanged. See [API](./api.md#6-tags).
## Adding a backend
1. Sign in as admin → **Storage** → **Add backend**.
2. Choose **local disk** or **S3-compatible** (R2 / COS / OSS presets).
3. Enter connection details (bucket, endpoint, keys).
2. Choose **local disk**, **S3-compatible** (R2 / COS / OSS presets), or **Telegram channel**.
3. Enter connection details (bucket, endpoint, keys, or Bot Token / Chat ID).
4. **Set as default** so new uploads use it.
New object-storage backends get an auto-generated **storage ID** prefix: `local` for disk; `r2-*` for R2; `cos-*` for COS; `oss-*` for OSS; `s3-*` for AWS S3 and custom S3-compatible endpoints (immutable after creation; the image index references this ID).
New backends get an auto-generated **storage ID** prefix: `local` for disk; `r2-*` for R2; `cos-*` for COS; `oss-*` for OSS; `s3-*` for AWS S3 and custom S3-compatible endpoints; `tg-*` for Telegram (immutable after creation; the image index references this ID).
### Cloudflare R2
@@ -38,6 +40,23 @@ New object-storage backends get an auto-generated **storage ID** prefix: `local`
The **cloudflare** branch streamlines R2-only deploys; see branch notes on the [docs overview](./index.md).
### Telegram channel or group
A bot posts each image into a channel or group (private chats work). Visitors still load PicHost URLs; the app never redirects to a Telegram file URL.
1. Create a bot with [@BotFather](https://t.me/BotFather) and copy the token.
2. Make the bot an admin of the channel or group (post messages; also grant delete messages if gallery deletes should remove the Telegram post).
3. On the Storage page choose **Telegram channel**, then enter the Chat ID (supergroups and channels are usually `-100…`), the bot token, and a quota.
4. If the server cannot reach `api.telegram.org` directly, set an optional HTTP/HTTPS API proxy (for example `http://127.0.0.1:7890`).
Limits and behavior:
- Practical per-file cap is about **20MB** (the smaller of this and the site upload limit applies)
- About **20 messages per minute** per chat; faster batches fail with a retry hint
- Serving mode is always **proxy**
- Gallery delete tries to delete the Telegram message. If an upload reaches the chat but PicHost cannot store a file id, that message is removed when possible
- Full backups download files through the bot and are subject to the rate limit. Packages do not include the bot token; enter it again after restore. Restoring onto a default Telegram backend re-uploads images into the chat
### Environment variables (optional)
Some installs seed a default S3 backend via `STORAGE_BACKEND=s3`, `S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY`, `S3_SECRET_KEY`, `S3_REGION`. **UI-configured backends live in SQLite** alongside env-based defaults.
@@ -54,13 +73,50 @@ Copied links use **IMAGE_BASE_URL**. “Hide folder prefix” may shorten URLs;
## Usage & gallery filter
- Per-backend usage on the Storage page
- Gallery filters by **storage backend** and **upload source**; grid/list view toggle
- Gallery filters by **storage backend**, **upload source**, and **tags**; grid/list view toggle; click a thumbnail for the detail modal (dimensions, storage path, tags, link formats)
## Backup
![Gallery grid](/screenshots/gallery.png) ![Gallery list](/screenshots/gallery-list.png) ![Image detail](/screenshots/gallery-detail.png)
Back up `data/images/`, `data/pichost.db`, and bucket objects.
## Backup & migration (v1.3.0+)
Upgrading from v1.1.x with parallel folders: [v1.2 migration](./migration.md).
The **Backup & migration** panel has three action cards and a paginated **Recent jobs** table below:
| Feature | Description |
| ------- | ------------- |
| **Create site backup** | Export `.phost.tar.gz` with `pichost.db` and all images (including objects on cloud backends); shows estimated size and package contents |
| **Restore from backup** | Upload locally or pick an existing package under `data/backups/`, preview, then confirm; skip or overwrite conflicting images |
| **Cross-backend sync** | Copy images between configured backends and update the index; shows pending count/size, dry-run, optional delete-source and set-default |
![Backup & migration](/screenshots/storage.png)
- Exports are saved under `data/backups/`; only one backup/migration job may run at a time
- Job list supports pagination; download exports, view restore summaries, retry failed sync jobs
- Packages **do not** include cloud storage secrets — re-enter them on the Storage page after restore
- Uninitialized instances can use the **Restore backup** tab on `/setup` (always overwrite mode)
![Setup restore](/screenshots/setup-restore.png)
### CLI
```bash
docker exec pichost backup-export
docker exec pichost backup-restore /data/backups/pichost-xxx.phost.tar.gz
docker exec pichost backup-restore /data/backups/pichost-xxx.phost.tar.gz --overwrite
docker exec pichost storage-sync --from local --to s3-xxx --dry-run
docker exec pichost storage-sync --from local --to s3-xxx --set-default
```
Local development (project root):
```bash
npm run backup-export
npm run backup-restore -- data/backups/pichost-xxx.phost.tar.gz
npm run storage-sync -- --from local --to s3-xxx --dry-run
```
### Manual backup
You can still back up `data/images/`, `data/pichost.db`, and bucket objects directly; prefer the full-site export above.
## See also
@@ -16,6 +16,7 @@ PicHost uses role-based access control (RBAC): **admin** and **user**. Enforceme
| Global API token | ✓ | — |
| Personal API token | ✓ | ✓ |
| Gallery stats overview (incl. user count) | ✓ | partial |
| Tag management (Settings → Tag management) | ✓ | — |
| Activity log (Settings → Activity log) | ✓ | — |
Regular users see **API**, **Gallery** in the nav; user menu: **Change password**, **Sign out**.
@@ -39,6 +40,20 @@ Regular users see **API**, **Gallery** in the nav; user menu: **Change password*
- If verification is misconfigured: `docker exec pichost slider` resets to the local slider
- Login rate limiting
## Tags
- Tags are **per-user**: regular users manage and filter only their own tags and images
- After upload on the home page, **tag one image** or use **batch tagging**; the gallery supports tag filters (OR / AND) and batch tagging
- Admins manage tags under **Settings → Tag management** (create, recolor, merge, delete). Tags classify images only and **do not change** `images/` storage paths
![Batch tagging](/screenshots/tags-batch.png) ![Tag management](/screenshots/tags.png)
## Activity log
Admins review uploads, deletes, logins, settings changes, tag operations, and more under **Settings → Activity log**, with filters for date, user, action type, and source.
![Activity log](/screenshots/logs.png)
## Upload preferences & auto-delete
- **Upload preferences**: admins configure client compression and auto-copy in **Settings → Basic**; regular users can flip the home upload card for personal preferences
+1 -1
View File
@@ -20,7 +20,7 @@ features:
- title: Drag, click, paste
details: Server-side WebP compression and Referer hotlink protection.
- title: Multi-backend storage
details: Local disk plus S3-compatible backends (R2 / COS / OSS / AWS); proxy or public URLs.
details: Local disk, S3-compatible backends (R2 / COS / OSS / AWS), and Telegram; proxy or public URLs.
- title: Users & RBAC
details: Admin and regular users; global and per-user API tokens; gallery scoped by owner.
- title: Zero-config Docker
+41 -5
View File
@@ -2,6 +2,8 @@
PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API** 页:左侧为接口目录与 Token 管理,中间为参数说明与 cURL 示例,右侧可 **在线调试** 发送请求。
![API 文档与在线调试](/screenshots/api.png)
## 鉴权
所有 REST 接口使用请求头:
@@ -10,10 +12,10 @@ PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API*
Auth-Token: YOUR_TOKEN
```
| Token 类型 | 获取方式 | 说明 |
| ---------- | -------- | ---- |
| **全局 Token** | 管理员 **API** 页生成;或 `API_UPLOAD_TOKEN` 环境变量 | 环境变量优先且锁定后台重新生成 |
| **个人 Token** | 各用户 **API** 页 | 仅用于该用户脚本,上传归属本人 |
| Token | 获取方式 | 说明 |
| ----- | -------- | ---- |
| **API Token** | 登录后 **API** 页(每账号一个,自动生成) | 请求头 `Auth-Token`;上传与 tagNames 归属该账号 |
| **遗留全站 Token** | 环境变量 `API_UPLOAD_TOKEN` 或旧版后台配置 | 仍可用;上传归属**首个管理员**账号。Twikoo 表单 `token` 亦支持各账号 API Token |
表单上传仍可使用字段 `token`(Twikoo 协议)。
@@ -28,9 +30,12 @@ Auth-Token: YOUR_TOKEN
```bash
curl -X POST "https://admin.example.com/api/images/upload" \
-H "Auth-Token: YOUR_TOKEN" \
-F "image=@./demo.png"
-F "image=@./demo.png" \
-F 'tagNames=["博客","截图"]'
```
可选表单字段 `tagNames`:JSON 数组或逗号分隔名称;上传成功后自动打标。存储路径仍为 `images/年/月/id.webp`,**不会**因标签创建子目录。
### 2. 获取图片列表
`GET /api/images`
@@ -42,6 +47,16 @@ curl "https://admin.example.com/api/images?limit=20&page=1" \
-H "Auth-Token: YOUR_TOKEN"
```
可选查询参数:
| 参数 | 说明 |
| ---- | ---- |
| `tagIds` | 逗号分隔的标签 ID,默认 **OR**(含任一标签) |
| `tagMode` | `and` 时多标签取交集 |
| `untagged` | `1` 仅返回无标签图片 |
响应 `items[]` 含 `tags` 数组(`id`、`name`、`color`)。
### 3. 搜索图片
`GET /api/images/search`
@@ -77,6 +92,27 @@ curl -X POST "https://admin.example.com/api/images/batch-delete" \
-d '{"keys":["images/2026/08/a.webp","images/2026/08/b.webp"]}'
```
### 6. 标签管理
| 方法 | 路径 | 说明 |
| ---- | ---- | ---- |
| `GET` | `/api/tags` | 当前用户标签列表(含 `imageCount`) |
| `POST` | `/api/tags` | 创建 `{ "name": "工作", "color": "#22c55e" }` |
| `PATCH` | `/api/tags/:id` | 改名称/颜色 |
| `DELETE` | `/api/tags/:id` | 删除标签(不删图片) |
| `POST` | `/api/tags/merge` | `{ "sourceIds": [2,3], "targetId": 1 }` |
### 7. 图片打标
| 方法 | 路径 | 说明 |
| ---- | ---- | ---- |
| `POST` | `/api/images/tags` | `{ "key": "images/…", "tagIds": [1,2] }` 追加 |
| `PATCH` | `/api/images/tags` | 整体替换标签集合 |
| `DELETE` | `/api/images/tags` | `key` + `tagId` 移除单个 |
| `POST` | `/api/images/batch-tags` | `{ "keys": [], "tagIds": [], "action": "add" \| "remove" }` |
`GET /api/stats` 支持与列表相同的 `tagIds` / `tagMode` / `untagged` 筛选,统计与当前筛选一致。
## 错误格式
REST 接口返回 JSON,含 `code` 与 `message`(如 `UNAUTHORIZED`、`FORBIDDEN`、`INVALID_REQUEST`)。Twikoo 端点使用 EasyImage 兼容 JSON 格式。
+46 -4
View File
@@ -4,6 +4,51 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
---
## [1.4.3] — 2026-10-09
### 新增
- **Telegram 存储后端**:频道/群组存图,直链仍经 PicHost;可选 API 代理
## [1.4.2] — 2026-09-23
### 修复
- 图库批量打标与上传 Token 鉴权(含 `API_UPLOAD_TOKEN` 兼容)
### 改进
- API 页单 Token;上传 `tagNames`;标签管理排序与移动端布局;API 文档表格式
## [1.4.1] — 2026-09-16
### 新增
- **上传策略(设置 → 基础)**:大小、格式、限流、保留原图;环境变量可覆盖
- **上传 API**:可选 `tagNames` 按名称打标(自动创建或复用)
### 改进
- 登录限流可配置;设置页布局调整
## [1.4.0] — 2026-09-09
### 新增
- **标签**:每用户彩色标签;设置页管理;上传/图库批量打标;图库 OR / AND 筛选
- **操作日志**:登录、删除、设置、标签等操作;日期与用户筛选
- **API**:标签与打标接口;上传 `tagIds`;列表/统计标签筛选
### 文档
- 截图与 README 同步 v1.4 界面
## [1.3.0] — 2026-09-07
### 新增
- **站点备份 / 恢复 / 跨后端同步** 与任务中心;运维 CLI `backup-export`、`backup-restore`、`storage-sync`
## [1.2.8] — 2026-09-04
### 改进
@@ -159,15 +204,12 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
### 变更
- 图片统一存放在 `data/images/`;遗留 `blog/`、`twikoo/` 等并列目录需迁移
- 图片统一存放在 `data/images/`;不再使用与 `images` 并列的顶层目录
### 新增
- CLI:`docker exec pichost migrate` / `migrate --apply`
- 启动时自动同步图片索引(扫描磁盘、归一化遗留 key、清理孤儿记录)
详见 [v1.2 迁移](./migration.md)。
---
## [1.1.x] 摘要
+3 -1
View File
@@ -1,4 +1,6 @@
PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配置。管理员在 **设置与偏好**(`/settings`)左侧切换 **基础设置**、**域名与路径**、**访问控制**、**操作日志**;多数项 **SQLite 优先**;部分项环境变量可覆盖或锁定后台编辑。
PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配置。管理员在 **设置与偏好**(`/settings`)左侧切换 **基础设置**、**域名与路径**、**访问控制**、**标签管理**、**操作日志**;多数项 **SQLite 优先**;部分项环境变量可覆盖或锁定后台编辑。
![基础设置](/screenshots/settings.png)
## 优先级总览
+10 -10
View File
@@ -62,21 +62,21 @@ docker exec pichost clear-domains
- 后台请用 **网站域名** 打开,不要用 `localhost` 混用
- 见 [双域名分离](./domain-separation.md)
## 升级 v1.2 后图库有删不掉的记录?
## 图库有删不掉的记录?
可能是 **孤儿索引**(有记录无文件)。重启后启动同步会自动清理;也可手动删除仅索引项。见 [v1.2 迁移](./migration.md#第二步启动时自动同步索引)。
可能是 **孤儿索引**(有记录无文件)。重启后启动同步会自动清理;也可在图库中手动删除。
## 遗留 `data/blog/` 目录还要吗?
## 如何备份与迁移整站?
执行 `migrate --apply` 后文件已迁入 `data/images/blog/`。若原目录只剩空壳或非图片文件,可自行备份后删除;迁移脚本不会删除仍含非图片文件的目录。
v1.3.0 起在 **存储** 页使用「备份与迁移」面板,或 CLI:
## 只用对象存储需要跑 migrate 吗?
```bash
docker exec pichost backup-export
docker exec pichost backup-restore /data/backups/pichost-xxx.phost.tar.gz
docker exec pichost storage-sync --from local --to s3-xxx --dry-run
```
不需要。图片在桶内时跳过 CLI;启动同步主要面向本地 `data/images/` 磁盘扫描。
## 如何替换博客里的旧图片 URL?
使用 `data/mapping.json`(`migrate` 预览时生成)批量替换旧 key。注意映射的是 **存储 key**,不是完整旧站 URL。见 [迁移指南](./migration.md#外链与直链)。
备份包含数据库与全部图片,**不含** 云存储密钥;恢复后请在存储页重新填写。详见 [存储 → 备份与迁移](./storage.md#备份与迁移v130)。
## 开发时如何跳过登录?
+12 -8
View File
@@ -33,9 +33,19 @@ docker compose up -d
## 首次设置
1. 访问实例 URL(Docker 默认 `http://<主机>:6892`)。
2. 在 `/setup` 填写管理员用户名与密码。
2. 在 `/setup` 选择 **创建管理员** 或 **从备份恢复**:
- **创建管理员**:填写用户名与密码,可选开放注册、双域名等。
- **从备份恢复**:上传 `.phost.tar.gz` 整站备份包(覆盖当前数据;云存储密钥需恢复后重新填写)。
3. (可选)配置网站域名、图片域名、防盗链等 — 详见 [环境变量](./configuration.md) 与 [双域名分离](./domain-separation.md)。
4. 登录后可在首页上传图片;顶栏可进入 **图库**、**存储**(管理员)、**设置**、**API**。
4. 登录后可在首页 **拖拽 / 点击 / Ctrl+V** 上传图片;上传结果区支持复制直链/Markdown/HTML/BBCode,并可 **批量打标签**。顶栏可进入 **图库**、**存储**(管理员)、**设置**、**API**。
![上传](/screenshots/upload.png)
| 创建管理员 | 从备份恢复 |
| :--------: | :--------: |
| ![首次设置](/screenshots/setup.png) | ![从备份恢复](/screenshots/setup-restore.png) |
已初始化实例请使用 [存储 → 备份与迁移](./storage.md#备份与迁移v130) 恢复,而非 setup 页。
## 登录
@@ -83,12 +93,6 @@ docker exec pichost clear-domains
本地:`npm run clear-domains`。详见 [常见问题 — 双域名配置后后台 404](./faq.md#双域名配置后后台-404-进不去)。
## 升级到 v1.2.0
若 `data/` 下存在与 `images` 并列的遗留目录(如 `blog/`、`twikoo/`),升级前请阅读 [v1.2 迁移指南](./migration.md)。
仅对象存储、或图片已在 `data/images/` 下时,拉取新镜像并重启即可。
## 下一步
- [本地开发](./local-dev.md) — `npm run dev` 与 `.env`
+21 -5
View File
@@ -12,15 +12,31 @@
## 截图预览
**main** 分支暂无公网演示,以下为当前产品界面(v1.2.5+)。
**main** 分支暂无公网演示,以下为当前产品界面(v1.4.0+)。
| API | 图库 |
| 上传 | 批量打标 |
| :-: | :-: |
| ![API](/screenshots/api.png) | ![图库](/screenshots/gallery.png) |
| ![上传](/screenshots/upload.png) | ![批量打标](/screenshots/tags-batch.png) |
| 存储管理 | 设置与偏好 |
| 上传结果(含标签) | API |
| :----------------: | :-: |
| ![上传结果](/screenshots/upload-tags.jpg) | ![API](/screenshots/api.png) |
| 图库(网格) | 图库(列表) |
| :----------: | :----------: |
| ![图库网格](/screenshots/gallery.png) | ![图库列表](/screenshots/gallery-list.png) |
| 图片详情 | 标签管理 |
| :------: | :------: |
| ![图片详情](/screenshots/gallery-detail.png) | ![标签管理](/screenshots/tags.png) |
| 存储管理 | 基础设置 |
| :------: | :------: |
| ![存储管理](/screenshots/storage.png) | ![基础设置](/screenshots/settings.png) |
| 首次设置 | 从备份恢复 |
| :------: | :--------: |
| ![存储管理](/screenshots/storage.png) | ![设置与偏好](/screenshots/settings.png) |
| ![首次设置](/screenshots/setup.png) | ![从备份恢复](/screenshots/setup-restore.png) |
| 操作日志 |
| :------: |
+1 -2
View File
@@ -30,7 +30,6 @@ npm run dev
| `npm run reset-password` | 重置密码(可选用户名) |
| `npm run slider` | 将登录验证重置为本地滑块 |
| `npm run clear-domains` | 清除数据库中的网站域 / 图片域配置(双域名锁死时恢复) |
| `npm run migrate` | 预览遗留目录迁移(加 `-- --apply` 执行) |
## 开发专用环境变量
@@ -53,4 +52,4 @@ npm run docs:build # 构建静态站点
npm run docs:preview # 预览构建结果
```
文档源码在 `docs-site/`;截图源文件在 `docs/screenshots/`(含 `login.png` 登录页),构建前会复制到 `docs-site/public/screenshots/`。在线文档:<https://o96u.github.io/PicHost/>
文档源码在 `docs-site/`;截图源文件在 `docs/screenshots/`(含 `upload.png`、`gallery.png`、`tags.png`、`api.png`、`storage.png`、`settings.png`、`logs.png`、`setup.png` 等),构建前会复制到 `docs-site/public/screenshots/`。在线文档:<https://o96u.github.io/PicHost/>
-176
View File
@@ -1,176 +0,0 @@
# v1.2.0 本地磁盘迁移指南
v1.2.0 起,**所有本地图片文件**统一放在 `data/images/` 下;SQLite `images` 表中的 `key` 也以 `images/` 开头。旧版在 `data/blog/`、`data/twikoo/` 等与 `images` **并列的顶层目录**不再符合新模型。
迁移分 **两步**:先用手动 CLI **搬文件**,再由服务 **启动时自动同步索引**。
---
## 从其它图床迁入(EasyImage / 兰空 / Chevereto 等)
**没有**单独的「一键从外链拉取」或「对接某某图床 API」工具。从 **PicHost 旧版** 或其它自托管图床迁入,走的是同一套 **本地文件迁移**:
1. 在旧图床服务器上找到图片**物理目录**(整目录拷贝,不要只拷数据库)。
2. 把该目录放到 PicHost 的 `data/` 下,作为与 `images` **并列的顶层文件夹**(文件夹名任意,会保留为 `images/{文件夹名}/...`)。
3. 执行 `migrate` / `migrate --apply`,再重启 PicHost。
### 常见来源示例
| 来源 | 典型图片目录(在旧服务器上) | 放入 PicHost 后示例 |
| ---- | ---------------------------- | ------------------- |
| PicHost v1.1.x | `data/blog/`、`data/twikoo/` | 已在 `data/` 下,直接 `migrate` |
| EasyImage / EasyImages | `i/` 或安装目录下的 `upload/` | 拷到 `data/easyimage/` 再 `migrate` |
| 兰空图床 (Lsky) | `public/uploads/` 等 | 拷到 `data/lsky/` 再 `migrate` |
| Chevereto 等 | `images/` 或 `content/` | 拷到 `data/chevereto/` 再 `migrate` |
| 任意自定义目录 | 你的顶层文件夹名 | 拷到 `data/你的目录名/` 再 `migrate` |
脚本会扫描 `data/` 下**除 `images` 外所有顶层目录**里的图片,不限于 `blog` / `twikoo`。子目录结构会原样保留在 `images/{顶层名}/` 下。
### 操作示例(Docker)
```bash
# 在宿主机:把从旧图床打包的目录放进挂载卷(名称自定)
# 例如:./data/easyimage/2026/01/photo.jpg
docker exec pichost migrate # 预览
docker exec pichost migrate --apply
# 重启容器 → 启动日志会补全 SQLite 索引
```
### 说明与限制
- **只迁移文件**:旧图床的账号、Token、外链 URL **不会**自动导入;`mapping.json` 里的 key 是「旧磁盘相对 key → 新 key」,**不是**旧站完整 URL,替换外链需自行对照。
- **对象存储**:若旧图床图片在 S3/R2 桶里,请用桶工具同步到本地 `data/某目录/`,或直接在 PicHost **存储**页配置同一桶(不经过本 CLI)。
- **已直接在 `data/images/` 下**:无需 `migrate`,重启后启动同步会自动建索引。
---
## 存储结构对比
### 迁移前(v1.1.x 常见)
```
/data
├── pichost.db
├── blog/
│ └── 2026/08/TeKJ2fD6cB6j.webp
├── twikoo/
│ └── xxx.webp
└── images/ # 可能已有部分新图
└── ...
```
SQLite 中 `key` 可能是 `blog/2026/08/TeKJ2fD6cB6j.webp`(与磁盘顶层目录一致)。
### 迁移后(v1.2.0)
```
/data
├── pichost.db
├── mapping.json # CLI 生成:旧 key → 新 key(供替换外链)
└── images/
├── blog/
│ └── 2026/08/TeKJ2fD6cB6j.webp
├── twikoo/
│ └── xxx.webp
└── ... # 新上传:images/随机ID.webp 或 images/年/月/随机ID.webp
```
对应 `key`:`images/blog/2026/08/TeKJ2fD6cB6j.webp`。
---
## 第一步:CLI 迁移磁盘文件
在 **升级镜像之前或之后**均可执行;建议在升级前完成,并先备份整个 `data/` 目录。
### Docker
```bash
# 预览:列出待迁移文件,写入 data/mapping.json(旧 key → 新 key)
docker exec pichost migrate
# 确认无误后执行文件移动
docker exec pichost migrate --apply
```
### 本地开发
```bash
npm run migrate # 预览
npm run migrate -- --apply # 执行
```
### 脚本行为
| 项目 | 说明 |
| ---- | ---- |
| 扫描范围 | `data/` 下**除 `images` 外所有顶层目录**(不限于 blog/twikoo) |
| 迁移目标 | `data/images/{原顶层目录名}/{相对路径}` |
| 图片类型 | `.jpg` `.jpeg` `.png` `.webp` `.gif` `.svg` `.ico` |
| 伴随文件 | 若存在同名的 `.meta.json` 会一并移动 |
| 非图片文件 | 不移动;若目录内仍有其它文件,**保留原目录**不删除 |
| 映射表 | `data/mapping.json`,例如 `"blog/foo.webp": "images/blog/foo.webp"` |
脚本路径:`server/cli/migrate-to-single-images.mjs`。
---
## 第二步:启动时自动同步索引
每次 PicHost 启动(`npm run dev`、Docker 容器启动)会自动执行,**无需手动命令**。日志示例:
```text
[INFO] 开始同步图片索引:扫描本地磁盘 {"path":".../data/images/"}
[INFO] 磁盘扫描完成:已补全缺失索引 {"inserted":3}
[INFO] 开始归一化遗留图片路径(如 blog/ → images/blog/)
[INFO] 遗留路径归一化完成:无需调整
[INFO] 开始校验索引与磁盘一致性,清理无文件的孤儿记录
[INFO] 孤儿索引清理完成:未发现孤儿记录
[INFO] 开始修复存量 Content-Type 元数据
[INFO] Content-Type 修复完成:无需修复
[INFO] 图片索引同步结束
```
| 步骤 | 作用 |
| ---- | ---- |
| 扫描 `data/images/` | 磁盘上有、索引里没有 → **补全** `images` 表 |
| 归一化遗留 key | 将 `blog/...` 等旧 key 更新为 `images/blog/...`(文件已在正确路径时) |
| 清理孤儿索引 | 索引里有记录、磁盘无文件 → **删除**幽灵记录(避免图库出现删不掉的项) |
| 修复 Content-Type | 修正错误的 `application/octet-stream` |
CLI 只负责**搬文件**;索引对齐、遗留 key、孤儿记录由启动同步处理。执行 `migrate --apply` 后**重启一次**服务即可。
---
## 推荐升级流程
1. **备份** `data/`(含 `pichost.db` 与各目录)。
2. `docker exec pichost migrate` 预览,检查输出与 `mapping.json`。
3. `docker exec pichost migrate --apply` 执行迁移。
4. 拉取 / 部署 **v1.2.0** 镜像并重启容器。
5. 查看启动日志,确认「图片索引同步结束」无报错。
6. 用 `mapping.json` 批量替换博客、Twikoo 等外链中的旧路径(若需要)。
仅使用对象存储、或图片早已全部在 `data/images/` 下时,**跳过第一步**;第二步仍会在启动时运行,通常几秒内完成且无变更日志。
---
## 外链与直链
| 场景 | 说明 |
| ---- | ---- |
| 旧 key | `blog/TeKJ2fD6cB6j.webp` |
| 新 key | `images/blog/TeKJ2fD6cB6j.webp` |
| 隐藏目录模式 | 若开启「隐藏 images 前缀」,短链可能为 `/TeKJ2fD6cB6j.webp`;服务按文件名反查索引 |
| 替换建议 | 以 `mapping.json` 为准;或重新在图库复制新链接 |
---
## 相关命令
| 命令 | 说明 |
| ---- | ---- |
| `docker exec pichost migrate` | 预览磁盘迁移 |
| `docker exec pichost migrate --apply` | 执行磁盘迁移 |
| `docker exec pichost reset-password` | 重置密码(与迁移无关) |
+68 -11
View File
@@ -1,6 +1,6 @@
# 存储
PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、腾讯云 COS、阿里云 OSS、AWS S3 等)。管理员在 **存储**(`/storage`)页管理后端;新上传写入 **默认后端**。页面顶部展示 **存储总览**(总量、已用、剩余、使用率与容量分布),下方为各后端卡片与支持的后端类型说明。
PicHost 支持 **本地磁盘**、**S3 兼容对象存储**(Cloudflare R2、腾讯云 COS、阿里云 OSS、AWS S3 等)与 **Telegram 频道/群组**。管理员在 **存储**(`/storage`)页管理后端;新上传写入 **默认后端**。页面顶部展示 **存储总览**(总量、已用、剩余、使用率与容量分布),下方为各后端卡片与支持的后端类型说明。
![存储管理](/screenshots/storage.png)
@@ -18,14 +18,16 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
所有图片 **key** 以 `images/` 开头。上传 API **不再接受** `folder` 参数。
**图片分类**使用每用户 **标签**(`tags` / `image_tags` 表),不改变磁盘路径。图库页按标签筛选;详见 [API 文档](./api.md#6-标签管理)。
## 添加存储后端
1. 以管理员登录,打开 **存储** → **添加存储**。
2. 选择类型:**本地磁盘** 或 **S3 兼容**(含 R2 / COS / OSS 预设)。
3. 填写连接信息(桶名、Endpoint、Access Key 等)。
2. 选择类型:**本地磁盘**、**S3 兼容**(含 R2 / COS / OSS 预设)或 **Telegram 频道**。
3. 填写连接信息(桶名、Endpoint、Access Key,或 Bot Token / Chat ID 等)。
4. 保存后可 **设默认**,新上传将写入该后端。
新建对象存储后端的 **存储标识** 按类型自动生成前缀:本地为 `local`;R2 为 `r2-*`;COS 为 `cos-*`;OSS 为 `oss-*`;AWS S3 及自定义 S3 兼容为 `s3-*`(创建后不可修改,图片索引会引用该 ID)。
新建后端的 **存储标识** 按类型自动生成前缀:本地为 `local`;R2 为 `r2-*`;COS 为 `cos-*`;OSS 为 `oss-*`;AWS S3 及自定义 S3 兼容为 `s3-*`;Telegram 为 `tg-*`(创建后不可修改,图片索引会引用该 ID)。
### Cloudflare R2 要点
@@ -38,6 +40,23 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
若仓库 **cloudflare** 分支专用于「仅 R2」部署,也可用环境变量预设,见 [文档首页](./index.md) 分支说明。
### Telegram 频道 / 群组
用 Bot 把图片发进指定频道或群组(含私有频道),访客仍通过 PicHost 直链访问,不会跳到 Telegram 文件地址。
1. 在 [@BotFather](https://t.me/BotFather) 创建 Bot,取得 Token。
2. 把 Bot 设为频道或群组管理员(需要发消息;若希望图库删除时同步删掉群消息,还需要删除消息权限)。
3. 在存储页选择 **Telegram 频道**,填写 Chat ID(超级群组/频道多为 `-100…`)、Bot Token,以及套餐配额。
4. 服务器若不能直连 `api.telegram.org`,可填写可选的 HTTP/HTTPS API 代理(如 `http://127.0.0.1:7890`)。
限制与行为:
- 单文件实际上限约 **20MB**(超过站点上传限制时,以更小者为准)
- 同一频道大约 **20 条消息/分钟**;批量上传过快会失败并提示稍后重试
- 直链固定为 **proxy**,不能改为公开 URL
- 图库删除会尝试删除对应的 Telegram 消息;上传失败且未记下文件编号时,会尽量撤回刚发出的消息
- 整站备份会经 Bot 拉取文件,耗时并受上述频率限制;备份包不含 Bot Token,恢复后需重新填写。恢复到 Telegram 默认后端时,会把图片重新发进频道
### 环境变量(可选)
部分部署用环境变量初始化默认 S3 后端(如 `STORAGE_BACKEND=s3`、`S3_ENDPOINT`、`S3_BUCKET`、`S3_ACCESS_KEY`、`S3_SECRET_KEY`、`S3_REGION`)。**UI 中配置的后端信息存于 SQLite**,与环境变量并存时以管理界面为准管理多后端。
@@ -56,17 +75,55 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
## 用量与筛选
- 存储页展示各后端用量(本地扫描目录,对象存储查询 API)
- 图库可按 **存储后端**、**上传来源** 筛选,支持网格/列表视图切换
- 图库可按 **存储后端**、**上传来源**、**标签** 筛选,支持网格/列表视图切换;点击图片打开详情弹窗(尺寸、存储路径、标签、多格式链接复制)
## 备份
![图库网格](/screenshots/gallery.png) ![图库列表](/screenshots/gallery-list.png) ![图片详情](/screenshots/gallery-detail.png)
请同时备份:
## 备份与迁移(v1.3.0+)
- `data/images/`(本地后端)
- `data/pichost.db`
- 各云桶中的对象
存储页 **备份与迁移** 面板包含三张功能卡与下方 **最近任务** 列表:
从 v1.1.x 升级且存在 `data/blog/` 等并列目录时,见 [v1.2 迁移](./migration.md)。
| 能力 | 说明 |
| ---- | ---- |
| **创建站点备份** | 导出 `.phost.tar.gz`,含 `pichost.db` 与全部图片(含云存储中的对象);展示预计体积与备份包含项 |
| **从备份恢复** | 本地上传或选择 `data/backups/` 内已有包,预检后确认;可选跳过/覆盖冲突图片 |
| **跨后端同步** | 在已配置后端间拷贝图片并更新索引;展示待迁移数量与体积,支持预检、删源、设默认 |
![备份与迁移](/screenshots/storage.png)
- 导出文件保存在 `data/backups/`;后端同一时间仅允许一个进行中的备份/迁移任务
- 任务列表支持分页,可下载导出包、查看恢复结果、重试失败的同步任务
- 备份包 **不含** 云存储 Access Key / Secret Key,恢复后请在存储页重新填写
- 未初始化实例可在 **setup** 页 **从备份恢复** 标签上传整站包(始终覆盖模式)
![从备份恢复(setup)](/screenshots/setup-restore.png)
### CLI
```bash
# 导出整站备份
docker exec pichost backup-export
# 从备份恢复(默认跳过冲突图片)
docker exec pichost backup-restore /data/backups/pichost-xxx.phost.tar.gz
docker exec pichost backup-restore /data/backups/pichost-xxx.phost.tar.gz --overwrite
# 跨后端同步
docker exec pichost storage-sync --from local --to s3-xxx --dry-run
docker exec pichost storage-sync --from local --to s3-xxx --set-default
```
本地开发(项目根目录):
```bash
npm run backup-export
npm run backup-restore -- data/backups/pichost-xxx.phost.tar.gz
npm run storage-sync -- --from local --to s3-xxx --dry-run
```
### 手动备份
仍可同时备份 `data/images/`(本地后端)、`data/pichost.db` 与各云桶中的对象;推荐使用上文整站导出。
## 相关
+22 -12
View File
@@ -13,9 +13,9 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
| 系统设置(`/settings`) | ✓ | — |
| 开放注册开关 | ✓ | — |
| 登录人机验证方式(滑块 / Turnstile / Cap) | ✓ | — |
| 全局 API Token 管理 | ✓ | — |
| 个人 API Token | ✓ | ✓ |
| API Token(每账号一个) | ✓ | ✓ |
| 图库统计概览(含注册用户数) | ✓ | 部分 |
| 标签管理(设置 → 标签管理) | ✓ | — |
| 操作日志(设置 → 操作日志) | ✓ | — |
普通用户顶栏:**API**、**图库**;用户菜单:**修改密码**、**退出登录**。
@@ -25,9 +25,8 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
| 场景 | 鉴权方式 | 图片归属 / 可见范围 |
| ---- | -------- | ------------------- |
| 网页上传 | Session Cookie | 当前登录用户 |
| API 上传 + **个人 Token** | `Auth-Token` 头 | Token 所属用户 |
| API 上传 + **全局 Token** | `Auth-Token` 头 | 管理员(`userId` 为空) |
| Twikoo `POST /api/index.php` | 表单 `token` | 与全局 Token 相同 |
| API 上传 | `Auth-Token` 或表单 `token` | Token 对应账号(遗留 `API_UPLOAD_TOKEN` 归属首个管理员) |
| Twikoo `POST /api/index.php` | 表单 `token` | 同上 |
| 图库列表 / 搜索 / 删除 | Session 或 Token | 普通用户仅自己;管理员全部 |
| 图片直链 `GET /images/...` | 无(Referer 防盗链) | 知道 URL 即可访问 |
@@ -39,19 +38,30 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
- 验证配置错误无法登录时:`docker exec pichost slider` 重置为本地滑块
- 登录失败有速率限制
## 标签
- 标签按 **用户隔离**:普通用户仅管理、筛选自己的标签与图片
- 首页上传完成后可 **单张打标** 或 **批量打标签**;图库支持按标签筛选(多标签 OR / AND)与批量打标
- 管理员在 **设置 → 标签管理** 新建、改色、合并、删除标签;标签仅用于分类,**不改变** `images/` 存储路径
![批量打标](/screenshots/tags-batch.png) ![标签管理](/screenshots/tags.png)
## 操作日志
管理员在 **设置 → 操作日志** 查看上传、删除、登录、设置变更、标签操作等记录,支持按日期、用户、操作类型、来源筛选。
![操作日志](/screenshots/logs.png)
## 上传偏好与自动删除
- **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好
- **自动删除**:管理员可设全局策略;用户可设个人策略。启用后仅影响 **之后新上传** 的图片
## API Token 说明
## API Token
| 类型 | 谁管理 | 上传归属 | 典型用途 |
| ---- | ------ | -------- | -------- |
| **全局 Token** | 管理员(API 页) | 管理员账号 | Twikoo、站点级脚本 |
| **个人 Token** | 各用户(API 页) | 该用户 | 个人博客、私有脚本 |
若设置了环境变量 `API_UPLOAD_TOKEN`,则全局 Token 被锁定,见 [环境变量](./configuration.md)。
- **每个账号一个 Token**(含管理员),在 **API** 页查看或重新生成;首次打开会自动创建
- 上传、`tagNames` 打标、图库接口均归属 **该 Token 所属账号**
- 环境变量 **`API_UPLOAD_TOKEN`**(旧部署)仍可作为鉴权密钥,上传归属 **首个管理员**,见 [环境变量](./configuration.md)
## 相关
+1 -1
View File
@@ -20,7 +20,7 @@ features:
- title: 拖拽 / 粘贴上传
details: 支持点击、拖拽与 Ctrl+V 粘贴;服务端 WebP 压缩与 Referer 防盗链。
- title: 多后端存储
details: 本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);proxy 或 public 直链模式。
details: 本地磁盘 + S3 兼容(R2 / COS / OSS / AWS)+ Telegram 频道/群组;proxy 或 public 直链。
- title: 多用户与权限
details: 管理员与普通用户 RBAC;全局 Token 与个人 Token;图库按归属隔离。
- title: Docker 零配置
Binary file not shown.

Before

Width:  |  Height:  |  Size: 125 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 151 KiB

After

Width:  |  Height:  |  Size: 209 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 101 KiB

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff. Show more