2 Commits
Author SHA1 Message Date
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
159 changed files with 9967 additions and 1111 deletions

No files matched your search

+36 -1
View File
@@ -4,6 +4,42 @@
## [Unreleased] ## [Unreleased]
## [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 ## [1.2.8] - 2026-09-04
### 改进 ### 改进
@@ -119,7 +155,6 @@
- CLI 迁移工具:`docker exec pichost migrate` / `migrate --apply`(`server/cli/migrate-to-single-images.mjs`) - CLI 迁移工具:`docker exec pichost migrate` / `migrate --apply`(`server/cli/migrate-to-single-images.mjs`)
- 扫描 `data/` 下除 `images` 外所有顶层目录中的图片,输出 `data/mapping.json` - 扫描 `data/` 下除 `images` 外所有顶层目录中的图片,输出 `data/mapping.json`
- 启动时自动同步图片索引(扫描磁盘、归一化遗留 key、清理孤儿记录),并打印同步日志 - 启动时自动同步图片索引(扫描磁盘、归一化遗留 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 DATA_DIR=/data
COPY --from=build /app/.output ./.output 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/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/slider.mjs ./server/cli/slider.mjs
COPY server/cli/clear-domains.mjs ./server/cli/clear-domains.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 COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh
+18 -4
View File
@@ -31,20 +31,34 @@
**main** has no public demo. **cloudflare** branch live demo: [pic.roven.cc](https://pic.roven.cc) **main** has no public demo. **cloudflare** branch live demo: [pic.roven.cc](https://pic.roven.cc)
| API | Gallery | | Upload | Gallery |
| :--: | :-----: | | :----: | :-----: |
| ![API](docs/screenshots/api.png) | ![Gallery](docs/screenshots/gallery.png) | | ![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 | Settings |
| :-----: | :-------: | | :-----: | :-------: |
| ![Storage](docs/screenshots/storage.png) | ![Settings](docs/screenshots/settings-en.png) | | ![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 ## Features
- **Drag, click, or Ctrl+V paste** — server-side WebP, Referer hotlink protection - **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-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 - **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 - **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 - **API & Twikoo** — global / per-user tokens; `POST /api/index.php` compatible
- **Zero-config Docker** — first-run web wizard, no secrets upfront - **Zero-config Docker** — first-run web wizard, no secrets upfront
+18 -4
View File
@@ -31,20 +31,34 @@
**main** 分支暂无公网演示;**cloudflare** 分支在线体验:[pic.roven.cc](https://pic.roven.cc) **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/storage.png) | ![设置](docs/screenshots/settings.png) |
| 首次设置 | 从备份恢复 |
| :--: | :--: |
| ![首次设置](docs/screenshots/setup.png) | ![从备份恢复](docs/screenshots/setup-restore.png) |
| 操作日志 |
| :------: |
| ![操作日志](docs/screenshots/logs.png) |
## 特性 ## 特性
- **拖拽 / 点击 / Ctrl+V 粘贴**上传;服务端 WebP 压缩、Referer 防盗链 - **拖拽 / 点击 / Ctrl+V 粘贴**上传;服务端 WebP 压缩、Referer 防盗链
- **多用户**:账号密码登录(滑块 / Turnstile / Cap 人机验证)、可选开放注册;普通用户仅见自己的图片 - **多用户**:账号密码登录(滑块 / Turnstile / Cap 人机验证)、可选开放注册;普通用户仅见自己的图片
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public` - **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public`
- **图库**:浏览、搜索、按存储/来源筛选、网格/列表切换、批量删除;统计概览与来源分布 - **图库**:浏览、搜索、按存储/来源/标签筛选、网格/列表切换、批量删除与批量打标;统计概览与来源分布;点击图片查看详情与多格式链接
- **标签**:每用户独立标签、彩色标记;上传后单张/批量打标;设置页管理(新建、改色、合并、删除);API 支持 `tagIds` 与批量打标
- **备份与迁移**:整站导出/恢复(`.phost.tar.gz`)、跨后端同步;setup 未初始化时可从备份恢复
- **API 与 Twikoo**:全局 / 个人 Token;`POST /api/index.php` 兼容 - **API 与 Twikoo**:全局 / 个人 Token;`POST /api/index.php` 兼容
- **Docker 零配置**:首次访问 Web 引导创建管理员 - **Docker 零配置**:首次访问 Web 引导创建管理员
@@ -74,7 +88,7 @@ docker run -d \
浏览器打开 `http://<主机IP>:6892`,按引导完成设置即可。 浏览器打开 `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"> <script setup lang="ts">
import type { ImageItem } from '~/types/image' import type { ImageItem } from '~/types/image'
import type { CopyFormat } from '~/composables/useUploadPreferences' import type { CopyFormat } from '~/composables/useUploadPreferences'
import { buildImageBbcode } from '~/utils/image-display'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
image: ImageItem image: ImageItem
@@ -11,19 +12,26 @@ const props = withDefaults(defineProps<{
compact?: boolean compact?: boolean
gallery?: boolean gallery?: boolean
allowDelete?: boolean allowDelete?: boolean
showTags?: boolean
showTagAction?: boolean
}>(), { }>(), {
selectable: true, selectable: true,
showKey: true, showKey: true,
showStorage: false, showStorage: false,
compact: false, compact: false,
gallery: false, gallery: false,
allowDelete: true allowDelete: true,
showTags: false,
showTagAction: false
}) })
const emit = defineEmits<{ const emit = defineEmits<{
'update:selected': [value: boolean] 'update:selected': [value: boolean]
'preview': [] 'preview': []
'delete': [] 'delete': []
'tag-click': [tagId: number]
'untagged-click': []
'edit-tags': []
}>() }>()
const { formatFileSize } = useFileSize() const { formatFileSize } = useFileSize()
@@ -79,7 +87,8 @@ onUnmounted(clearRetryTimer)
const copyFormatItems = computed(() => [ const copyFormatItems = computed(() => [
{ label: t('copy.url'), value: 'url' as const }, { label: t('copy.url'), value: 'url' as const },
{ label: t('copy.markdown'), value: 'markdown' 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(() => { const uploadedLabel = computed(() => {
@@ -96,6 +105,8 @@ const previewValue = computed(() => {
return props.image.markdown return props.image.markdown
case 'html': case 'html':
return props.image.html return props.image.html
case 'bbcode':
return buildImageBbcode(props.image.url)
default: default:
return props.image.url return props.image.url
} }
@@ -107,6 +118,8 @@ const copySuccessTitle = computed(() => {
return t('copy.copiedMarkdown') return t('copy.copiedMarkdown')
case 'html': case 'html':
return t('copy.copiedHtml') return t('copy.copiedHtml')
case 'bbcode':
return t('copy.copiedBbcode')
default: default:
return t('copy.copiedUrl') 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') { function toggleSelected(value: boolean | 'indeterminate') {
emit('update:selected', value === true) emit('update:selected', value === true)
} }
@@ -210,16 +251,61 @@ async function copyGalleryUrl() {
<p class="truncate text-xs text-muted"> <p class="truncate text-xs text-muted">
{{ uploadedLabel }} · {{ formatFileSize(image.size) }} {{ uploadedLabel }} · {{ formatFileSize(image.size) }}
</p> </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 <div
v-if="uploadSourceLabel || (showStorage && image.storage)" 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 <span
v-if="showStorage && image.storage" 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" 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 class="truncate">{{ image.storage.name }}</span>
</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>
</div> </div>
@@ -302,6 +398,21 @@ async function copyGalleryUrl() {
@update:model-value="toggleSelected" @update:model-value="toggleSelected"
/> />
</div> </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 <div
v-if="image.owner" v-if="image.owner"
class="absolute bottom-2 left-2 max-w-[calc(50%-0.5rem)]" class="absolute bottom-2 left-2 max-w-[calc(50%-0.5rem)]"
@@ -371,6 +482,20 @@ async function copyGalleryUrl() {
> >
{{ image.originalName }} {{ image.originalName }}
</p> </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"> <p class="text-xs text-muted">
{{ uploadedLabel }} · {{ formatFileSize(image.size) }} {{ uploadedLabel }} · {{ formatFileSize(image.size) }}
</p> </p>
@@ -396,13 +521,28 @@ async function copyGalleryUrl() {
class="min-w-0 flex-1 font-mono text-xs" class="min-w-0 flex-1 font-mono text-xs"
/> />
<CopyButton <CopyButton
icon="i-lucide-copy"
:label="t('common.copy')" :label="t('common.copy')"
:variant="showTagAction ? 'solid' : 'soft'"
:color="showTagAction ? 'primary' : undefined"
:icon="showTagAction ? undefined : 'i-lucide-copy'"
:value="previewValue" :value="previewValue"
:success-title="copySuccessTitle" :success-title="copySuccessTitle"
/> />
</div> </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 <p
v-if="showKey" v-if="showKey"
class="truncate text-xs text-dimmed" class="truncate text-xs text-dimmed"
+13 -1
View File
@@ -13,6 +13,8 @@ const props = withDefaults(defineProps<{
/** 图库:5 列 × 2 行,缩略图略扁 */ /** 图库:5 列 × 2 行,缩略图略扁 */
gallery?: boolean gallery?: boolean
allowDelete?: boolean allowDelete?: boolean
showTags?: boolean
showTagAction?: boolean
}>(), { }>(), {
selectable: true, selectable: true,
showKey: true, showKey: true,
@@ -20,7 +22,9 @@ const props = withDefaults(defineProps<{
dense: false, dense: false,
compact: false, compact: false,
gallery: false, gallery: false,
allowDelete: true allowDelete: true,
showTags: false,
showTagAction: false
}) })
const gridClass = computed(() => { const gridClass = computed(() => {
@@ -37,6 +41,9 @@ const emit = defineEmits<{
'update:selectedKeys': [value: Set<string>] 'update:selectedKeys': [value: Set<string>]
'preview': [image: ImageItem] 'preview': [image: ImageItem]
'delete': [image: ImageItem] 'delete': [image: ImageItem]
'tag-click': [tagId: number]
'untagged-click': []
'edit-tags': [image: ImageItem]
}>() }>()
const { t } = useI18n() const { t } = useI18n()
@@ -68,9 +75,14 @@ function updateSelection(key: string, selected: boolean) {
:compact="compact" :compact="compact"
:gallery="gallery" :gallery="gallery"
:allow-delete="allowDelete" :allow-delete="allowDelete"
:show-tags="showTags"
:show-tag-action="showTagAction"
@update:selected="updateSelection(image.key, $event)" @update:selected="updateSelection(image.key, $event)"
@preview="emit('preview', image)" @preview="emit('preview', image)"
@delete="emit('delete', image)" @delete="emit('delete', image)"
@tag-click="emit('tag-click', $event)"
@untagged-click="emit('untagged-click')"
@edit-tags="emit('edit-tags', image)"
/> />
</div> </div>
<div <div
+52 -9
View File
@@ -1,18 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ImageItem } from '~/types/image' import type { ImageItem } from '~/types/image'
import type { CopyFormat } from '~/composables/useUploadPreferences' import type { CopyFormat } from '~/composables/useUploadPreferences'
import { formatImageDimensions } from '~/utils/image-display' import { buildImageBbcode, formatImageDimensions } from '~/utils/image-display'
type EmbedFormat = CopyFormat | 'bbcode'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
open: boolean open: boolean
image: ImageItem | null image: ImageItem | null
showStorage?: boolean showStorage?: boolean
showTags?: boolean
deleting?: boolean deleting?: boolean
allowDelete?: boolean allowDelete?: boolean
}>(), { }>(), {
showStorage: false, showStorage: false,
showTags: false,
allowDelete: true allowDelete: true
}) })
@@ -22,6 +22,7 @@ const emit = defineEmits<{
}>() }>()
const toast = useToast() const toast = useToast()
const { formatFileSize } = useFileSize() const { formatFileSize } = useFileSize()
const { t, locale } = useI18n() const { t, locale } = useI18n()
const { copyFormat } = useUploadPreferences() const { copyFormat } = useUploadPreferences()
@@ -30,7 +31,7 @@ const naturalWidth = ref<number | null>(null)
const naturalHeight = ref<number | null>(null) const naturalHeight = ref<number | null>(null)
const dimensionsLoaded = ref(false) const dimensionsLoaded = ref(false)
const copyingUrl = ref(false) const copyingUrl = ref(false)
const embedFormat = ref<EmbedFormat>('url') const embedFormat = ref<CopyFormat>('url')
const embedFormatItems = computed(() => [ const embedFormatItems = computed(() => [
{ label: t('copy.url'), value: 'url' as const }, { label: t('copy.url'), value: 'url' as const },
@@ -65,7 +66,7 @@ const sizeLabel = computed(() => {
const bbcodeValue = computed(() => { const bbcodeValue = computed(() => {
if (!props.image) return '' if (!props.image) return ''
return `[img]${props.image.url}[/img]` return buildImageBbcode(props.image.url)
}) })
const previewValue = computed(() => { 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 dimensionsLabel = computed(() => {
const formatted = formatImageDimensions(naturalWidth.value, naturalHeight.value) const formatted = formatImageDimensions(naturalWidth.value, naturalHeight.value)
if (formatted) return formatted if (formatted) return formatted
@@ -128,11 +140,9 @@ watch(() => props.open, (open) => {
} }
}) })
function selectEmbedFormat(value: EmbedFormat) { function selectEmbedFormat(value: CopyFormat) {
embedFormat.value = value embedFormat.value = value
if (value !== 'bbcode') {
copyFormat.value = value copyFormat.value = value
}
} }
async function copyText(text: string, successTitle: string) { async function copyText(text: string, successTitle: string) {
@@ -288,6 +298,32 @@ function onImageLoad(event: Event) {
</span> </span>
</dd> </dd>
</div> </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 <div
v-if="uploadSourceTag" v-if="uploadSourceTag"
class="flex gap-4 py-2.5" class="flex gap-4 py-2.5"
@@ -296,7 +332,14 @@ function onImageLoad(event: Event) {
{{ t('image.previewUploadSource') }} {{ t('image.previewUploadSource') }}
</dt> </dt>
<dd class="min-w-0 flex-1"> <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 }} {{ uploadSourceTag }}
</span> </span>
</dd> </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>
+843
View File
@@ -0,0 +1,843 @@
<script setup lang="ts">
import type { ImageTag } from '~/types/image'
import {
defaultTagColor,
pickDefaultTagColorFromCandidates,
pickTagColorCandidates,
resolveTagHexColor,
TAG_COLOR_EDIT_CANDIDATE_COUNT
} from '~/utils/tag-colors'
const props = withDefaults(defineProps<{
tags: ImageTag[]
embedded?: boolean
}>(), {
embedded: false
})
const emit = defineEmits<{
changed: []
close: []
}>()
const { t, locale } = useI18n()
const toast = useToast()
const { createTag, updateTag, deleteTag, mergeTags } = useTags()
const creating = ref(false)
const newName = ref('')
const newColorCandidates = ref<string[]>(pickTagColorCandidates([]))
const newColor = ref(pickDefaultTagColorFromCandidates(newColorCandidates.value, []))
const search = ref('')
const statusFilter = ref<'all' | 'used' | 'unused'>('all')
const selectedIds = ref<Set<number>>(new Set())
const renamingId = ref<number | null>(null)
const renameValue = ref('')
const colorPickerId = ref<number | null>(null)
const colorValue = ref('#22c55e')
const editColorCandidates = ref<string[]>([])
const mergeOpen = ref(false)
const mergeConfirmOpen = ref(false)
const mergeMode = ref<'batch' | 'single'>('batch')
const mergeSourceIds = ref<number[]>([])
const mergeTargetId = ref<number | null>(null)
const deleteOpen = ref(false)
const deleteTarget = ref<ImageTag | null>(null)
const saving = ref(false)
const page = ref(1)
const pageSize = ref(10)
const stats = computed(() => {
const now = Date.now()
const sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000
let used = 0
let unused = 0
let newIn7Days = 0
for (const tag of props.tags) {
const count = tag.imageCount ?? 0
if (count > 0) used++
else unused++
if (tag.createdAt && new Date(tag.createdAt).getTime() >= sevenDaysAgo) {
newIn7Days++
}
}
return {
total: props.tags.length,
used,
unused,
newIn7Days
}
})
const filteredTags = computed(() => {
const q = search.value.trim().toLowerCase()
return props.tags.filter((tag) => {
if (statusFilter.value === 'used' && (tag.imageCount ?? 0) === 0) return false
if (statusFilter.value === 'unused' && (tag.imageCount ?? 0) > 0) return false
if (q && !tag.name.toLowerCase().includes(q)) return false
return true
}).sort((a, b) => (b.imageCount ?? 0) - (a.imageCount ?? 0) || a.name.localeCompare(b.name))
})
const totalPages = computed(() => Math.max(1, Math.ceil(filteredTags.value.length / pageSize.value)))
const paginatedTags = computed(() => {
const start = (page.value - 1) * pageSize.value
return filteredTags.value.slice(start, start + pageSize.value)
})
watch([search, statusFilter, pageSize], () => {
page.value = 1
})
watch(filteredTags, (list) => {
if (page.value > Math.max(1, Math.ceil(list.length / pageSize.value))) {
page.value = 1
}
})
const selectedList = computed(() =>
[...selectedIds.value]
.map(id => props.tags.find(tag => tag.id === id))
.filter(Boolean) as ImageTag[]
)
const selectedCount = computed(() => selectedIds.value.size)
const allPageSelected = computed(() =>
paginatedTags.value.length > 0
&& paginatedTags.value.every(tag => selectedIds.value.has(tag.id))
)
const mergeSourceTags = computed(() =>
mergeSourceIds.value
.map(id => props.tags.find(tag => tag.id === id))
.filter(Boolean) as ImageTag[]
)
const mergeTargetCandidates = computed(() => {
const sourceSet = new Set(mergeSourceIds.value)
return props.tags
.filter(tag => !sourceSet.has(tag.id))
.sort((a, b) => (b.imageCount ?? 0) - (a.imageCount ?? 0) || a.name.localeCompare(b.name))
})
const mergeTagsToDelete = computed(() => {
if (!mergeTargetId.value) return []
return mergeSourceTags.value.filter(tag => tag.id !== mergeTargetId.value)
})
const mergeKeepTag = computed(() =>
props.tags.find(tag => tag.id === mergeTargetId.value) ?? null
)
const statusItems = computed(() => [
{ label: t('tags.filterStatusAll'), value: 'all' },
{ label: t('tags.filterStatusUsed'), value: 'used' },
{ label: t('tags.filterStatusUnused'), value: 'unused' }
])
const statValueClass = computed(() =>
'mt-2 text-2xl font-semibold tabular-nums text-highlighted'
)
const tableTextClass = computed(() => 'text-sm')
function formatLastUsed(tag: ImageTag) {
if (!tag.lastUsedAt || (tag.imageCount ?? 0) === 0) {
return t('tags.neverUsed')
}
const date = new Date(tag.lastUsedAt)
if (Number.isNaN(date.getTime())) {
return t('tags.neverUsed')
}
return date.toLocaleString(locale.value, {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false
})
}
function toggleSelect(id: number) {
const next = new Set(selectedIds.value)
if (next.has(id)) next.delete(id)
else next.add(id)
selectedIds.value = next
}
function toggleSelectAll() {
const next = new Set(selectedIds.value)
if (allPageSelected.value) {
for (const tag of paginatedTags.value) next.delete(tag.id)
} else {
for (const tag of paginatedTags.value) next.add(tag.id)
}
selectedIds.value = next
}
function clearSelection() {
selectedIds.value = new Set()
}
function usedColorsExcept(tagId?: number) {
return props.tags
.filter(tag => tagId === undefined || tag.id !== tagId)
.map(tag => tag.color)
}
function refreshNewTagColor() {
const used = usedColorsExcept()
newColorCandidates.value = pickTagColorCandidates(used)
newColor.value = pickDefaultTagColorFromCandidates(newColorCandidates.value, used)
}
function toggleCreating() {
if (creating.value) {
creating.value = false
return
}
newName.value = ''
refreshNewTagColor()
creating.value = true
}
async function handleCreate() {
const name = newName.value.trim()
if (!name || saving.value) return
saving.value = true
try {
await createTag(name, newColor.value)
newName.value = ''
creating.value = false
refreshNewTagColor()
emit('changed')
toast.add({ title: t('tags.created', { name }), color: 'success' })
} catch {
toast.add({ title: t('tags.createFailed'), color: 'error' })
} finally {
saving.value = false
}
}
function startRename(tag: ImageTag) {
if (renamingId.value !== null && renamingId.value !== tag.id) {
cancelRename()
}
renamingId.value = tag.id
renameValue.value = tag.name
}
function cancelRename() {
renamingId.value = null
renameValue.value = ''
}
function onRenameBlur(tagId: number) {
window.setTimeout(() => {
if (renamingId.value === tagId) {
void finishRename(tagId)
}
}, 0)
}
async function finishRename(tagId: number) {
if (renamingId.value !== tagId) return
const name = renameValue.value.trim()
const tag = props.tags.find(item => item.id === tagId)
renamingId.value = null
renameValue.value = ''
if (!name || !tag || tag.name === name) return
saving.value = true
try {
await updateTag(tagId, { name })
emit('changed')
toast.add({ title: t('tags.renamed'), color: 'success' })
} catch {
toast.add({ title: t('tags.renameFailed'), color: 'error' })
} finally {
saving.value = false
}
}
function openColorPicker(tag: ImageTag) {
colorPickerId.value = tag.id
colorValue.value = resolveTagHexColor(tag.color, defaultTagColor(tag.id))
editColorCandidates.value = pickTagColorCandidates(
usedColorsExcept(tag.id),
TAG_COLOR_EDIT_CANDIDATE_COUNT
)
}
async function saveColor(tagId: number) {
saving.value = true
try {
await updateTag(tagId, { color: colorValue.value })
colorPickerId.value = null
emit('changed')
} catch {
toast.add({ title: t('tags.colorFailed'), color: 'error' })
} finally {
saving.value = false
}
}
function openDeleteConfirm(tag: ImageTag) {
deleteTarget.value = tag
deleteOpen.value = true
}
async function confirmDelete() {
const tag = deleteTarget.value
if (!tag || saving.value) return
saving.value = true
try {
await deleteTag(tag.id)
deleteOpen.value = false
deleteTarget.value = null
selectedIds.value.delete(tag.id)
selectedIds.value = new Set(selectedIds.value)
emit('changed')
toast.add({ title: t('tags.deleted', { name: tag.name }), color: 'success' })
} catch {
toast.add({ title: t('tags.deleteFailed'), color: 'error' })
} finally {
saving.value = false
}
}
function openBatchMerge() {
if (selectedIds.value.size < 2) {
toast.add({ title: t('tags.mergeSelectAtLeast'), color: 'warning' })
return
}
mergeMode.value = 'batch'
mergeSourceIds.value = [...selectedIds.value]
const sorted = selectedList.value.sort((a, b) => (b.imageCount ?? 0) - (a.imageCount ?? 0))
mergeTargetId.value = sorted[0]?.id ?? null
mergeOpen.value = true
}
function openSingleMerge(tag: ImageTag) {
mergeMode.value = 'single'
mergeSourceIds.value = [tag.id]
const fallback = props.tags
.filter(item => item.id !== tag.id)
.sort((a, b) => (b.imageCount ?? 0) - (a.imageCount ?? 0))[0]
mergeTargetId.value = fallback?.id ?? null
mergeOpen.value = true
}
function requestMergeConfirm() {
if (!mergeTargetId.value) return
const sourceIds = mergeSourceIds.value.filter(id => id !== mergeTargetId.value)
if (!sourceIds.length) return
mergeConfirmOpen.value = true
}
async function confirmMerge() {
if (!mergeTargetId.value || saving.value) return
const sourceIds = mergeSourceIds.value.filter(id => id !== mergeTargetId.value)
if (!sourceIds.length) return
saving.value = true
try {
await mergeTags(sourceIds, mergeTargetId.value)
selectedIds.value = new Set()
mergeConfirmOpen.value = false
mergeOpen.value = false
emit('changed')
toast.add({ title: t('tags.merged'), color: 'success' })
} catch {
toast.add({ title: t('tags.mergeFailed'), color: 'error' })
} finally {
saving.value = false
}
}
</script>
<template>
<div class="space-y-5">
<div class="grid grid-cols-2 gap-3 lg:grid-cols-4">
<div class="rounded-xl border border-default bg-elevated p-4">
<div class="flex items-center gap-2 text-xs text-muted">
<span class="flex size-7 items-center justify-center rounded-lg bg-primary/10 text-primary">
<UIcon
name="i-lucide-tags"
class="size-4"
/>
</span>
{{ t('tags.statTotal') }}
</div>
<p :class="statValueClass">
{{ stats.total }}
</p>
</div>
<div class="rounded-xl border border-default bg-elevated p-4">
<div class="flex items-center gap-2 text-xs text-muted">
<span class="flex size-7 items-center justify-center rounded-lg bg-blue-500/10 text-blue-600 dark:text-blue-400">
<UIcon
name="i-lucide-image"
class="size-4"
/>
</span>
{{ t('tags.statUsed') }}
</div>
<p :class="statValueClass">
{{ stats.used }}
</p>
</div>
<div class="rounded-xl border border-default bg-elevated p-4">
<div class="flex items-center gap-2 text-xs text-muted">
<span class="flex size-7 items-center justify-center rounded-lg bg-orange-500/10 text-orange-600 dark:text-orange-400">
<UIcon
name="i-lucide-tag"
class="size-4"
/>
</span>
{{ t('tags.statUnused') }}
</div>
<p :class="statValueClass">
{{ stats.unused }}
</p>
</div>
<div class="rounded-xl border border-default bg-elevated p-4">
<div class="flex items-center gap-2 text-xs text-muted">
<span class="flex size-7 items-center justify-center rounded-lg bg-violet-500/10 text-violet-600 dark:text-violet-400">
<UIcon
name="i-lucide-trending-up"
class="size-4"
/>
</span>
{{ t('tags.statNew7d') }}
</div>
<p :class="statValueClass">
{{ stats.newIn7Days }}
</p>
</div>
</div>
<div class="flex flex-wrap items-center gap-2">
<UInput
v-model="search"
size="sm"
icon="i-lucide-search"
:placeholder="t('tags.searchName')"
class="min-w-44 flex-1 sm:max-w-xs"
/>
<USelect
v-model="statusFilter"
size="sm"
:items="statusItems"
class="w-32"
/>
<div class="ml-auto flex flex-wrap gap-2">
<UButton
type="button"
size="sm"
color="primary"
icon="i-lucide-plus"
@click="toggleCreating"
>
{{ t('tags.addTag') }}
</UButton>
<UButton
type="button"
size="sm"
variant="outline"
color="neutral"
icon="i-lucide-merge"
:disabled="selectedCount < 2"
@click="openBatchMerge"
>
{{ t('tags.mergeTags') }}
</UButton>
</div>
</div>
<div
v-if="selectedCount > 0"
class="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-primary/25 bg-primary/5 px-3 py-2"
>
<span class="text-xs font-medium text-highlighted">
{{ t('tags.mergeSelected', { n: selectedCount }) }}
</span>
<UButton
size="xs"
variant="ghost"
color="neutral"
@click="clearSelection"
>
{{ t('tags.mergeClear') }}
</UButton>
</div>
<div
v-if="creating"
class="space-y-4 rounded-xl border border-default bg-elevated/50 p-4"
>
<div class="flex flex-wrap items-start gap-3">
<div class="min-w-0 flex-1 space-y-3">
<UInput
v-model="newName"
size="md"
:placeholder="t('tags.namePlaceholder')"
@keydown.enter.prevent="handleCreate"
/>
<TagColorPicker
v-model="newColor"
:candidates="newColorCandidates"
/>
</div>
<div
v-if="newName.trim()"
class="shrink-0 pt-1"
>
<p class="mb-1.5 text-xs text-muted">
{{ t('tags.preview') }}
</p>
<TagBadge
:tag="{ id: 0, name: newName.trim(), color: newColor }"
/>
</div>
</div>
<div class="flex justify-end gap-2 border-t border-default pt-3">
<UButton
size="sm"
variant="ghost"
color="neutral"
@click="() => { creating = false }"
>
{{ t('common.cancel') }}
</UButton>
<UButton
size="sm"
color="primary"
:loading="saving"
:disabled="!newName.trim()"
@click="handleCreate"
>
{{ t('common.save') }}
</UButton>
</div>
</div>
<div class="overflow-hidden rounded-xl border border-default">
<div class="overflow-x-auto">
<table
class="min-w-full"
:class="tableTextClass"
>
<thead class="border-b border-default bg-elevated/60 text-xs text-muted">
<tr>
<th class="w-10 px-3 py-3">
<UCheckbox
:model-value="allPageSelected"
:disabled="!paginatedTags.length"
@update:model-value="toggleSelectAll"
/>
</th>
<th class="px-3 py-3 text-left font-medium">
{{ t('tags.colName') }}
</th>
<th class="px-3 py-3 text-left font-medium">
{{ t('tags.colImageCount') }}
</th>
<th class="px-3 py-3 text-left font-medium">
{{ t('tags.colLastUsed') }}
</th>
<th class="px-3 py-3 text-right font-medium">
{{ t('tags.colActions') }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="tag in paginatedTags"
:key="tag.id"
class="border-b border-default last:border-b-0"
:class="selectedIds.has(tag.id) ? 'bg-primary/5' : 'hover:bg-elevated/40'"
>
<td class="px-3 py-3 align-middle">
<UCheckbox
:model-value="selectedIds.has(tag.id)"
@update:model-value="toggleSelect(tag.id)"
/>
</td>
<td class="px-3 py-3 align-middle">
<UInput
v-if="renamingId === tag.id"
v-model="renameValue"
size="sm"
class="max-w-xs"
autofocus
@keydown.enter.prevent="finishRename(tag.id)"
@keydown.esc.prevent="cancelRename"
@blur="onRenameBlur(tag.id)"
/>
<TagBadge
v-else
:tag="tag"
size="sm"
/>
</td>
<td class="px-3 py-3 align-middle tabular-nums text-muted">
{{ tag.imageCount ?? 0 }}
</td>
<td class="px-3 py-3 align-middle text-muted">
{{ formatLastUsed(tag) }}
</td>
<td class="px-3 py-3 align-middle">
<div class="flex items-center justify-end gap-0.5">
<UButton
type="button"
size="xs"
variant="ghost"
color="primary"
icon="i-lucide-pencil"
:aria-label="t('common.edit')"
@click="startRename(tag)"
/>
<UPopover
:open="colorPickerId === tag.id"
:content="{ side: 'bottom', align: 'end' }"
@update:open="(open) => { colorPickerId = open ? tag.id : null }"
>
<UButton
type="button"
size="xs"
variant="ghost"
color="primary"
icon="i-lucide-palette"
:aria-label="t('tags.pickColor')"
@click="() => openColorPicker(tag)"
/>
<template #content>
<div
class="flex items-center gap-2 p-2"
@click.stop
>
<TagColorPicker
v-model="colorValue"
:candidates="editColorCandidates"
compact
/>
<UButton
icon="i-lucide-check"
size="sm"
color="primary"
class="shrink-0"
:aria-label="t('common.save')"
:loading="saving"
@click="saveColor(tag.id)"
/>
</div>
</template>
</UPopover>
<UButton
type="button"
size="xs"
variant="ghost"
color="primary"
icon="i-lucide-merge"
:aria-label="t('tags.mergeIntoAction')"
:disabled="tags.length < 2"
@click="openSingleMerge(tag)"
/>
<UButton
type="button"
size="xs"
variant="ghost"
color="error"
icon="i-lucide-trash-2"
:aria-label="t('common.delete')"
@click="openDeleteConfirm(tag)"
/>
</div>
</td>
</tr>
<tr v-if="!paginatedTags.length">
<td
colspan="5"
class="px-3 py-12 text-center text-sm text-muted"
>
{{ tags.length ? t('tags.noMatch') : t('tags.emptyHint') }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<PaginationBar
v-if="filteredTags.length > 0"
:page="page"
:total-pages="totalPages"
:total="filteredTags.length"
:page-size="pageSize"
:page-size-options="[10, 20, 30, 50]"
@update:page="(value) => { page = value }"
@update:page-size="(value) => { pageSize = value }"
/>
<UModal
v-model:open="mergeOpen"
:title="mergeMode === 'single' ? t('tags.mergeIntoTitle') : t('tags.mergeTitle')"
:description="mergeMode === 'single'
? t('tags.mergeIntoSubtitle', { name: mergeSourceTags[0]?.name ?? '' })
: t('tags.mergeSubtitle')"
>
<template #body>
<template v-if="mergeMode === 'batch'">
<p class="mb-2 text-sm text-muted">
{{ t('tags.mergeChooseTarget') }}
</p>
<div class="merge-tag-list max-h-[16.5rem] space-y-2 overflow-y-auto">
<label
v-for="tag in mergeSourceTags"
:key="tag.id"
class="flex cursor-pointer items-center gap-3 rounded-lg border border-default px-3 py-2.5 transition-colors"
:class="mergeTargetId === tag.id ? 'border-primary/40 bg-primary/5' : 'hover:bg-elevated'"
>
<input
v-model="mergeTargetId"
type="radio"
:value="tag.id"
class="accent-primary"
>
<TagBadge :tag="tag" />
<span class="ml-auto text-sm text-muted">
{{ t('common.countImages', { count: tag.imageCount ?? 0 }) }}
</span>
</label>
</div>
</template>
<template v-else>
<p class="mb-2 text-sm text-muted">
{{ t('tags.mergeIntoChoose') }}
</p>
<div class="merge-tag-list max-h-[16.5rem] space-y-2 overflow-y-auto">
<label
v-for="tag in mergeTargetCandidates"
:key="tag.id"
class="flex cursor-pointer items-center gap-3 rounded-lg border border-default px-3 py-2.5 transition-colors"
:class="mergeTargetId === tag.id ? 'border-primary/40 bg-primary/5' : 'hover:bg-elevated'"
>
<input
v-model="mergeTargetId"
type="radio"
:value="tag.id"
class="accent-primary"
>
<TagBadge :tag="tag" />
<span class="ml-auto text-sm text-muted">
{{ t('common.countImages', { count: tag.imageCount ?? 0 }) }}
</span>
</label>
</div>
</template>
</template>
<template #footer>
<div class="flex w-full justify-end gap-2">
<UButton
variant="outline"
color="neutral"
@click="() => { mergeOpen = false }"
>
{{ t('common.cancel') }}
</UButton>
<UButton
color="primary"
icon="i-lucide-merge"
:disabled="!mergeTargetId"
@click="requestMergeConfirm"
>
{{ t('tags.mergeConfirm') }}
</UButton>
</div>
</template>
</UModal>
<UModal
v-model:open="mergeConfirmOpen"
:title="t('tags.mergeIrreversibleTitle')"
:description="t('tags.mergeIrreversible')"
>
<template #body>
<div class="space-y-3 text-sm">
<p v-if="mergeKeepTag">
{{ t('tags.mergeConfirmKeep', { name: mergeKeepTag.name }) }}
</p>
<p v-if="mergeTagsToDelete.length">
{{ t('tags.mergeWillDelete', {
names: mergeTagsToDelete.map(tag => tag.name).join('、')
}) }}
</p>
</div>
</template>
<template #footer>
<div class="flex w-full justify-end gap-2">
<UButton
variant="outline"
color="neutral"
@click="() => { mergeConfirmOpen = false }"
>
{{ t('common.cancel') }}
</UButton>
<UButton
color="primary"
icon="i-lucide-merge"
:loading="saving"
@click="confirmMerge"
>
{{ t('tags.mergeConfirm') }}
</UButton>
</div>
</template>
</UModal>
<UModal
v-model:open="deleteOpen"
:title="t('tags.deleteConfirmTitle')"
:description="deleteTarget ? t('tags.deleteConfirmDesc', { name: deleteTarget.name }) : ''"
>
<template #footer>
<div class="flex w-full justify-end gap-2">
<UButton
variant="outline"
color="neutral"
@click="() => { deleteOpen = false }"
>
{{ t('common.cancel') }}
</UButton>
<UButton
color="error"
icon="i-lucide-trash-2"
:loading="saving"
@click="confirmDelete"
>
{{ t('common.delete') }}
</UButton>
</div>
</template>
</UModal>
</div>
</template>
<style scoped>
.merge-tag-list {
scrollbar-width: none;
-ms-overflow-style: none;
}
.merge-tag-list::-webkit-scrollbar {
display: none;
}
</style>
+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(() => [ const copyFormatItems = computed(() => [
{ label: t('copy.url'), value: 'url' as const }, { label: t('copy.url'), value: 'url' as const },
{ label: t('copy.markdown'), value: 'markdown' 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(() => { const clientQualityLevel = computed(() => {
@@ -32,7 +33,7 @@ const clientQualityLevel = computed(() => {
return t('preferences.qualityLow') return t('preferences.qualityLow')
}) })
function setCopyFormat(value: 'url' | 'markdown' | 'html') { function setCopyFormat(value: 'url' | 'markdown' | 'html' | 'bbcode') {
copyFormat.value = value copyFormat.value = value
} }
+42 -1
View File
@@ -5,24 +5,39 @@ const props = withDefaults(defineProps<{
storageBackendItems: Array<{ label: string, value: string }> storageBackendItems: Array<{ label: string, value: string }>
uploadSource: string uploadSource: string
uploadSourceItems: Array<{ label: string, value: 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' viewMode: 'grid' | 'list'
selectedCount?: number selectedCount?: number
loading?: boolean loading?: boolean
showBatchDelete?: boolean showBatchDelete?: boolean
showBatchTags?: boolean
}>(), { }>(), {
selectedCount: 0, selectedCount: 0,
loading: false, loading: false,
showBatchDelete: true showBatchDelete: true,
showBatchTags: false,
tagIds: () => [],
tags: () => [],
tagMode: 'or',
untaggedOnly: false
}) })
const emit = defineEmits<{ const emit = defineEmits<{
'update:searchQuery': [value: string] 'update:searchQuery': [value: string]
'update:storageBackend': [value: string] 'update:storageBackend': [value: string]
'update:uploadSource': [value: string] 'update:uploadSource': [value: string]
'update:tagIds': [value: number[]]
'update:tagMode': [value: 'or' | 'and']
'update:untaggedOnly': [value: boolean]
'update:viewMode': [mode: 'grid' | 'list'] 'update:viewMode': [mode: 'grid' | 'list']
'search': [] 'search': []
'reset': [] 'reset': []
'batch-delete': [] 'batch-delete': []
'batch-tags': []
'manage-tags': []
}>() }>()
const { t } = useI18n() const { t } = useI18n()
@@ -74,6 +89,18 @@ function viewButtonClass(active: boolean) {
@update:model-value="emit('update:uploadSource', $event)" @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 <UButton
type="submit" type="submit"
icon="i-lucide-search" icon="i-lucide-search"
@@ -100,6 +127,20 @@ function viewButtonClass(active: boolean) {
{{ t('stats.resetFilters') }} {{ t('stats.resetFilters') }}
</UButton> </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 <UButton
v-if="showBatchDelete" v-if="showBatchDelete"
type="button" type="button"
+140 -28
View File
@@ -1,16 +1,18 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ImageItem } from '~/types/image' import type { ImageItem, ImageTag } from '~/types/image'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
items: ImageItem[] items: ImageItem[]
selectedKeys: Set<string> selectedKeys: Set<string>
selectable?: boolean selectable?: boolean
showStorage?: boolean showStorage?: boolean
showTags?: boolean
emptyText?: string emptyText?: string
showDelete?: boolean showDelete?: boolean
}>(), { }>(), {
selectable: false, selectable: false,
showStorage: false, showStorage: false,
showTags: false,
showDelete: true showDelete: true
}) })
@@ -18,11 +20,15 @@ const emit = defineEmits<{
'update:selectedKeys': [value: Set<string>] 'update:selectedKeys': [value: Set<string>]
'preview': [image: ImageItem] 'preview': [image: ImageItem]
'delete': [image: ImageItem] 'delete': [image: ImageItem]
'tag-click': [tagId: number]
'untagged-click': []
}>() }>()
const { t } = useI18n() const { t } = useI18n()
const { formatFileSize } = useFileSize() const { formatFileSize } = useFileSize()
const INLINE_TAG_LIMIT = 3
const displayEmptyText = computed(() => props.emptyText ?? t('image.empty')) const displayEmptyText = computed(() => props.emptyText ?? t('image.empty'))
const allSelected = computed(() => const allSelected = computed(() =>
@@ -76,10 +82,33 @@ function sourceLabel(image: ImageItem) {
} }
} }
function typeLabel(image: ImageItem) { function sourceIcon(image: ImageItem) {
if (props.showStorage && image.storage) return image.storage.name switch (image.uploadSource) {
return '—' 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> </script>
<template> <template>
@@ -88,12 +117,12 @@ function typeLabel(image: ImageItem) {
class="overflow-hidden rounded-xl border border-default bg-default" class="overflow-hidden rounded-xl border border-default bg-default"
> >
<div class="overflow-x-auto"> <div class="overflow-x-auto">
<table class="min-w-full text-sm"> <table class="min-w-full text-xs">
<thead class="border-b border-default text-xs text-muted"> <thead class="border-b border-default bg-elevated/40 text-muted">
<tr> <tr>
<th <th
v-if="selectable" 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 <UCheckbox
:model-value="allSelected ? true : headerIndeterminate ? 'indeterminate' : false" :model-value="allSelected ? true : headerIndeterminate ? 'indeterminate' : false"
@@ -101,22 +130,31 @@ function typeLabel(image: ImageItem) {
@update:model-value="toggleAll" @update:model-value="toggleAll"
/> />
</th> </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') }} {{ t('stats.colFilename') }}
</th> </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') }} {{ t('stats.colSource') }}
</th> </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') }} {{ t('stats.colSize') }}
</th> </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') }} {{ t('stats.colType') }}
</th> </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') }} {{ t('stats.colUploadedAt') }}
</th> </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') }} {{ t('stats.colActions') }}
</th> </th>
</tr> </tr>
@@ -125,22 +163,23 @@ function typeLabel(image: ImageItem) {
<tr <tr
v-for="image in items" v-for="image in items"
:key="image.key" :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 <td
v-if="selectable" v-if="selectable"
class="px-4 py-3" class="px-3 py-2"
> >
<UCheckbox <UCheckbox
:model-value="selectedKeys.has(image.key)" :model-value="selectedKeys.has(image.key)"
@update:model-value="updateSelection(image.key, $event === true)" @update:model-value="updateSelection(image.key, $event === true)"
/> />
</td> </td>
<td class="px-4 py-3"> <td class="px-3 py-2.5">
<div class="flex min-w-0 items-center gap-3"> <div class="flex min-w-0 items-center gap-3">
<button <button
type="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')" :aria-label="t('image.openPreview')"
@click="emit('preview', image)" @click="emit('preview', image)"
> >
@@ -152,35 +191,108 @@ function typeLabel(image: ImageItem) {
> >
</button> </button>
<p <p
class="min-w-0 flex-1 truncate font-medium" class="min-w-0 flex-1 truncate text-highlighted"
:title="image.originalName" :title="image.originalName"
> >
{{ image.originalName }} {{ image.originalName }}
</p> </p>
</div> </div>
</td> </td>
<td class="hidden px-4 py-3 sm:table-cell"> <td class="hidden px-3 py-2 sm:table-cell">
<span <span
v-if="sourceLabel(image)" v-if="sourceLabel(image) && sourceIcon(image)"
class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary" :class="metaBadgeClass"
> >
{{ sourceLabel(image) }} <UIcon
:name="sourceIcon(image)!"
class="size-3 shrink-0"
/>
<span class="truncate">{{ sourceLabel(image) }}</span>
</span> </span>
<span <span
v-else v-else
class="text-muted" class="text-muted"
>—</span> >—</span>
</td> </td>
<td class="px-4 py-3 text-muted"> <td class="px-3 py-2 tabular-nums text-muted">
{{ formatFileSize(image.size) }} {{ formatFileSize(image.size) }}
</td> </td>
<td class="hidden px-4 py-3 text-muted md:table-cell"> <td
<span class="truncate">{{ typeLabel(image) }}</span> 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>
<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) }} {{ formatUploadedAt(image.uploadedAt) }}
</td> </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"> <div class="flex items-center justify-end gap-0.5 text-muted">
<CopyButton <CopyButton
icon="i-lucide-link" icon="i-lucide-link"
@@ -217,7 +329,7 @@ function typeLabel(image: ImageItem) {
</div> </div>
<div <div
v-else 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 }} {{ displayEmptyText }}
</div> </div>
+1 -1
View File
@@ -1,5 +1,5 @@
<template> <template>
<div class="divide-y divide-default overflow-hidden rounded-lg border border-default"> <div class="divide-y divide-default">
<slot /> <slot />
</div> </div>
</template> </template>
+196 -193
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <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 { isAuthenticated, handleAuthError, isAdmin } = useAuth()
const toast = useToast() const toast = useToast()
@@ -8,36 +8,30 @@ const { formatFileSize } = useFileSize()
const loading = ref(true) const loading = ref(true)
const page = ref(1) const page = ref(1)
const pageSize = ref(10)
const actionFilter = ref<'all' | LogAction>('all') const actionFilter = ref<'all' | LogAction>('all')
const sourceFilter = ref<'all' | LogSource>('all') const sourceFilter = ref<'all' | LogSource>('all')
const userFilter = ref<'all' | number>('all') const userFilter = ref<'all' | number>('all')
const dateFrom = ref('')
const dateTo = ref('')
const searchQuery = ref('') const searchQuery = ref('')
const activeSearch = ref('') const activeSearch = ref('')
const listData = ref<ActivityLogListResponse | null>(null) 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(() => [ const actionItems = computed(() => [
{ label: t('logs.filterActionAll'), value: 'all' as const }, { label: t('logs.filterActionAll'), value: 'all' as const },
{ label: t('logs.actionUpload'), value: 'upload' 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(() => [ const sourceItems = computed(() => [
{ label: t('logs.filterSourceAll'), value: 'all' as const }, { label: t('logs.filterSourceAll'), value: 'all' as const },
{ label: t('logs.sourceWeb'), value: 'web' 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 } { 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) { 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' const base = 'inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs font-medium whitespace-nowrap'
return action === 'upload' switch (action) {
? `${base} bg-success/10 text-success` case 'upload':
: `${base} bg-error/10 text-error` 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) { 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) { function sourceLabel(source: LogSource) {
switch (source) { switch (source) {
case 'web': case 'web':
return t('logs.sourceWeb') return t('logs.sourceWeb')
case 'admin':
return t('logs.sourceAdmin')
case 'api': case 'api':
return t('logs.sourceApi') return t('logs.sourceApi')
} }
} }
function storageIcon(storage: ActivityLogStorage | null) { function sourceBadgeClass(source: LogSource) {
return storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud' const base = 'inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs font-medium whitespace-nowrap'
switch (source) {
case 'web':
return `${base} bg-primary/10 text-primary`
case 'admin':
return `${base} bg-orange-500/10 text-orange-600 dark:text-orange-400`
case 'api':
return `${base} bg-violet-500/10 text-violet-600 dark:text-violet-400`
}
} }
function publicPathFromKey(key: string) { function statusLabel(status: LogStatus) {
if (hideFolderInUrl.value) { return status === 'failure' ? t('logs.resultFailure') : t('logs.resultSuccess')
const slash = key.lastIndexOf('/')
return slash >= 0 ? key.slice(slash + 1) : key
}
const prefix = 'images/'
return key.startsWith(prefix) ? key.slice(prefix.length) : key
} }
function imageUrl(key: string) { function statusDotClass(status: LogStatus) {
const base = imageLinkBase.value.replace(/\/$/, '') return status === 'failure' ? 'bg-error' : 'bg-success'
const path = publicPathFromKey(key)
if (!base) return `/${path}`
return `${base}/${path}`
} }
async function loadImageLinkBase() { function formatIp(value: string | null) {
try { if (!value || value === '-') return '—'
if (isAdmin.value) { return value
const data = await $fetch<{ effectiveImageBaseUrl: string, hideFolderInUrl: boolean }>('/api/settings', { }
credentials: 'include'
}) function formatSize(action: LogAction, size: number) {
imageLinkBase.value = data.effectiveImageBaseUrl if (action !== 'upload' && action !== 'delete') return '—'
hideFolderInUrl.value = data.hideFolderInUrl if (action === 'delete' && size <= 0) return '—'
return return formatFileSize(size)
}
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
}
}
} }
async function loadLogs() { async function loadLogs() {
@@ -140,7 +172,7 @@ async function loadLogs() {
try { try {
const query: Record<string, string | number> = { const query: Record<string, string | number> = {
page: page.value, page: page.value,
limit: pageSize limit: pageSize.value
} }
if (actionFilter.value !== 'all') { if (actionFilter.value !== 'all') {
query.action = actionFilter.value query.action = actionFilter.value
@@ -154,6 +186,12 @@ async function loadLogs() {
if (activeSearch.value) { if (activeSearch.value) {
query.q = 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', { listData.value = await $fetch<ActivityLogListResponse>('/api/logs', {
credentials: 'include', credentials: 'include',
@@ -191,21 +229,32 @@ function handlePageChange(target: number) {
void loadLogs() void loadLogs()
} }
onMounted(async () => { function handlePageSizeChange(size: number) {
await loadImageLinkBase() pageSize.value = size
await loadLogs() page.value = 1
void loadLogs()
}
onMounted(() => {
void loadLogs()
}) })
</script> </script>
<template> <template>
<div class="min-w-0"> <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 class="mb-6 flex items-start justify-between gap-4">
<div> <div class="min-w-0">
<h2 class="text-sm font-semibold"> <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') }} {{ t('logs.pageTitle') }}
</h2> </h2>
<p class="mt-0.5 text-xs text-muted"> </div>
{{ isAdmin ? t('logs.pageSubtitleAdmin') : t('logs.pageSubtitle') }} <p class="mt-1.5 pl-3 text-xs leading-relaxed text-muted">
{{ isAdmin ? t('settings.pageSubtitleLogs') : t('logs.pageSubtitle') }}
</p> </p>
</div> </div>
<UButton <UButton
@@ -215,35 +264,45 @@ onMounted(async () => {
size="sm" size="sm"
:label="t('common.refresh')" :label="t('common.refresh')"
:loading="loading" :loading="loading"
class="shrink-0"
@click="loadLogs" @click="loadLogs"
/> />
</div> </div>
<form <form
class="border-b border-default px-5 py-3 sm:px-6" class="mb-4 flex flex-col gap-3"
@submit.prevent="submitSearch" @submit.prevent="submitSearch"
> >
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between"> <div class="flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
<p <div class="flex min-w-0 flex-wrap items-center gap-2">
v-if="summaryLabel" <UInput
class="text-xs text-muted" v-model="dateFrom"
> type="date"
{{ summaryLabel }} size="sm"
</p> class="min-w-0 w-full sm:w-36"
<p :aria-label="t('logs.dateFrom')"
v-else :disabled="loading"
class="text-xs text-muted" @change="applyFilters"
> />
{{ t('stats.counting') }} <span class="hidden text-xs text-muted sm:inline">{{ t('logs.dateRangeSeparator') }}</span>
</p> <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 <USelect
v-if="isAdmin" v-if="isAdmin"
v-model="userFilter" v-model="userFilter"
:items="userItems" :items="userItems"
value-key="value" value-key="value"
class="min-w-0 w-full sm:w-36" class="min-w-0 w-full sm:w-32"
size="sm" size="sm"
@update:model-value="applyFilters" @update:model-value="applyFilters"
/> />
@@ -251,7 +310,7 @@ onMounted(async () => {
v-model="actionFilter" v-model="actionFilter"
:items="actionItems" :items="actionItems"
value-key="value" 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" size="sm"
@update:model-value="applyFilters" @update:model-value="applyFilters"
/> />
@@ -259,7 +318,7 @@ onMounted(async () => {
v-model="sourceFilter" v-model="sourceFilter"
:items="sourceItems" :items="sourceItems"
value-key="value" 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" size="sm"
@update:model-value="applyFilters" @update:model-value="applyFilters"
/> />
@@ -268,19 +327,17 @@ onMounted(async () => {
v-model="searchQuery" v-model="searchQuery"
icon="i-lucide-search" icon="i-lucide-search"
:placeholder="t('logs.searchPlaceholder')" :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" size="sm"
:disabled="loading" :disabled="loading"
/> />
<UButton <UButton
type="submit" type="submit"
icon="i-lucide-search"
size="sm" size="sm"
class="shrink-0" class="shrink-0"
:aria-label="t('common.search')"
:loading="loading" :loading="loading"
> >
<span class="hidden sm:inline">{{ t('common.search') }}</span> {{ t('common.search') }}
</UButton> </UButton>
<UButton <UButton
v-if="activeSearch" v-if="activeSearch"
@@ -292,14 +349,13 @@ onMounted(async () => {
class="shrink-0" class="shrink-0"
:aria-label="t('stats.clear')" :aria-label="t('stats.clear')"
@click="clearSearch" @click="clearSearch"
> />
<span class="hidden sm:inline">{{ t('stats.clear') }}</span>
</UButton>
</div> </div>
</div> </div>
</div> </div>
</form> </form>
<div class="overflow-hidden rounded-xl border border-default bg-default">
<div <div
v-if="loading" v-if="loading"
class="p-4 sm:p-6" class="p-4 sm:p-6"
@@ -333,7 +389,7 @@ onMounted(async () => {
{{ formatTimeShort(row.createdAt) }} {{ formatTimeShort(row.createdAt) }}
</time> </time>
<span class="shrink-0 text-xs tabular-nums text-muted"> <span class="shrink-0 text-xs tabular-nums text-muted">
{{ formatFileSize(row.size) }} {{ formatSize(row.action, row.size) }}
</span> </span>
</div> </div>
@@ -343,9 +399,13 @@ onMounted(async () => {
:name="actionIcon(row.action)" :name="actionIcon(row.action)"
class="size-3 shrink-0" class="size-3 shrink-0"
/> />
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }} {{ actionLabel(row.action) }}
</span> </span>
<span class="inline-flex items-center rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary whitespace-nowrap"> <span :class="sourceBadgeClass(row.source)">
<UIcon
:name="sourceIcon(row.source)"
class="size-3 shrink-0"
/>
{{ sourceLabel(row.source) }} {{ sourceLabel(row.source) }}
</span> </span>
<span <span
@@ -354,19 +414,6 @@ onMounted(async () => {
> >
{{ row.username ?? '—' }} {{ row.username ?? '—' }}
</span> </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> </div>
<p <p
@@ -376,67 +423,50 @@ onMounted(async () => {
{{ row.originalName }} {{ row.originalName }}
</p> </p>
<div class="mt-2 flex min-w-0 items-center gap-1"> <div class="mt-2 flex items-center justify-between gap-2 text-xs text-muted">
<a <span>{{ formatIp(row.ipAddress) }}</span>
v-if="row.action === 'upload'" <span class="inline-flex items-center gap-1.5">
: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 <span
v-else class="size-1.5 rounded-full"
class="min-w-0 flex-1 truncate font-mono text-xs text-dimmed" :class="statusDotClass(row.status)"
: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')"
/> />
{{ statusLabel(row.status) }}
</span>
</div> </div>
</article> </article>
</div> </div>
</div> </div>
<div class="hidden min-w-0 sm:block"> <div class="hidden min-w-0 overflow-x-auto sm:block">
<table class="w-full table-fixed text-left text-sm"> <table class="w-full min-w-[56rem] text-left text-sm">
<thead class="border-b border-default bg-muted/30 text-xs text-muted"> <thead class="border-b border-default bg-muted/30 text-xs text-muted">
<tr> <tr>
<th class="w-36 px-4 py-3 font-medium sm:px-6"> <th class="whitespace-nowrap px-4 py-3 font-medium sm:px-5">
{{ t('logs.colTime') }} {{ t('logs.colTime') }}
</th> </th>
<th <th
v-if="isAdmin" v-if="isAdmin"
class="w-20 px-4 py-3 font-medium" class="whitespace-nowrap px-4 py-3 font-medium"
> >
{{ t('logs.colUser') }} {{ t('logs.colUser') }}
</th> </th>
<th class="w-20 whitespace-nowrap px-4 py-3 font-medium"> <th class="whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colAction') }} {{ t('logs.colAction') }}
</th> </th>
<th class="w-16 whitespace-nowrap px-4 py-3 font-medium"> <th class="whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colSource') }} {{ t('logs.colSource') }}
</th> </th>
<th class="w-24 px-4 py-3 font-medium"> <th class="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') }} {{ t('logs.colFile') }}
</th> </th>
<th class="w-20 px-4 py-3 font-medium"> <th class="whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colSize') }} {{ t('logs.colSize') }}
</th> </th>
<th class="hidden px-4 py-3 font-medium xl:table-cell"> <th class="whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colKey') }} {{ t('logs.colIp') }}
</th>
<th class="whitespace-nowrap px-4 py-3 font-medium sm:px-5">
{{ t('logs.colResult') }}
</th> </th>
</tr> </tr>
</thead> </thead>
@@ -446,14 +476,14 @@ onMounted(async () => {
:key="row.id" :key="row.id"
class="hover:bg-muted/20" class="hover:bg-muted/20"
> >
<td class="px-4 py-3 text-xs text-muted sm:px-6"> <td class="whitespace-nowrap px-4 py-3 text-xs text-muted sm:px-5">
<span class="block truncate">{{ formatTime(row.createdAt) }}</span> {{ formatTime(row.createdAt) }}
</td> </td>
<td <td
v-if="isAdmin" v-if="isAdmin"
class="px-4 py-3 text-xs" class="whitespace-nowrap px-4 py-3 text-xs"
> >
<span class="block truncate">{{ row.username ?? '—' }}</span> {{ row.username ?? '—' }}
</td> </td>
<td class="whitespace-nowrap px-4 py-3"> <td class="whitespace-nowrap px-4 py-3">
<span :class="actionBadgeClass(row.action)"> <span :class="actionBadgeClass(row.action)">
@@ -461,68 +491,38 @@ onMounted(async () => {
:name="actionIcon(row.action)" :name="actionIcon(row.action)"
class="size-3 shrink-0" class="size-3 shrink-0"
/> />
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }} {{ actionLabel(row.action) }}
</span> </span>
</td> </td>
<td class="whitespace-nowrap px-4 py-3"> <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) }} {{ sourceLabel(row.source) }}
</span> </span>
</td> </td>
<td class="px-4 py-3 text-xs">
<span
v-if="row.storage"
class="flex min-w-0 items-center gap-1"
:title="row.storage.name"
>
<UIcon
:name="storageIcon(row.storage)"
class="size-3.5 shrink-0 opacity-70"
/>
<span class="truncate">{{ row.storage.name }}</span>
</span>
<span
v-else
class="text-muted"
>—</span>
</td>
<td <td
class="hidden max-w-0 truncate px-4 py-3 md:table-cell" class="max-w-[12rem] truncate px-4 py-3"
:title="row.originalName" :title="row.originalName"
> >
{{ row.originalName }} {{ row.originalName }}
</td> </td>
<td class="whitespace-nowrap px-4 py-3 tabular-nums text-muted"> <td class="whitespace-nowrap px-4 py-3 tabular-nums text-muted">
{{ formatFileSize(row.size) }} {{ formatSize(row.action, row.size) }}
</td> </td>
<td class="hidden max-w-0 px-4 py-3 xl:table-cell"> <td class="whitespace-nowrap px-4 py-3 font-mono text-xs text-muted">
<div class="flex min-w-0 items-center gap-1"> {{ formatIp(row.ipAddress) }}
<a </td>
v-if="row.action === 'upload'" <td class="whitespace-nowrap px-4 py-3 sm:px-5">
:href="imageUrl(row.key)" <span class="inline-flex items-center gap-1.5 text-xs">
target="_blank"
rel="noopener noreferrer"
class="min-w-0 truncate font-mono text-xs text-primary hover:underline"
:title="row.key"
>
{{ row.key }}
</a>
<span <span
v-else class="size-1.5 rounded-full"
class="min-w-0 truncate font-mono text-xs text-dimmed" :class="statusDotClass(row.status)"
: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> {{ statusLabel(row.status) }}
</span>
</td> </td>
</tr> </tr>
</tbody> </tbody>
@@ -539,16 +539,19 @@ onMounted(async () => {
<div <div
v-if="listData && listData.total > 0" v-if="listData && listData.total > 0"
class="border-t border-default px-4 py-4 sm:px-6" class="border-t border-default px-4 py-4 sm:px-5"
> >
<PaginationBar <PaginationBar
:page="listData.page" :page="listData.page"
:total-pages="listData.totalPages" :total-pages="listData.totalPages"
:total="listData.total" :total="listData.total"
:unit="t('logs.entriesUnit')" :unit="t('logs.entriesUnit')"
:page-size="pageSize"
:loading="loading" :loading="loading"
@update:page="handlePageChange" @update:page="handlePageChange"
@update:page-size="handlePageSizeChange"
/> />
</div> </div>
</div> </div>
</div>
</template> </template>
@@ -0,0 +1,29 @@
<script setup lang="ts">
defineProps<{
icon: string
title: string
subtitle?: string
}>()
</script>
<template>
<header class="mb-0 flex items-start gap-3 border-b border-default pb-6">
<div class="flex size-10 shrink-0 items-center justify-center rounded-xl bg-primary/10">
<UIcon
:name="icon"
class="size-5 text-primary"
/>
</div>
<div class="min-w-0 pt-0.5">
<h1 class="text-lg font-semibold tracking-tight text-highlighted">
{{ title }}
</h1>
<p
v-if="subtitle"
class="mt-1 text-xs leading-relaxed text-muted"
>
{{ subtitle }}
</p>
</div>
</header>
</template>
+1 -3
View File
@@ -1,7 +1,5 @@
<template> <template>
<div class="overflow-hidden rounded-xl border border-default bg-default p-5 sm:p-6"> <div class="mt-6 space-y-4">
<div class="space-y-8">
<slot /> <slot />
</div> </div>
</div>
</template> </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>
+4 -2
View File
@@ -6,8 +6,8 @@ defineProps<{
</script> </script>
<template> <template>
<section class="space-y-4"> <section class="overflow-hidden rounded-xl border border-default bg-default">
<div class="flex items-start justify-between gap-4"> <div class="flex items-start justify-between gap-4 px-4 py-3">
<div class="min-w-0"> <div class="min-w-0">
<div class="flex items-center gap-2"> <div class="flex items-center gap-2">
<span <span
@@ -32,6 +32,8 @@ defineProps<{
<slot name="action" /> <slot name="action" />
</div> </div>
</div> </div>
<div class="border-t border-default px-4">
<slot /> <slot />
</div>
</section> </section>
</template> </template>
@@ -6,6 +6,7 @@ defineProps<{
const emit = defineEmits<{ const emit = defineEmits<{
save: [] save: []
restore: []
}>() }>()
const { t } = useI18n() const { t } = useI18n()
@@ -13,13 +14,19 @@ const { t } = useI18n()
<template> <template>
<div class="border-t border-default bg-default px-4 py-4 sm:px-6"> <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 <p
v-if="hasChanges" v-if="hasChanges"
class="mr-auto text-xs text-warning" class="mr-auto text-xs text-warning"
> >
{{ t('settings.unsavedChanges') }} {{ t('settings.unsavedChanges') }}
</p> </p>
<UButton
:label="t('settings.restoreDefaults')"
color="neutral"
variant="outline"
@click="emit('restore')"
/>
<UButton <UButton
:label="t('settings.saveSettings')" :label="t('settings.saveSettings')"
icon="i-lucide-save" icon="i-lucide-save"
+40 -12
View File
@@ -1,39 +1,67 @@
<script setup lang="ts"> <script setup lang="ts">
import type { SettingsTab } from '~/types/settings' import type { SettingsTab } from '~/types/settings'
defineProps<{ const props = defineProps<{
modelValue: SettingsTab modelValue: SettingsTab
items: Array<{ id: SettingsTab, label: string, icon: string }> items: Array<{ id: SettingsTab, label: string, icon: string }>
title: string
subtitle: string
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
'update:modelValue': [SettingsTab] '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> </script>
<template> <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"> <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"> <div class="border-b border-default p-3">
<h1 class="text-lg font-semibold tracking-tight text-highlighted"> <UInput
{{ title }} v-model="searchQuery"
</h1> size="sm"
<p class="mt-1 text-xs leading-relaxed text-muted"> :placeholder="t('settings.searchPlaceholder')"
{{ subtitle }} icon="i-lucide-search"
</p> class="w-full"
>
<template #trailing>
<UKbd
size="sm"
class="hidden sm:inline-flex"
>
⌘K
</UKbd>
</template>
</UInput>
</div> </div>
<nav class="flex-1 space-y-0.5 p-3"> <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 <button
v-for="item in items" v-for="item in filteredItems"
:key="item.id" :key="item.id"
type="button" 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="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 :class="modelValue === item.id
? 'bg-primary/10 font-medium text-primary' ? 'bg-primary/10 font-medium text-primary'
: 'text-muted hover:bg-muted/50 hover:text-highlighted'" : 'text-muted hover:bg-muted/50 hover:text-highlighted'"
@click="emit('update:modelValue', item.id)" @click="selectTab(item.id)"
> >
<UIcon <UIcon
:name="item.icon" :name="item.icon"
+39 -7
View File
@@ -4,32 +4,64 @@ defineProps<{
updateAvailable: boolean updateAvailable: boolean
latestVersion: string | null latestVersion: string | null
releaseUrl: string | null releaseUrl: string | null
checking: boolean
}>()
const emit = defineEmits<{
checkUpdate: []
}>() }>()
const { t } = useI18n() const { t } = useI18n()
</script> </script>
<template> <template>
<div class="pl-3"> <div class="flex flex-wrap items-center justify-between gap-4 py-4">
<div class="flex flex-wrap items-center gap-2"> <div class="min-w-0">
<span class="text-sm font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('settings.systemVersion') }} {{ 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> </span>
<UBadge <UBadge
color="neutral" v-if="updateAvailable && latestVersion"
color="warning"
variant="subtle" variant="subtle"
size="sm" size="sm"
> >
v{{ appVersion }} {{ t('settings.updateAvailable', { version: `v${latestVersion}` }) }}
</UBadge> </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 <a
v-if="updateAvailable && latestVersion" v-if="updateAvailable && latestVersion"
:href="releaseUrl || 'https://github.com/O96u/PicHost/releases'" :href="releaseUrl || 'https://github.com/O96u/PicHost/releases'"
target="_blank" target="_blank"
rel="noopener noreferrer" 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> </a>
</div> </div>
</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> </script>
<template> <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"> <div class="min-w-0 flex-1 pr-2">
<p class="text-sm font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
<slot name="title"> <slot name="title">
@@ -19,16 +19,11 @@ const {
const copyFormatItems = computed(() => [ const copyFormatItems = computed(() => [
{ label: t('copy.url'), value: 'url' as const }, { label: t('copy.url'), value: 'url' as const },
{ label: t('copy.markdown'), value: 'markdown' 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(() => { function setCopyFormat(value: 'url' | 'markdown' | 'html' | 'bbcode') {
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') {
copyFormat.value = value copyFormat.value = value
} }
@@ -37,6 +32,11 @@ function onClientQualityInput(event: Event) {
clientWebpQuality.value = Number.isFinite(value) ? value : 80 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(() => { onMounted(() => {
loadPreferences() loadPreferences()
void loadUserSettings() void loadUserSettings()
@@ -53,7 +53,7 @@ onMounted(() => {
/> />
<div <div
v-if="userSettings" v-if="userSettings"
class="flex items-start justify-between gap-4 px-4 py-4 sm:px-5" class="flex items-start justify-between gap-4 py-4"
> >
<div class="min-w-0 flex-1 pr-2"> <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"> <p class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm font-medium text-highlighted">
@@ -87,9 +87,8 @@ onMounted(() => {
class="size-5 animate-spin text-muted" class="size-5 animate-spin text-muted"
/> />
</div> </div>
<div class="px-4 py-4 sm:px-5"> <div class="py-4">
<div class="flex items-start justify-between gap-4"> <div class="min-w-0">
<div class="min-w-0 flex-1">
<p class="text-sm font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('preferences.webpQuality') }} {{ t('preferences.webpQuality') }}
</p> </p>
@@ -97,45 +96,52 @@ onMounted(() => {
{{ t('preferences.webpQualityHint') }} {{ t('preferences.webpQualityHint') }}
</p> </p>
</div> </div>
<div class="shrink-0 text-right text-xs text-muted"> <div class="mt-3 flex items-center gap-3">
<p>{{ t('preferences.current', { n: clientWebpQuality }) }}</p>
<p class="mt-0.5">
{{ clientQualityLevel }}
</p>
</div>
</div>
<input <input
type="range" type="range"
min="1" min="1"
max="100" max="100"
:value="clientWebpQuality" :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" @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>
</div> </div>
</SettingsGroup> </SettingsGroup>
</SettingsSection> </SettingsSection>
<SettingsSection :title="t('settings.uploadConvenience')"> <SettingsSection :title="t('preferences.title')">
<SettingsGroup> <SettingsGroup>
<SettingsToggleRow <SettingsToggleRow
v-model="autoCopyMarkdown" v-model="autoCopyMarkdown"
:title="t('preferences.autoCopy')" :title="t('preferences.autoCopy')"
:hint="t('preferences.autoCopyHint')" :hint="t('preferences.autoCopyHint')"
/> />
<div class="flex flex-col gap-3 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5"> <div class="py-4">
<p class="text-sm font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('settings.defaultCopyFormat') }} {{ t('settings.defaultCopyFormat') }}
</p> </p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('settings.defaultCopyFormatHint') }}
</p>
<div <div
class="flex w-full max-w-xs gap-1 rounded-lg border border-default p-0.5 sm:w-auto" class="mt-3 flex w-full max-w-md gap-1 rounded-lg border border-default p-0.5"
:class="autoCopyMarkdown ? '' : 'pointer-events-none opacity-40'" :class="autoCopyMarkdown ? '' : 'pointer-events-none opacity-40'"
> >
<UButton <UButton
v-for="item in copyFormatItems" v-for="item in copyFormatItems"
:key="item.value" :key="item.value"
size="xs" size="xs"
class="flex-1 justify-center sm:min-w-[4.5rem]" class="flex-1 justify-center"
:variant="copyFormat === item.value ? 'solid' : 'ghost'" :variant="copyFormat === item.value ? 'solid' : 'ghost'"
:color="copyFormat === item.value ? 'primary' : 'neutral'" :color="copyFormat === item.value ? 'primary' : 'neutral'"
:label="item.label" :label="item.label"
+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>
@@ -5,6 +5,8 @@ const props = defineProps<{
backend: StorageBackendItem backend: StorageBackendItem
envOverride?: boolean envOverride?: boolean
busy?: boolean busy?: boolean
showMigrateIn?: boolean
showMigrateOut?: boolean
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
@@ -13,6 +15,8 @@ const emit = defineEmits<{
test: [] test: []
toggleEnabled: [] toggleEnabled: []
delete: [] delete: []
migrateIn: []
migrateOut: []
}>() }>()
const { t } = useI18n() const { t } = useI18n()
@@ -129,6 +133,28 @@ function canDelete() {
:disabled="actionsDisabled" :disabled="actionsDisabled"
@click="emit('setDefault')" @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 <UButton
v-if="canEdit()" v-if="canEdit()"
:label="t('common.edit')" :label="t('common.edit')"
@@ -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>
+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 activeStorageBackend = ref('all')
const activeContentType = ref('all') const activeContentType = ref('all')
const activeUploadSource = 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 }>>([]) const storageBackendOptions = ref<Array<{ id: string, name: string }>>([])
function storageQueryParams(): Record<string, string> { function storageQueryParams(): Record<string, string> {
@@ -38,6 +41,14 @@ export function useImageList() {
if (uploadSource && uploadSource !== 'all') { if (uploadSource && uploadSource !== 'all') {
params.uploadSource = uploadSource 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 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() { async function resetFilters() {
searchQuery.value = '' searchQuery.value = ''
activeSearch.value = '' activeSearch.value = ''
activeStorageBackend.value = 'all' activeStorageBackend.value = 'all'
activeContentType.value = 'all' activeContentType.value = 'all'
activeUploadSource.value = 'all' activeUploadSource.value = 'all'
activeTagIds.value = []
activeTagMode.value = 'or'
activeUntaggedOnly.value = false
page.value = 1 page.value = 1
await Promise.all([fetchList(1), fetchTotal()]) await Promise.all([fetchList(1), fetchTotal()])
} }
@@ -278,6 +325,12 @@ export function useImageList() {
return t('stats.summaryTotal', { total: count }) 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 { return {
items, items,
page, page,
@@ -288,6 +341,9 @@ export function useImageList() {
activeStorageBackend, activeStorageBackend,
activeContentType, activeContentType,
activeUploadSource, activeUploadSource,
activeTagIds,
activeTagMode,
activeUntaggedOnly,
storageBackendOptions, storageBackendOptions,
searchQuery, searchQuery,
activeSearch, activeSearch,
@@ -300,12 +356,16 @@ export function useImageList() {
setActiveStorageBackend, setActiveStorageBackend,
setActiveContentType, setActiveContentType,
setActiveUploadSource, setActiveUploadSource,
setActiveTagFilter,
toggleTagFilter,
resetFilters, resetFilters,
loadStorageBackendOptions, loadStorageBackendOptions,
submitSearch, submitSearch,
goToPage, goToPage,
setPageSize, setPageSize,
prependItems, prependItems,
removeItems removeItems,
updateItemTags,
listQueryParams
} }
} }
+8 -2
View File
@@ -10,14 +10,14 @@ const MAX_FILES = 10
export function useImageUpload() { export function useImageUpload() {
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
const { compressEnabled, clientWebpQuality } = useUploadPreferences() const { compressEnabled, clientWebpQuality, lastTagIds } = useUploadPreferences()
const uploading = ref(false) const uploading = ref(false)
const progressItems = ref<UploadProgressItem[]>([]) const progressItems = ref<UploadProgressItem[]>([])
const lastUploadResult = ref<UploadResponse | null>(null) const lastUploadResult = ref<UploadResponse | null>(null)
async function uploadFiles( async function uploadFiles(
files: File[], files: File[],
options?: { notify?: boolean } options?: { notify?: boolean, tagIds?: number[] }
) { ) {
if (uploading.value) return if (uploading.value) return
@@ -58,6 +58,12 @@ export function useImageUpload() {
formData.append('files', file, file.name) formData.append('files', file, file.name)
} }
const tagIds = options?.tagIds ?? lastTagIds.value
if (tagIds.length) {
formData.append('tagIds', JSON.stringify(tagIds))
lastTagIds.value = tagIds
}
const response = await $fetch<UploadResponse>('/api/images/upload', { const response = await $fetch<UploadResponse>('/api/images/upload', {
method: 'POST', method: 'POST',
body: formData 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' const STORAGE_KEY = 'pichost.upload-preferences'
export type CopyFormat = 'url' | 'markdown' | 'html' export type CopyFormat = 'url' | 'markdown' | 'html' | 'bbcode'
export interface UploadPreferences { export interface UploadPreferences {
compressEnabled: boolean compressEnabled: boolean
autoCopyMarkdown: boolean autoCopyMarkdown: boolean
copyFormat: CopyFormat copyFormat: CopyFormat
clientWebpQuality: number clientWebpQuality: number
lastTagIds: number[]
} }
const DEFAULTS: UploadPreferences = { const DEFAULTS: UploadPreferences = {
compressEnabled: false, compressEnabled: false,
autoCopyMarkdown: false, autoCopyMarkdown: false,
copyFormat: 'markdown', copyFormat: 'markdown',
clientWebpQuality: 80 clientWebpQuality: 80,
lastTagIds: []
} }
function clampQuality(value: unknown): number { function clampQuality(value: unknown): number {
@@ -23,7 +25,7 @@ function clampQuality(value: unknown): number {
} }
function isCopyFormat(value: unknown): value is CopyFormat { function isCopyFormat(value: unknown): value is CopyFormat {
return value === 'url' || value === 'markdown' || value === 'html' return value === 'url' || value === 'markdown' || value === 'html' || value === 'bbcode'
} }
function readStored(): UploadPreferences { function readStored(): UploadPreferences {
@@ -37,7 +39,10 @@ function readStored(): UploadPreferences {
compressEnabled: parsed.compressEnabled === true, compressEnabled: parsed.compressEnabled === true,
autoCopyMarkdown: parsed.autoCopyMarkdown === true, autoCopyMarkdown: parsed.autoCopyMarkdown === true,
copyFormat: isCopyFormat(parsed.copyFormat) ? parsed.copyFormat : DEFAULTS.copyFormat, 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 { } catch {
return { ...DEFAULTS } return { ...DEFAULTS }
@@ -54,6 +59,7 @@ export function useUploadPreferences() {
const autoCopyMarkdown = useState('upload-pref-auto-md', () => DEFAULTS.autoCopyMarkdown) const autoCopyMarkdown = useState('upload-pref-auto-md', () => DEFAULTS.autoCopyMarkdown)
const copyFormat = useState<CopyFormat>('upload-pref-copy-format', () => DEFAULTS.copyFormat) const copyFormat = useState<CopyFormat>('upload-pref-copy-format', () => DEFAULTS.copyFormat)
const clientWebpQuality = useState('upload-pref-webp-quality', () => DEFAULTS.clientWebpQuality) 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) const loaded = useState('upload-pref-loaded', () => false)
function loadPreferences() { function loadPreferences() {
@@ -62,6 +68,7 @@ export function useUploadPreferences() {
autoCopyMarkdown.value = stored.autoCopyMarkdown autoCopyMarkdown.value = stored.autoCopyMarkdown
copyFormat.value = stored.copyFormat copyFormat.value = stored.copyFormat
clientWebpQuality.value = stored.clientWebpQuality clientWebpQuality.value = stored.clientWebpQuality
lastTagIds.value = stored.lastTagIds
loaded.value = true loaded.value = true
} }
@@ -74,11 +81,20 @@ export function useUploadPreferences() {
compressEnabled: compressEnabled.value, compressEnabled: compressEnabled.value,
autoCopyMarkdown: autoCopyMarkdown.value, autoCopyMarkdown: autoCopyMarkdown.value,
copyFormat: copyFormat.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) { if (loaded.value) {
savePreferences() savePreferences()
} }
@@ -89,8 +105,10 @@ export function useUploadPreferences() {
autoCopyMarkdown, autoCopyMarkdown,
copyFormat, copyFormat,
clientWebpQuality, clientWebpQuality,
lastTagIds,
loaded, loaded,
loadPreferences, loadPreferences,
savePreferences savePreferences,
resetToDefaults
} }
} }
+112 -3
View File
@@ -46,9 +46,17 @@ const {
activeUploadSource, activeUploadSource,
setActiveUploadSource, setActiveUploadSource,
resetFilters, resetFilters,
loadStorageBackendOptions loadStorageBackendOptions,
activeTagIds,
activeTagMode,
activeUntaggedOnly,
setActiveTagFilter,
toggleTagFilter,
listQueryParams
} = useImageList() } = useImageList()
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth() const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth()
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
@@ -66,6 +74,7 @@ const showScrollTop = ref(false)
const previewOpen = ref(false) const previewOpen = ref(false)
const previewImage = ref<ImageItem | null>(null) const previewImage = ref<ImageItem | null>(null)
const viewMode = ref<'grid' | 'list'>('grid') const viewMode = ref<'grid' | 'list'>('grid')
const batchTagOpen = ref(false)
const currentUploadSource = ref('all') const currentUploadSource = ref('all')
const currentStorageBackend = ref('all') const currentStorageBackend = ref('all')
@@ -96,7 +105,8 @@ function scrollToTop() {
async function fetchStats() { async function fetchStats() {
stats.value = await $fetch<StatsResponse>('/api/stats', { stats.value = await $fetch<StatsResponse>('/api/stats', {
credentials: 'include' credentials: 'include',
query: listQueryParams()
}) })
} }
@@ -131,7 +141,8 @@ async function refreshAll() {
await Promise.all([ await Promise.all([
fetchStats(), fetchStats(),
reloadGallery(), reloadGallery(),
loadStorageBackendOptions() loadStorageBackendOptions(),
fetchTags()
]) ])
currentUploadSource.value = activeUploadSource.value currentUploadSource.value = activeUploadSource.value
currentStorageBackend.value = activeStorageBackend.value currentStorageBackend.value = activeStorageBackend.value
@@ -174,11 +185,85 @@ async function handleResetFilters() {
currentStorageBackend.value = 'all' currentStorageBackend.value = 'all'
try { try {
await resetFilters() await resetFilters()
await fetchStats()
} catch (error: unknown) { } catch (error: unknown) {
handleAuthError(error) 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: t('tags.batchFailed'), color: 'error' })
}
}
function goToTagSettings() {
void navigateTo({ path: '/settings', query: { tab: 'tags' } })
}
function updateSelectedKeys(keys: Set<string>) { function updateSelectedKeys(keys: Set<string>) {
selectedKeys.value = keys selectedKeys.value = keys
} }
@@ -398,16 +483,26 @@ watch(isAuthenticated, async (authed, prev) => {
:storage-backend-items="storageBackendItems" :storage-backend-items="storageBackendItems"
:upload-source="currentUploadSource" :upload-source="currentUploadSource"
:upload-source-items="uploadSourceItems" :upload-source-items="uploadSourceItems"
:tag-ids="activeTagIds"
:tag-mode="activeTagMode"
:untagged-only="activeUntaggedOnly"
:tags="tagItems"
:view-mode="viewMode" :view-mode="viewMode"
:selected-count="selectedCount" :selected-count="selectedCount"
:loading="galleryLoading" :loading="galleryLoading"
:show-batch-delete="true" :show-batch-delete="true"
:show-batch-tags="selectedCount > 0"
@update:storage-backend="handleStorageBackendChange" @update:storage-backend="handleStorageBackendChange"
@update:upload-source="handleUploadSourceChange" @update:upload-source="handleUploadSourceChange"
@update:tag-ids="handleTagIdsChange"
@update:tag-mode="handleTagModeChange"
@update:untagged-only="handleUntaggedOnlyChange"
@update:view-mode="viewMode = $event" @update:view-mode="viewMode = $event"
@search="handleSearch" @search="handleSearch"
@reset="handleResetFilters" @reset="handleResetFilters"
@batch-delete="requestBatchDelete" @batch-delete="requestBatchDelete"
@batch-tags="batchTagOpen = true"
@manage-tags="goToTagSettings"
/> />
</div> </div>
@@ -429,6 +524,7 @@ watch(isAuthenticated, async (authed, prev) => {
gallery gallery
:show-key="false" :show-key="false"
show-storage show-storage
show-tags
:items="items" :items="items"
:selected-keys="selectedKeys" :selected-keys="selectedKeys"
:selectable="true" :selectable="true"
@@ -436,11 +532,14 @@ watch(isAuthenticated, async (authed, prev) => {
@update:selected-keys="updateSelectedKeys" @update:selected-keys="updateSelectedKeys"
@preview="openPreview" @preview="openPreview"
@delete="(image) => requestDelete(image.key)" @delete="(image) => requestDelete(image.key)"
@tag-click="handleTagFilterClick"
@untagged-click="handleUntaggedFilterClick"
/> />
<GalleryImageList <GalleryImageList
v-else v-else
show-storage show-storage
show-tags
:items="items" :items="items"
:selected-keys="selectedKeys" :selected-keys="selectedKeys"
:selectable="true" :selectable="true"
@@ -448,12 +547,15 @@ watch(isAuthenticated, async (authed, prev) => {
@update:selected-keys="updateSelectedKeys" @update:selected-keys="updateSelectedKeys"
@preview="openPreview" @preview="openPreview"
@delete="(image) => requestDelete(image.key)" @delete="(image) => requestDelete(image.key)"
@tag-click="handleTagFilterClick"
@untagged-click="handleUntaggedFilterClick"
/> />
<ImagePreviewModal <ImagePreviewModal
v-model:open="previewOpen" v-model:open="previewOpen"
:image="previewImage" :image="previewImage"
show-storage show-storage
show-tags
:deleting="previewImage ? deletingKeys.has(previewImage.key) : false" :deleting="previewImage ? deletingKeys.has(previewImage.key) : false"
:allow-delete="true" :allow-delete="true"
@delete="requestPreviewDelete" @delete="requestPreviewDelete"
@@ -479,6 +581,13 @@ watch(isAuthenticated, async (authed, prev) => {
@confirm="confirmDelete" @confirm="confirmDelete"
/> />
<BatchTagModal
v-model:open="batchTagOpen"
:tags="tagItems"
:selected-count="selectedCount"
@confirm="confirmBatchTags"
/>
<UButton <UButton
v-show="showScrollTop" v-show="showScrollTop"
icon="i-lucide-arrow-up" icon="i-lucide-arrow-up"
+84 -2
View File
@@ -1,5 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ImageItem } from '~/types/image' import type { ImageItem, ImageTag } from '~/types/image'
import { buildImageBbcode } from '~/utils/image-display'
const { uploading, progressItems, uploadFiles } = useImageUpload() const { uploading, progressItems, uploadFiles } = useImageUpload()
@@ -9,6 +10,9 @@ const {
loadPreferences loadPreferences
} = useUploadPreferences() } = useUploadPreferences()
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
const { recordRecent } = useRecentTags()
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth() const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth()
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
@@ -17,6 +21,9 @@ const deletingKeys = ref<Set<string>>(new Set())
const emptySelection = ref(new Set<string>()) const emptySelection = ref(new Set<string>())
const previewOpen = ref(false) const previewOpen = ref(false)
const previewImage = ref<ImageItem | null>(null) const previewImage = ref<ImageItem | null>(null)
const tagModalOpen = ref(false)
const tagModalImage = ref<ImageItem | null>(null)
const batchTagOpen = ref(false)
const showProgress = computed( const showProgress = computed(
() => () =>
@@ -47,7 +54,7 @@ onMounted(async () => {
await checkSession() await checkSession()
} }
if (isAuthenticated.value) { if (isAuthenticated.value) {
await loadPage() await Promise.all([loadPage(), fetchTags()])
} }
}) })
@@ -66,6 +73,8 @@ function copyFormatLabel() {
return t('copy.url') return t('copy.url')
case 'html': case 'html':
return t('copy.html') return t('copy.html')
case 'bbcode':
return t('copy.bbcode')
default: default:
return t('copy.markdown') return t('copy.markdown')
} }
@@ -108,6 +117,8 @@ async function handleUpload(files: File[]) {
? first.url ? first.url
: copyFormat.value === 'html' : copyFormat.value === 'html'
? first.html ? first.html
: copyFormat.value === 'bbcode'
? buildImageBbcode(first.url)
: first.markdown : first.markdown
if (text) await copyUploadLink(text) if (text) await copyUploadLink(text)
} }
@@ -148,6 +159,50 @@ function requestPreviewDelete() {
if (!previewImage.value) return if (!previewImage.value) return
void handleDelete(previewImage.value.key) 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> </script>
<template> <template>
@@ -189,6 +244,14 @@ function requestPreviewDelete() {
{{ t('upload.sessionTitle') }} {{ t('upload.sessionTitle') }}
<span class="ml-1 text-sm font-normal text-muted">({{ sessionItems.length }})</span> <span class="ml-1 text-sm font-normal text-muted">({{ sessionItems.length }})</span>
</h2> </h2>
<UButton
icon="i-lucide-tags"
variant="outline"
color="primary"
size="sm"
:label="t('tags.batchTagAll')"
@click="() => { batchTagOpen = true }"
/>
</div> </div>
<ImageGrid <ImageGrid
@@ -196,9 +259,13 @@ function requestPreviewDelete() {
:selected-keys="emptySelection" :selected-keys="emptySelection"
:selectable="false" :selectable="false"
:show-key="false" :show-key="false"
:allow-delete="true"
show-tag-action
:empty-text="t('upload.sessionEmpty')" :empty-text="t('upload.sessionEmpty')"
@update:selected-keys="() => {}" @update:selected-keys="() => {}"
@preview="openPreview" @preview="openPreview"
@delete="(image) => handleDelete(image.key)"
@edit-tags="openTagModal"
/> />
</section> </section>
@@ -209,6 +276,21 @@ function requestPreviewDelete() {
:allow-delete="true" :allow-delete="true"
@delete="requestPreviewDelete" @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> </AppShell>
</div> </div>
</template> </template>
+161 -124
View File
@@ -2,6 +2,7 @@
import type { SettingsTab } from '~/types/settings' import type { SettingsTab } from '~/types/settings'
import { ADMIN_SETTINGS_TABS, USER_SETTINGS_TABS } from '~/types/settings' import { ADMIN_SETTINGS_TABS, USER_SETTINGS_TABS } from '~/types/settings'
import { willActivateDomainSeparation } from '~/utils/domain-separation' import { willActivateDomainSeparation } from '~/utils/domain-separation'
import SettingsUserPreferencesFields from '~/components/settings/SettingsUserPreferencesFields.vue'
type SettingSource = 'env' | 'db' | 'none' type SettingSource = 'env' | 'db' | 'none'
type WebpQualitySource = 'env' | 'db' | 'default' type WebpQualitySource = 'env' | 'db' | 'default'
@@ -51,7 +52,7 @@ const router = useRouter()
const allowedTabs = computed(() => (isAdmin.value ? ADMIN_SETTINGS_TABS : USER_SETTINGS_TABS)) 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 { function parseTab(value: unknown): SettingsTab | null {
if (typeof value !== 'string') return null if (typeof value !== 'string') return null
@@ -69,26 +70,53 @@ const activeTab = computed<SettingsTab>({
const sidebarItems = computed(() => { const sidebarItems = computed(() => {
const labels: Record<SettingsTab, { label: string, icon: string }> = { 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' }, domains: { label: t('settings.navDomains'), icon: 'i-lucide-globe' },
access: { label: t('settings.navAccess'), icon: 'i-lucide-shield' }, 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' } logs: { label: t('settings.navLogs'), icon: 'i-lucide-scroll-text' }
} }
return allowedTabs.value.map(id => ({ id, ...labels[id] })) 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(() => const showSaveBar = computed(() =>
isAdmin.value && ['basic', 'domains', 'access'].includes(activeTab.value) 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 checkingRelease = ref(false)
const { resetToDefaults: resetUploadPreferences } = useUploadPreferences()
const { load: reloadUserSettings } = useUserAutoDeleteSettings()
const domainSeparationDocUrl = computed(() => const domainSeparationDocUrl = computed(() =>
locale.value === 'en' locale.value === 'en'
@@ -339,21 +367,33 @@ async function checkLatestRelease(options: { notify?: boolean, refresh?: boolean
} }
const loginVerificationOptions = computed(() => [ const loginVerificationOptions = computed(() => [
{ value: 'slider' as const, label: t('settings.loginVerificationSlider') }, {
{ value: 'turnstile' as const, label: t('settings.loginVerificationTurnstile') }, value: 'slider' as const,
{ value: 'cap' as const, label: t('settings.loginVerificationCap') } 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(() => { function restoreDefaults() {
switch (loginVerificationMethodDraft.value) { if (activeTab.value === 'basic') {
case 'turnstile': resetUploadPreferences()
return t('settings.loginVerificationTurnstileHint') void reloadUserSettings()
case 'cap':
return t('settings.loginVerificationCapHint')
default:
return t('settings.loginVerificationSliderHint')
} }
}) if (settings.value) {
applySettings(settings.value)
}
toast.add({ title: t('settings.restoredDefaults'), color: 'success' })
}
async function loadPage() { async function loadPage() {
if (isAdmin.value) { if (isAdmin.value) {
@@ -427,23 +467,22 @@ watch(isAdmin, () => {
<SettingsSidebar <SettingsSidebar
v-model="activeTab" v-model="activeTab"
:items="sidebarItems" :items="sidebarItems"
:title="t('settings.pageTitle')"
:subtitle="pageSubtitle"
/> />
<div class="flex min-w-0 flex-1 flex-col bg-default"> <div class="flex min-w-0 flex-1 flex-col bg-default">
<div <div class="flex-1 p-5 text-sm sm:p-6">
class="flex-1" <SettingsPageHeader
:class="activeTab === 'logs' ? '' : 'p-4 sm:p-5'" v-if="activeTab !== 'logs'"
> :icon="tabPageHeader.icon"
:title="tabPageHeader.title"
:subtitle="tabPageHeader.subtitle"
/>
<div <div
v-if="activeTab === 'basic' && isAdmin" v-if="activeTab === 'basic' && isAdmin"
> >
<SettingsPanel v-if="settings"> <SettingsPanel v-if="settings">
<SettingsSection <SettingsSection :title="t('settings.featureToggles')">
:title="t('settings.featureToggles')"
:hint="t('settings.featureTogglesHint')"
>
<SettingsGroup> <SettingsGroup>
<SettingsToggleRow <SettingsToggleRow
v-model="allowRegistrationDraft" v-model="allowRegistrationDraft"
@@ -455,31 +494,17 @@ watch(isAdmin, () => {
<SettingsUserPreferencesFields /> <SettingsUserPreferencesFields />
<SettingsSection <SettingsSection :title="t('settings.systemInfo')">
:title="t('settings.systemInfo')" <SettingsGroup>
:hint="t('settings.systemInfoHint')"
>
<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 })"
/>
</template>
<SettingsSystemInfo <SettingsSystemInfo
:app-version="settings.appVersion" :app-version="settings.appVersion"
:update-available="!!releaseCheck?.updateAvailable" :update-available="!!releaseCheck?.updateAvailable"
:latest-version="releaseCheck?.latestVersion ?? null" :latest-version="releaseCheck?.latestVersion ?? null"
:release-url="releaseCheck?.releaseUrl ?? null" :release-url="releaseCheck?.releaseUrl ?? null"
:checking="checkingRelease"
@check-update="checkLatestRelease({ notify: true, refresh: true })"
/> />
</SettingsGroup>
</SettingsSection> </SettingsSection>
</SettingsPanel> </SettingsPanel>
<div <div
@@ -498,50 +523,60 @@ watch(isAdmin, () => {
> >
<SettingsPanel v-if="settings"> <SettingsPanel v-if="settings">
<SettingsSection :title="t('settings.domainSettings')"> <SettingsSection :title="t('settings.domainSettings')">
<div class="divide-y divide-default">
<p <p
v-if="settings.runtime.currentOrigin" v-if="settings.runtime.currentOrigin"
class="mb-3 pl-3 text-xs text-primary" 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 }) }} {{ t('settings.runtimeDetected', { url: settings.runtime.currentOrigin }) }}
</span>
</p> </p>
<SettingsGroup>
<SettingsToggleRow <SettingsToggleRow
:model-value="domainSeparationDraft" :model-value="domainSeparationDraft"
:title="t('setup.domainSeparation')" :title="t('setup.domainSeparation')"
:hint="t('setup.domainSeparationHint')" :hint="t('setup.domainSeparationHint')"
@update:model-value="onDomainSeparationDraftChange" @update:model-value="onDomainSeparationDraftChange"
/> />
</SettingsGroup> <div
</SettingsSection>
<p
v-if="domainSeparationDraft" v-if="domainSeparationDraft"
class="rounded-xl border border-warning/25 bg-warning/5 px-4 py-3 text-xs leading-relaxed text-warning" class="py-4"
> >
{{ t('setup.domainSeparationProxyHint') }} <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 <a
:href="domainSeparationDocUrl" :href="domainSeparationDocUrl"
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
class="text-primary hover:underline" class="shrink-0 text-xs text-primary hover:underline sm:pt-0.5"
> >
{{ t('setup.domainSeparationProxyExample') }} {{ t('setup.domainSeparationProxyExample') }} →
</a> </a>
</p> </div>
<UAlert <UAlert
v-if="domainSeparationDraft && settings.runtime.hostRole === 'unknown'" v-if="settings.runtime.hostRole === 'unknown'"
color="warning" color="warning"
variant="subtle" variant="subtle"
icon="i-lucide-triangle-alert" icon="i-lucide-triangle-alert"
:title="t('settings.hostRoleUnknown')" :title="t('settings.hostRoleUnknown')"
class="mb-4" class="mt-4"
/> />
</div>
</div>
</SettingsSection>
<SettingsSection <SettingsSection :title="t('settings.pathAndLink')">
:title="t('settings.pathAndLink')"
:hint="t('settings.pathAndLinkHint')"
>
<SettingsGroup> <SettingsGroup>
<SettingsToggleRow <SettingsToggleRow
:model-value="hideFolderInUrlDraft" :model-value="hideFolderInUrlDraft"
@@ -590,33 +625,34 @@ watch(isAdmin, () => {
</SettingsGroup> </SettingsGroup>
</SettingsSection> </SettingsSection>
<SettingsSection :title="t('settings.imageBaseUrl')"> <SettingsSection :title="t('settings.imageDomainSection')">
<div <div
v-if="domainSeparationDraft" 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> <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"> <div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('settings.siteBaseUrl') }} {{ t('settings.siteBaseUrl') }}
</p> </p>
<UBadge <UBadge
:color="sourceBadge(settings.siteBaseUrlSource).color" color="success"
variant="subtle" variant="subtle"
size="xs" size="xs"
> >
{{ sourceBadge(settings.siteBaseUrlSource).label }} {{ t('settings.badgeEnabled') }}
</UBadge> </UBadge>
</div> </div>
<p class="text-xs leading-relaxed text-muted"> <p class="text-xs leading-relaxed text-muted">
{{ t('settings.siteBaseUrlHint') }} {{ t('settings.siteBaseUrlRoleHint') }}
</p> </p>
<div class="flex gap-2"> <div class="flex gap-2">
<UInput <UInput
v-model="siteBaseUrlDraft" v-model="siteBaseUrlDraft"
size="sm"
:placeholder="t('settings.siteBaseUrlPlaceholder')" :placeholder="t('settings.siteBaseUrlPlaceholder')"
class="min-w-0 flex-1 font-mono text-sm" class="min-w-0 flex-1 font-mono"
/> />
<UButton <UButton
v-if="settings.runtime.currentOrigin" v-if="settings.runtime.currentOrigin"
@@ -630,7 +666,7 @@ watch(isAdmin, () => {
</div> </div>
<p <p
v-if="settings.effectiveSiteBaseUrl" 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" :title="settings.effectiveSiteBaseUrl"
> >
{{ t('settings.siteBaseUrlActive', { url: settings.effectiveSiteBaseUrl }) }} {{ t('settings.siteBaseUrlActive', { url: settings.effectiveSiteBaseUrl }) }}
@@ -639,30 +675,31 @@ watch(isAdmin, () => {
</SettingsGroup> </SettingsGroup>
<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"> <div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('settings.imageBaseUrl') }} {{ t('settings.imageBaseUrl') }}
</p> </p>
<UBadge <UBadge
:color="sourceBadge(settings.imageBaseUrlSource).color" color="success"
variant="subtle" variant="subtle"
size="xs" size="xs"
> >
{{ sourceBadge(settings.imageBaseUrlSource).label }} {{ t('settings.badgeEnabled') }}
</UBadge> </UBadge>
</div> </div>
<p class="text-xs leading-relaxed text-muted"> <p class="text-xs leading-relaxed text-muted">
{{ t('settings.imageBaseUrlHint') }} {{ t('settings.imageBaseUrlRoleHint') }}
</p> </p>
<UInput <UInput
v-model="imageBaseUrlDraft" v-model="imageBaseUrlDraft"
size="sm"
:placeholder="t('settings.imageBaseUrlPlaceholder')" :placeholder="t('settings.imageBaseUrlPlaceholder')"
class="w-full font-mono text-sm" class="w-full font-mono"
/> />
<p <p
v-if="settings.effectiveImageBaseUrl" 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" :title="settings.effectiveImageBaseUrl"
> >
{{ t('settings.imageBaseUrlActive', { url: settings.effectiveImageBaseUrl }) }} {{ t('settings.imageBaseUrlActive', { url: settings.effectiveImageBaseUrl }) }}
@@ -672,7 +709,7 @@ watch(isAdmin, () => {
</div> </div>
<SettingsGroup v-else> <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"> <div class="flex flex-wrap items-center gap-2">
<p class="text-sm font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('settings.imageBaseUrl') }} {{ t('settings.imageBaseUrl') }}
@@ -698,12 +735,13 @@ watch(isAdmin, () => {
</p> </p>
<UInput <UInput
v-model="imageBaseUrlDraft" v-model="imageBaseUrlDraft"
size="sm"
:placeholder="t('settings.imageBaseUrlPlaceholder')" :placeholder="t('settings.imageBaseUrlPlaceholder')"
class="w-full font-mono text-sm" class="w-full font-mono"
/> />
<p <p
v-if="settings.effectiveImageBaseUrl" 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" :title="settings.effectiveImageBaseUrl"
> >
{{ t('settings.imageBaseUrlActive', { url: settings.effectiveImageBaseUrl }) }} {{ t('settings.imageBaseUrlActive', { url: settings.effectiveImageBaseUrl }) }}
@@ -728,18 +766,11 @@ watch(isAdmin, () => {
class="settings-referer-section" class="settings-referer-section"
> >
<SettingsPanel v-if="settings"> <SettingsPanel v-if="settings">
<div class="flex items-start gap-3"> <SettingsPlainSection
<div class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10"> :title="t('settings.refererProtection')"
<UIcon :hint="t('settings.refererHint')"
name="i-lucide-shield" >
class="size-4 text-primary" <template #badge>
/>
</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 <UBadge
:color="refererDraft.trim() ? 'success' : 'neutral'" :color="refererDraft.trim() ? 'success' : 'neutral'"
variant="subtle" variant="subtle"
@@ -747,24 +778,20 @@ watch(isAdmin, () => {
> >
{{ refererDraft.trim() ? t('settings.refererEnabled') : t('settings.refererUnrestricted') }} {{ refererDraft.trim() ? t('settings.refererEnabled') : t('settings.refererUnrestricted') }}
</UBadge> </UBadge>
</div> </template>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('settings.refererHint') }}
</p>
</div>
</div>
<div class="mt-5 grid gap-5 lg:grid-cols-[minmax(0,1fr)_12rem] xl:grid-cols-[minmax(0,1fr)_14rem]"> <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-2"> <div class="min-w-0 space-y-3">
<label class="text-sm font-medium text-highlighted"> <label class="block text-sm font-medium text-highlighted">
{{ t('settings.refererDomainsLabel') }} {{ t('settings.refererDomainsLabel') }}
</label> </label>
<UTextarea <UTextarea
v-model="refererDraft" v-model="refererDraft"
size="sm"
:placeholder="t('settings.refererPlaceholder')" :placeholder="t('settings.refererPlaceholder')"
:rows="7" :rows="7"
:autoresize="false" :autoresize="false"
class="settings-referer-field w-full font-mono text-sm" class="settings-referer-field w-full font-mono"
/> />
<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"> <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 <UIcon
@@ -775,9 +802,9 @@ watch(isAdmin, () => {
</div> </div>
</div> </div>
<div class="space-y-3 border-l border-default pl-4"> <div class="space-y-4 border-l border-default pl-4">
<div> <div>
<p class="text-xs font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('settings.refererExamplesTitle') }} {{ t('settings.refererExamplesTitle') }}
</p> </p>
<p class="mt-2 font-mono text-xs text-muted"> <p class="mt-2 font-mono text-xs text-muted">
@@ -785,41 +812,43 @@ watch(isAdmin, () => {
</p> </p>
</div> </div>
<div> <div>
<p class="text-xs font-medium text-highlighted"> <p class="text-sm font-medium text-highlighted">
{{ t('settings.refererScenarioTitle') }} {{ t('settings.refererScenarioTitle') }}
</p> </p>
<p class="mt-1 text-xs leading-relaxed text-muted"> <ul class="mt-2 list-disc space-y-1 pl-4 text-xs leading-relaxed text-muted">
{{ t('settings.refererScenarioDesc') }} <li>{{ t('settings.refererScenario1') }}</li>
</p> <li>{{ t('settings.refererScenario2') }}</li>
<li>{{ t('settings.refererScenario3') }}</li>
<li>{{ t('settings.refererScenario4') }}</li>
</ul>
</div> </div>
</div> </div>
</div> </div>
</SettingsPlainSection>
<SettingsSection <SettingsSection
:title="t('settings.loginVerification')" :title="t('settings.loginVerification')"
:hint="t('settings.loginVerificationHint')" :hint="t('settings.loginVerificationHint')"
> >
<SettingsGroup> <SettingsGroup>
<div class="space-y-4 px-4 py-4 sm:px-5"> <SettingsRadioGroup
<URadioGroup
v-model="loginVerificationMethodDraft" v-model="loginVerificationMethodDraft"
:items="loginVerificationOptions" :items="loginVerificationOptions"
/> />
<p class="text-xs leading-relaxed text-muted">
{{ loginVerificationHint }}
</p>
<div <div
v-if="loginVerificationMethodDraft === 'turnstile'" v-if="loginVerificationMethodDraft === 'turnstile'"
class="space-y-3 rounded-xl border border-default bg-muted/20 p-4" class="py-4"
> >
<div class="space-y-3 rounded-xl border border-default bg-muted/20 p-4">
<div class="space-y-2"> <div class="space-y-2">
<label class="text-sm font-medium text-highlighted"> <label class="text-sm font-medium text-highlighted">
{{ t('settings.turnstileSiteKey') }} {{ t('settings.turnstileSiteKey') }}
</label> </label>
<UInput <UInput
v-model="turnstileSiteKeyDraft" v-model="turnstileSiteKeyDraft"
size="sm"
:placeholder="t('settings.turnstileSiteKeyPlaceholder')" :placeholder="t('settings.turnstileSiteKeyPlaceholder')"
class="w-full font-mono text-sm" class="w-full font-mono"
/> />
</div> </div>
<div class="space-y-2"> <div class="space-y-2">
@@ -829,23 +858,27 @@ watch(isAdmin, () => {
<UInput <UInput
v-model="turnstileSecretKeyDraft" v-model="turnstileSecretKeyDraft"
type="password" type="password"
size="sm"
:placeholder="t('settings.turnstileSecretKeyPlaceholder')" :placeholder="t('settings.turnstileSecretKeyPlaceholder')"
class="w-full font-mono text-sm" class="w-full font-mono"
/> />
</div> </div>
</div> </div>
</div>
<div <div
v-else-if="loginVerificationMethodDraft === 'cap'" v-else-if="loginVerificationMethodDraft === 'cap'"
class="space-y-3 rounded-xl border border-default bg-muted/20 p-4" class="py-4"
> >
<div class="space-y-3 rounded-xl border border-default bg-muted/20 p-4">
<div class="space-y-2"> <div class="space-y-2">
<label class="text-sm font-medium text-highlighted"> <label class="text-sm font-medium text-highlighted">
{{ t('settings.capApiEndpoint') }} {{ t('settings.capApiEndpoint') }}
</label> </label>
<UInput <UInput
v-model="capApiEndpointDraft" v-model="capApiEndpointDraft"
size="sm"
:placeholder="t('settings.capApiEndpointPlaceholder')" :placeholder="t('settings.capApiEndpointPlaceholder')"
class="w-full font-mono text-sm" class="w-full font-mono"
/> />
</div> </div>
<div class="space-y-2"> <div class="space-y-2">
@@ -855,8 +888,9 @@ watch(isAdmin, () => {
<UInput <UInput
v-model="capSecretDraft" v-model="capSecretDraft"
type="password" type="password"
size="sm"
:placeholder="t('settings.capSecretKeyPlaceholder')" :placeholder="t('settings.capSecretKeyPlaceholder')"
class="w-full font-mono text-sm" class="w-full font-mono"
/> />
</div> </div>
</div> </div>
@@ -875,6 +909,8 @@ watch(isAdmin, () => {
</div> </div>
</div> </div>
<SettingsTagsPanel v-else-if="activeTab === 'tags'" />
<SettingsLogsPanel v-else-if="activeTab === 'logs'" /> <SettingsLogsPanel v-else-if="activeTab === 'logs'" />
</div> </div>
@@ -883,6 +919,7 @@ watch(isAdmin, () => {
:has-changes="hasServerChanges" :has-changes="hasServerChanges"
:saving="savingServer" :saving="savingServer"
@save="saveServerSettings" @save="saveServerSettings"
@restore="restoreDefaults"
/> />
</div> </div>
</div> </div>
+175
View File
@@ -29,6 +29,93 @@ const imageBaseUrl = ref('')
const loading = ref(false) const loading = ref(false)
const domainSeparationConfirmOpen = 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(() => const domainSeparationWouldActivate = computed(() =>
willActivateDomainSeparation( willActivateDomainSeparation(
domainSeparation.value, domainSeparation.value,
@@ -149,7 +236,28 @@ async function performSubmit() {
</div> </div>
</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 <form
v-if="setupMode === 'init'"
class="flex w-full flex-col gap-5" class="flex w-full flex-col gap-5"
@submit.prevent="submit" @submit.prevent="submit"
> >
@@ -269,6 +377,73 @@ async function performSubmit() {
:disabled="!canSubmit" :disabled="!canSubmit"
/> />
</form> </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> </div>
<UModal <UModal
+57
View File
@@ -21,6 +21,53 @@ const deleteTarget = ref<StorageBackendItem | null>(null)
const deleteConfirmName = ref('') const deleteConfirmName = ref('')
const deleting = ref(false) 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 defaultBackendName = computed(() => {
const backend = storageData.value?.backends.find(item => item.isDefault) const backend = storageData.value?.backends.find(item => item.isDefault)
return backend?.name ?? t('storage.backendLocal') return backend?.name ?? t('storage.backendLocal')
@@ -297,14 +344,24 @@ watch(isAuthenticated, async (authed) => {
:backend="backend" :backend="backend"
:env-override="storageData.envOverride" :env-override="storageData.envOverride"
:busy="busyId === backend.id" :busy="busyId === backend.id"
:show-migrate-in="showMigrateIn(backend)"
:show-migrate-out="showMigrateOut(backend)"
@set-default="setDefault(backend)" @set-default="setDefault(backend)"
@edit="openEdit(backend)" @edit="openEdit(backend)"
@test="testBackend(backend)" @test="testBackend(backend)"
@toggle-enabled="toggleEnabled(backend)" @toggle-enabled="toggleEnabled(backend)"
@delete="confirmDelete(backend)" @delete="confirmDelete(backend)"
@migrate-in="onMigrateIn(backend)"
@migrate-out="onMigrateOut(backend)"
/> />
</div> </div>
<StorageBackupPanel
v-if="!storageData.envOverride"
ref="backupPanelRef"
:backends="storageData.backends"
/>
<StorageSupportedBackends /> <StorageSupportedBackends />
</template> </template>
</section> </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
}
+11
View File
@@ -44,6 +44,17 @@ export interface ImageItem {
} }
/** 上传来源:网页或 API(来自活动日志) */ /** 上传来源:网页或 API(来自活动日志) */
uploadSource?: 'web' | '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 { export interface UploadErrorItem {
+5 -2
View File
@@ -1,5 +1,6 @@
export type LogAction = 'upload' | 'delete' export type LogAction = 'upload' | 'delete' | 'login' | 'edit' | 'settings' | 'tags'
export type LogSource = 'web' | 'api' export type LogSource = 'web' | 'api' | 'admin'
export type LogStatus = 'success' | 'failure'
export interface ActivityLogStorage { export interface ActivityLogStorage {
id: string id: string
@@ -18,6 +19,8 @@ export interface ActivityLogItem {
userId: number | null userId: number | null
username: string | null username: string | null
storage: ActivityLogStorage | null storage: ActivityLogStorage | null
ipAddress: string | null
status: LogStatus
createdAt: string 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
View File
@@ -22,3 +22,7 @@ export function formatImageDimensions(width: number | null, height: number | nul
if (!width || !height) return null if (!width || !height) return null
return `${width} × ${height} px` 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" - "6892:6892"
# 首次访问 Web 引导创建管理员,无需预先配置环境变量 # 首次访问 Web 引导创建管理员,无需预先配置环境变量
# 可选:environment 中设置 API_UPLOAD_TOKEN、ALLOWED_REFERER_HOSTS 等 # 可选: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: volumes:
# 冒号左边改成 NAS 上的实际存图目录(飞牛示例:/vol1/1000/pichost-data) # 冒号左边改成 NAS 上的实际存图目录(飞牛示例:/vol1/1000/pichost-data)
- ./data:/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}" exec node /app/server/cli/reset-password.mjs "${@:2}"
fi fi
if [ "$1" = "migrate" ]; then
exec node /app/server/cli/migrate-to-single-images.mjs "${@:2}"
fi
if [ "$1" = "slider" ]; then if [ "$1" = "slider" ]; then
exec node /app/server/cli/slider.mjs "${@:2}" exec node /app/server/cli/slider.mjs "${@:2}"
fi fi
@@ -17,4 +13,16 @@ if [ "$1" = "clear-domains" ]; then
exec node /app/server/cli/clear-domains.mjs "${@:2}" exec node /app/server/cli/clear-domains.mjs "${@:2}"
fi 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 "$@" exec node /app/.output/server/index.mjs "$@"
-2
View File
@@ -34,7 +34,6 @@ const zhSidebar = [
text: '升级', text: '升级',
items: [ items: [
{ text: '更新日志', link: '/guide/changelog' }, { text: '更新日志', link: '/guide/changelog' },
{ text: 'v1.2 迁移', link: '/guide/migration' },
{ text: '常见问题', link: '/guide/faq' } { text: '常见问题', link: '/guide/faq' }
] ]
} }
@@ -71,7 +70,6 @@ const enSidebar = [
text: 'Upgrade', text: 'Upgrade',
items: [ items: [
{ text: 'Changelog', link: '/en/guide/changelog' }, { text: 'Changelog', link: '/en/guide/changelog' },
{ text: 'v1.2 migration', link: '/en/guide/migration' },
{ text: 'FAQ', link: '/en/guide/faq' } { text: 'FAQ', link: '/en/guide/faq' }
] ]
} }
+29 -1
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**. 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 ## Authentication
All REST calls use: All REST calls use:
@@ -28,9 +30,12 @@ Upload one or more images via `image`; also accepts `file`, `files`. Stored unde
```bash ```bash
curl -X POST "https://admin.example.com/api/images/upload" \ curl -X POST "https://admin.example.com/api/images/upload" \
-H "Auth-Token: YOUR_TOKEN" \ -H "Auth-Token: YOUR_TOKEN" \
-F "image=@./demo.png" -F "image=@./demo.png" \
-F 'tagIds=[1,2]'
``` ```
Optional form field `tagIds`: JSON array string or repeated fields. Tags do **not** change storage paths under `images/`.
### 2. List images ### 2. List images
`GET /api/images` `GET /api/images`
@@ -42,6 +47,8 @@ curl "https://admin.example.com/api/images?limit=20&page=1" \
-H "Auth-Token: YOUR_TOKEN" -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 ### 3. Search images
`GET /api/images/search` `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"]}' -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 ## Errors
REST responses are JSON with `code` and `message` (`UNAUTHORIZED`, `FORBIDDEN`, `INVALID_REQUEST`, etc.). Twikoo uses EasyImage-compatible JSON. REST responses are JSON with `code` and `message` (`UNAUTHORIZED`, `FORBIDDEN`, `INVALID_REQUEST`, etc.). Twikoo uses EasyImage-compatible JSON.
+19 -4
View File
@@ -4,6 +4,24 @@ Version history and notable changes. The full log is also in the repo root [CHAN
--- ---
## [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 ## [1.2.8] — 2026-09-04
### Improved ### Improved
@@ -159,15 +177,12 @@ Version history and notable changes. The full log is also in the repo root [CHAN
### Changed ### 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 ### Added
- CLI: `docker exec pichost migrate` / `migrate --apply`
- Startup index sync (disk scan, legacy key normalization, orphan cleanup) - Startup index sync (disk scan, legacy key normalization, orphan cleanup)
See [v1.2 migration](./migration.md).
--- ---
## [1.1.x] summary ## [1.1.x] summary
+3 -1
View File
@@ -1,6 +1,8 @@
# Environment variables # 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 ## 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` - Always open admin on the **site hostname**, not mixed with `localhost`
- See [Dual-domain separation](./domain-separation.md) - 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. 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).
## 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).
## Skip login during development? ## Skip login during development?
+12 -8
View File
@@ -33,9 +33,19 @@ See `docker-compose.yml` in the repository.
## First-time setup ## First-time setup
1. Open your instance URL (Docker default `http://<host>:6892`). 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). 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 ## 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). 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 ## Next steps
- [Local development](./local-dev.md) - [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 ## 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 | | Upload | Batch tagging |
| :-: | :-----: | | :----: | :-----------: |
| ![API](/screenshots/api.png) | ![Gallery](/screenshots/gallery.png) | | ![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 | Settings |
| :-----: | :-------: | | :-----: | :-------: |
| ![Storage](/screenshots/storage.png) | ![Settings](/screenshots/settings-en.png) | | ![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 |
| :----------: | | :----------: |
| ![Activity log](/screenshots/logs.png) | | ![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 reset-password` | Reset password (optional username) |
| `npm run slider` | Reset login verification to local slider | | `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 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 ## Dev-only variables
@@ -53,4 +52,4 @@ npm run docs:build
npm run docs:preview 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)
+43 -4
View File
@@ -18,6 +18,8 @@ PicHost supports **local disk** and **S3-compatible object storage** (Cloudflare
All **keys** start with `images/`. The upload API does **not** accept a `folder` parameter. 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 ## Adding a backend
1. Sign in as admin → **Storage** → **Add backend**. 1. Sign in as admin → **Storage** → **Add backend**.
@@ -54,13 +56,50 @@ Copied links use **IMAGE_BASE_URL**. “Hide folder prefix” may shorten URLs;
## Usage & gallery filter ## Usage & gallery filter
- Per-backend usage on the Storage page - 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 ## See also
@@ -16,6 +16,7 @@ PicHost uses role-based access control (RBAC): **admin** and **user**. Enforceme
| Global API token | ✓ | — | | Global API token | ✓ | — |
| Personal API token | ✓ | ✓ | | Personal API token | ✓ | ✓ |
| Gallery stats overview (incl. user count) | ✓ | partial | | Gallery stats overview (incl. user count) | ✓ | partial |
| Tag management (Settings → Tag management) | ✓ | — |
| Activity log (Settings → Activity log) | ✓ | — | | Activity log (Settings → Activity log) | ✓ | — |
Regular users see **API**, **Gallery** in the nav; user menu: **Change password**, **Sign out**. 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 - If verification is misconfigured: `docker exec pichost slider` resets to the local slider
- Login rate limiting - 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 & 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 - **Upload preferences**: admins configure client compression and auto-copy in **Settings → Basic**; regular users can flip the home upload card for personal preferences
+37 -1
View File
@@ -2,6 +2,8 @@
PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API** 页:左侧为接口目录与 Token 管理,中间为参数说明与 cURL 示例,右侧可 **在线调试** 发送请求。 PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API** 页:左侧为接口目录与 Token 管理,中间为参数说明与 cURL 示例,右侧可 **在线调试** 发送请求。
![API 文档与在线调试](/screenshots/api.png)
## 鉴权 ## 鉴权
所有 REST 接口使用请求头: 所有 REST 接口使用请求头:
@@ -28,9 +30,12 @@ Auth-Token: YOUR_TOKEN
```bash ```bash
curl -X POST "https://admin.example.com/api/images/upload" \ curl -X POST "https://admin.example.com/api/images/upload" \
-H "Auth-Token: YOUR_TOKEN" \ -H "Auth-Token: YOUR_TOKEN" \
-F "image=@./demo.png" -F "image=@./demo.png" \
-F 'tagIds=[1,2]'
``` ```
可选表单字段 `tagIds`:JSON 数组字符串(如 `[1,2]`)或重复字段,上传成功后自动打标。存储路径仍为 `images/年/月/id.webp`,**不会**因标签创建子目录。
### 2. 获取图片列表 ### 2. 获取图片列表
`GET /api/images` `GET /api/images`
@@ -42,6 +47,16 @@ curl "https://admin.example.com/api/images?limit=20&page=1" \
-H "Auth-Token: YOUR_TOKEN" -H "Auth-Token: YOUR_TOKEN"
``` ```
可选查询参数:
| 参数 | 说明 |
| ---- | ---- |
| `tagIds` | 逗号分隔的标签 ID,默认 **OR**(含任一标签) |
| `tagMode` | `and` 时多标签取交集 |
| `untagged` | `1` 仅返回无标签图片 |
响应 `items[]` 含 `tags` 数组(`id`、`name`、`color`)。
### 3. 搜索图片 ### 3. 搜索图片
`GET /api/images/search` `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"]}' -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 格式。 REST 接口返回 JSON,含 `code` 与 `message`(如 `UNAUTHORIZED`、`FORBIDDEN`、`INVALID_REQUEST`)。Twikoo 端点使用 EasyImage 兼容 JSON 格式。
+19 -4
View File
@@ -4,6 +4,24 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
--- ---
## [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 ## [1.2.8] — 2026-09-04
### 改进 ### 改进
@@ -159,15 +177,12 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
### 变更 ### 变更
- 图片统一存放在 `data/images/`;遗留 `blog/`、`twikoo/` 等并列目录需迁移 - 图片统一存放在 `data/images/`;不再使用与 `images` 并列的顶层目录
### 新增 ### 新增
- CLI:`docker exec pichost migrate` / `migrate --apply`
- 启动时自动同步图片索引(扫描磁盘、归一化遗留 key、清理孤儿记录) - 启动时自动同步图片索引(扫描磁盘、归一化遗留 key、清理孤儿记录)
详见 [v1.2 迁移](./migration.md)。
--- ---
## [1.1.x] 摘要 ## [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` 混用 - 后台请用 **网站域名** 打开,不要用 `localhost` 混用
- 见 [双域名分离](./domain-separation.md) - 见 [双域名分离](./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/` 磁盘扫描。 备份包含数据库与全部图片,**不含** 云存储密钥;恢复后请在存储页重新填写。详见 [存储 → 备份与迁移](./storage.md#备份与迁移v130)。
## 如何替换博客里的旧图片 URL?
使用 `data/mapping.json`(`migrate` 预览时生成)批量替换旧 key。注意映射的是 **存储 key**,不是完整旧站 URL。见 [迁移指南](./migration.md#外链与直链)。
## 开发时如何跳过登录? ## 开发时如何跳过登录?
+12 -8
View File
@@ -33,9 +33,19 @@ docker compose up -d
## 首次设置 ## 首次设置
1. 访问实例 URL(Docker 默认 `http://<主机>:6892`)。 1. 访问实例 URL(Docker 默认 `http://<主机>:6892`)。
2. 在 `/setup` 填写管理员用户名与密码。 2. 在 `/setup` 选择 **创建管理员** 或 **从备份恢复**:
- **创建管理员**:填写用户名与密码,可选开放注册、双域名等。
- **从备份恢复**:上传 `.phost.tar.gz` 整站备份包(覆盖当前数据;云存储密钥需恢复后重新填写)。
3. (可选)配置网站域名、图片域名、防盗链等 — 详见 [环境变量](./configuration.md) 与 [双域名分离](./domain-separation.md)。 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-进不去)。 本地:`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` - [本地开发](./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 reset-password` | 重置密码(可选用户名) |
| `npm run slider` | 将登录验证重置为本地滑块 | | `npm run slider` | 将登录验证重置为本地滑块 |
| `npm run clear-domains` | 清除数据库中的网站域 / 图片域配置(双域名锁死时恢复) | | `npm run clear-domains` | 清除数据库中的网站域 / 图片域配置(双域名锁死时恢复) |
| `npm run migrate` | 预览遗留目录迁移(加 `-- --apply` 执行) |
## 开发专用环境变量 ## 开发专用环境变量
@@ -53,4 +52,4 @@ npm run docs:build # 构建静态站点
npm run docs:preview # 预览构建结果 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` | 重置密码(与迁移无关) |
+47 -7
View File
@@ -18,6 +18,8 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
所有图片 **key** 以 `images/` 开头。上传 API **不再接受** `folder` 参数。 所有图片 **key** 以 `images/` 开头。上传 API **不再接受** `folder` 参数。
**图片分类**使用每用户 **标签**(`tags` / `image_tags` 表),不改变磁盘路径。图库页按标签筛选;详见 [API 文档](./api.md#6-标签管理)。
## 添加存储后端 ## 添加存储后端
1. 以管理员登录,打开 **存储** → **添加存储**。 1. 以管理员登录,打开 **存储** → **添加存储**。
@@ -56,17 +58,55 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
## 用量与筛选 ## 用量与筛选
- 存储页展示各后端用量(本地扫描目录,对象存储查询 API) - 存储页展示各后端用量(本地扫描目录,对象存储查询 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` 与各云桶中的对象;推荐使用上文整站导出。
## 相关 ## 相关
+15
View File
@@ -16,6 +16,7 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
| 全局 API Token 管理 | ✓ | — | | 全局 API Token 管理 | ✓ | — |
| 个人 API Token | ✓ | ✓ | | 个人 API Token | ✓ | ✓ |
| 图库统计概览(含注册用户数) | ✓ | 部分 | | 图库统计概览(含注册用户数) | ✓ | 部分 |
| 标签管理(设置 → 标签管理) | ✓ | — |
| 操作日志(设置 → 操作日志) | ✓ | — | | 操作日志(设置 → 操作日志) | ✓ | — |
普通用户顶栏:**API**、**图库**;用户菜单:**修改密码**、**退出登录**。 普通用户顶栏:**API**、**图库**;用户菜单:**修改密码**、**退出登录**。
@@ -39,6 +40,20 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
- 验证配置错误无法登录时:`docker exec pichost slider` 重置为本地滑块 - 验证配置错误无法登录时:`docker exec pichost slider` 重置为本地滑块
- 登录失败有速率限制 - 登录失败有速率限制
## 标签
- 标签按 **用户隔离**:普通用户仅管理、筛选自己的标签与图片
- 首页上传完成后可 **单张打标** 或 **批量打标签**;图库支持按标签筛选(多标签 OR / AND)与批量打标
- 管理员在 **设置 → 标签管理** 新建、改色、合并、删除标签;标签仅用于分类,**不改变** `images/` 存储路径
![批量打标](/screenshots/tags-batch.png) ![标签管理](/screenshots/tags.png)
## 操作日志
管理员在 **设置 → 操作日志** 查看上传、删除、登录、设置变更、标签操作等记录,支持按日期、用户、操作类型、来源筛选。
![操作日志](/screenshots/logs.png)
## 上传偏好与自动删除 ## 上传偏好与自动删除
- **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好 - **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好
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

Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 82 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 146 KiB

+268 -7
View File
@@ -110,7 +110,18 @@
"migrateSubmit": "Complete migration", "migrateSubmit": "Complete migration",
"initSubmit": "Create and continue", "initSubmit": "Create and continue",
"migrateSuccess": "Migration complete", "migrateSuccess": "Migration complete",
"initSuccess": "Setup complete" "initSuccess": "Setup complete",
"restoreTitle": "Restore from backup",
"restoreSubtitle": "Upload a .phost.tar.gz to restore the full site",
"restoreHint": "Restore replaces all current data. Cloud storage secrets are not in the backup—re-enter them on the Storage page after sign-in.",
"restoreUpload": "Choose backup file",
"restoreSubmit": "Start restore",
"restoreProgress": "Restoring… {progress}/{total}",
"restoreSuccess": "Restore complete. Sign in with the admin account from the backup.",
"restoreFailed": "Restore failed",
"restoreSecretsHint": "Cloud storage secrets are not in the backup. Re-enter them on the Storage page after sign-in.",
"modeInit": "Create admin",
"modeRestore": "Restore backup"
}, },
"register": { "register": {
"title": "Register", "title": "Register",
@@ -155,6 +166,104 @@
"sessionTitle": "This session", "sessionTitle": "This session",
"sessionEmpty": "No uploads in this session" "sessionEmpty": "No uploads in this session"
}, },
"tags": {
"column": "Tags",
"uploadLabel": "Tags (optional)",
"addTag": "Add tag",
"searchOrCreate": "Search or create tag",
"createNamed": "Create tag \"{name}\"",
"created": "Created tag \"{name}\"",
"createFailed": "Failed to create tag",
"updateFailed": "Failed to update tags",
"filterAll": "All tags",
"filterSelected": "{n} selected",
"filterTitle": "Filter by tag",
"manage": "Manage",
"manageTitle": "Manage tags",
"manageImageTitle": "Manage tags",
"manageSubtitle": "Centralized tag management — add, edit, delete, and merge",
"newTag": "New tag",
"addTag": "Add tag",
"mergeTags": "Merge tags",
"searchName": "Search tag name",
"filterStatusAll": "All statuses",
"filterStatusUsed": "In use",
"filterStatusUnused": "Unused",
"statTotal": "Total tags",
"statUsed": "Tags in use",
"statUnused": "Unused tags",
"statNew7d": "New in 7 days",
"colName": "Tag name",
"colImageCount": "Images",
"colLastUsed": "Last used",
"neverUsed": "Never used",
"colActions": "Actions",
"mergeIntoAction": "Merge into…",
"mergeIntoTitle": "Merge into…",
"mergeIntoSubtitle": "Merge tag \"{name}\" into another tag",
"mergeIntoChoose": "Choose the target tag",
"mergeIrreversibleTitle": "This cannot be undone",
"mergeIrreversible": "Merged tags are permanently deleted and their images move to the kept tag. This action cannot be reversed.",
"mergeConfirmKeep": "Keeping tag \"{name}\"",
"mergeWillDelete": "These tags will be deleted: {names}",
"totalCount": "{n} tags",
"sortByCount": "By count",
"sortByName": "By name",
"search": "Search tags",
"namePlaceholder": "Tag name",
"customColor": "Custom color",
"pickColor": "Pick a color",
"preview": "Preview",
"renamed": "Tag renamed",
"renameFailed": "Rename failed",
"colorFailed": "Failed to update color",
"deleted": "Deleted tag \"{name}\"",
"deleteFailed": "Failed to delete tag",
"deleteConfirmTitle": "Delete tag",
"deleteConfirmDesc": "Delete tag \"{name}\"? It will be removed from all images. This cannot be undone.",
"mergeSelectAtLeast": "Select at least 2 tags",
"mergeHint": "Select multiple tags to merge; images from other tags will move to the kept tag",
"mergeSelected": "{n} tags selected",
"mergeClear": "Clear selection",
"mergeTitle": "Merge tags",
"mergeSubtitle": "Combine multiple tags into one",
"mergeNote": "Unselected tags will be deleted; their images move to the kept tag",
"mergeChooseTarget": "Choose the tag to keep",
"mergeAction": "Merge into…",
"mergeRow": "Merge",
"mergeConfirm": "Confirm merge",
"merged": "Tags merged",
"mergeFailed": "Merge failed",
"untagged": "Untagged",
"untaggedAction": "+ Untagged",
"unlabeled": "Unlabeled",
"selectedLabel": "Selected ({n})",
"clearSelected": "Clear",
"selectAll": "Select all",
"deselectAll": "Deselect all",
"existingLabel": "Existing tags ({n})",
"commonTags": "Common tags",
"recentTags": "Recently used",
"moreTags": "{n} more tags",
"classifyHint": "Tags are for organization only and do not affect storage paths",
"saved": "Tags saved",
"saveFailed": "Failed to save tags",
"batchTagAll": "Batch tag",
"batchAddTitle": "Add tags",
"batchAddSubtitle": "{n} images selected",
"modeOr": "Any",
"modeAnd": "All",
"batchTitle": "Batch tags",
"batchSubtitle": "Update tags for {n} selected image(s)",
"batchAdd": "Add tags",
"batchRemove": "Remove tags",
"batchSuccess": "Batch update complete",
"batchFailed": "Batch update failed",
"noMatch": "No matching tags",
"emptyHint": "No tags yet — type a name to create one",
"settingsLink": "Manage tags in the gallery (create, colors, merge, delete)",
"openManage": "Open tag manager"
},
"copy": { "copy": {
"url": "URL", "url": "URL",
"markdown": "Markdown", "markdown": "Markdown",
@@ -195,12 +304,30 @@
"title": "System settings", "title": "System settings",
"pageTitle": "Settings & preferences", "pageTitle": "Settings & preferences",
"pageSubtitle": "Manage system configuration and activity logs", "pageSubtitle": "Manage system configuration and activity logs",
"pageSubtitleBasic": "Manage system configuration and upload preferences", "pageSubtitleBasic": "Configure basic options so PicHost works better for you.",
"pageSubtitleDomains": "Configure site and image URLs and upload path rules",
"pageSubtitleAccess": "Configure image access policies to prevent hotlink abuse",
"pageSubtitleLogs": "View uploads, deletions, edits, and configuration changes",
"searchPlaceholder": "Search settings…",
"searchEmpty": "No matches",
"restoreDefaults": "Restore defaults",
"restoredDefaults": "Defaults restored",
"refererProtection": "Hotlink protection",
"defaultCopyFormatHint": "Link format copied automatically after upload",
"systemVersionHint": "Currently running PicHost version",
"badgeEnabled": "Enabled",
"domainSeparationProxyTitle": "Both domains must resolve to this host",
"domainSeparationProxyBody": "Point the site and image URLs to this host and reverse-proxy to port 6892 (Nginx, Caddy, NPM, etc.).",
"siteBaseUrlRoleHint": "URL for the admin UI",
"imageBaseUrlRoleHint": "URL for serving and displaying images",
"imageDomainSection": "Image domain",
"navBasic": "Basic", "navBasic": "Basic",
"navDomains": "Domains & paths", "navDomains": "Domains & paths",
"navAccess": "Access control", "navAccess": "Access control",
"navTags": "Tags",
"navPreferences": "Preferences", "navPreferences": "Preferences",
"navLogs": "Activity log", "navLogs": "Activity log",
"pageSubtitleTags": "Create, rename, merge, or delete tags",
"systemVersion": "Version", "systemVersion": "Version",
"checkUpdate": "Check for updates", "checkUpdate": "Check for updates",
"saveSettings": "Save settings", "saveSettings": "Save settings",
@@ -220,6 +347,10 @@
"refererExamplesSample": "example.com, static.example.com", "refererExamplesSample": "example.com, static.example.com",
"refererScenarioTitle": "Common use case", "refererScenarioTitle": "Common use case",
"refererScenarioDesc": "Allow your main site and static site to embed images", "refererScenarioDesc": "Allow your main site and static site to embed images",
"refererScenario1": "Personal blog embedding images",
"refererScenario2": "Corporate site and static CDN",
"refererScenario3": "Local development",
"refererScenario4": "Leave empty for no restriction",
"refererEnabled": "Enabled", "refererEnabled": "Enabled",
"refererUnrestricted": "Unrestricted", "refererUnrestricted": "Unrestricted",
"loginVerification": "Login verification", "loginVerification": "Login verification",
@@ -388,7 +519,125 @@
"deleteConfirmBody": "Delete “{name}”? This cannot be undone.", "deleteConfirmBody": "Delete “{name}”? This cannot be undone.",
"secretsRequired": "Access Key and Secret Key are required for new storage", "secretsRequired": "Access Key and Secret Key are required for new storage",
"manageStorage": "Manage object storage", "manageStorage": "Manage object storage",
"manageStorageHint": "Configure R2 / S3 / COS backends and URL serving" "manageStorageHint": "Configure R2 / S3 / COS backends and URL serving",
"backup": {
"sectionTitle": "Backup & migration",
"sectionSubtitle": "Full-site backup, restore, and cross-backend image migration",
"siteTitle": "Site backup & restore",
"siteSubtitle": "For migration, disaster recovery, and full-site restore",
"siteFooterHint": "Backups include the database and images, not plain-text secret_json.",
"exportTitle": "Create site backup",
"exportSubtitle": "Package the database and all images as .phost.tar.gz",
"exportAction": "Start backup",
"exportStarted": "Backup job started",
"exportFailed": "Failed to start backup",
"exportPathHint": "Exports are saved under data/backups/",
"exportIncludesTitle": "Package includes",
"exportIncludesDb": "Database snapshot (pichost.db)",
"exportIncludesImages": "All image files ({count})",
"exportExcludesSecrets": "Excludes plain-text secret.json for cloud storage",
"exportConcurrencyHint": "Only one backup or migration job can run at a time",
"estimateLoading": "Estimating size…",
"estimateImageCountLabel": "Images",
"estimatePackageSizeLabel": "Est. package",
"estimateDatabaseSnapshotLabel": "Database snapshot",
"estimateStoragePathLabel": "Save location",
"estimateStoragePathValue": "data/backups/",
"estimateImages": "{count} images · {size}",
"estimateDatabase": "Database ~{size}",
"estimateTotal": "Total ~{size}",
"restoreTitle": "Restore from backup",
"restoreSubtitle": "Upload or pick a .phost.tar.gz on the server, preview, then confirm",
"restoreUpload": "Choose backup file",
"restoreUploadLabel": "Upload from device",
"restoreUploadHint": "Click to select a .phost.tar.gz backup",
"restoreUploadAction": "Upload & restore",
"restoreServerAction": "Server backup",
"restoreServerPackages": "Server backups",
"restoreServerSelectPlaceholder": "Select a backup",
"restorePreview": "Preview",
"restorePreviewConfirm": "Preview & confirm",
"restoreConfirm": "Confirm restore",
"restoreConfirmTitle": "Confirm site restore",
"restoreConfirmSource": "Source: {name}",
"restoreOverwriteWarning": "Overwrite mode replaces conflicting images and the database. Ensure you have a current backup.",
"restoreSelectRequired": "Select or upload a backup file",
"restoreStarted": "Restore job started",
"restoreFailed": "Restore failed",
"conflictMode": "Conflict policy",
"conflictSkip": "Skip existing images",
"conflictOverwrite": "Overwrite existing images and database",
"syncTitle": "Cross-backend sync",
"syncMigrateTitle": "Cross-backend migration",
"syncMigrateSubtitle": "Migrate images between configured backends",
"syncSubtitle": "Copy images between configured backends and update the index",
"syncFrom": "Source backend",
"syncTo": "Target backend",
"syncPendingImages": "Images to migrate",
"syncPendingSize": "Est. size",
"syncIncludesTitle": "What sync does",
"syncIncludesCopy": "Copy image files from source to target backend",
"syncIncludesIndex": "Update storage_backend_id in the index",
"syncIncludesConfig": "Site settings and other backends are unchanged",
"syncDryRun": "Dry run only",
"syncSetDefaultAfter": "Set target as default after migration",
"syncStartMigrate": "Start migration",
"syncPreviewOnly": "Preview",
"syncFooterHint": "Only image files and index are migrated; site settings are unchanged.",
"syncDeleteSource": "Delete source files after sync",
"syncSetDefault": "Set target as default after sync",
"syncPreview": "Preview & start",
"syncConfirm": "Start sync",
"syncConfirmTitle": "Confirm cross-backend sync",
"syncDeleteWarning": "Source files will be deleted. This cannot be undone.",
"syncSelectRequired": "Select source and target backends",
"syncSameBackend": "Source and target must differ",
"syncStarted": "Sync job started",
"syncFailed": "Sync failed",
"previewFailed": "Preview failed",
"previewImages": "Images",
"previewNew": "New images",
"previewConflicts": "Conflicts",
"previewCreated": "Backup created",
"previewSize": "Data size",
"jobsTitle": "Recent jobs",
"jobsSubtitle": "Track backup, restore, and migration progress",
"jobsEmpty": "No backup or migration jobs yet",
"jobsEmptyHint": "Progress appears here after export, restore, or sync starts",
"jobsUnit": "jobs",
"colTask": "Task",
"colType": "Type",
"colStatus": "Status",
"colProgress": "Progress",
"colMessage": "Message",
"colCreated": "Created",
"colActions": "Actions",
"jobTypeExport": "Site export",
"jobTypeRestore": "Site restore",
"jobTypeSync": "Cross-backend sync",
"statusPending": "Pending",
"statusRunning": "Running",
"statusDone": "Done",
"statusFailed": "Failed",
"jobFailedUnknown": "Unknown error",
"download": "Download",
"jobView": "View",
"retry": "Retry",
"retryStarted": "Retry started",
"retryFailed": "Retry failed",
"jobRunning": "Another job is already running. Try again later.",
"migrateIn": "Migrate in",
"migrateOut": "Migrate out",
"migrateInHint": "Copy images from the default backend to this one",
"migrateOutHint": "Move images out of this backend",
"syncDraftApplied": "Sync form prefilled — review and start when ready",
"syncNeedTwoBackends": "At least two storage backends are required to sync",
"selectBackend": "Select backend",
"syncConfirmRoute": "{from} → {to}",
"cancel": "Cancel",
"cancelDone": "Job cancelled",
"cancelFailed": "Failed to cancel job"
}
}, },
"stats": { "stats": {
"title": "Gallery", "title": "Gallery",
@@ -465,20 +714,28 @@
}, },
"logs": { "logs": {
"pageTitle": "Activity log", "pageTitle": "Activity log",
"pageSubtitle": "Your upload and delete history", "pageSubtitle": "Your activity history",
"pageSubtitleAdmin": "Upload and delete history for all users", "pageSubtitleAdmin": "Activity history for all users",
"loadFailed": "Failed to load activity log", "loadFailed": "Failed to load activity log",
"empty": "No activity yet", "empty": "No activity yet",
"entriesUnit": "entries", "entriesUnit": "entries",
"filterActionAll": "All actions", "filterActionAll": "All actions",
"filterSourceAll": "All sources", "filterSourceAll": "All sources",
"filterUserAll": "All users", "filterUserAll": "All users",
"searchPlaceholder": "Search filename", "searchPlaceholder": "Search filename, path, or IP",
"dateFrom": "Start date",
"dateTo": "End date",
"dateRangeSeparator": "~",
"summaryAll": "All · {total} entries, {upload} uploads, {delete} deletes", "summaryAll": "All · {total} entries, {upload} uploads, {delete} deletes",
"actionUpload": "Upload", "actionUpload": "Upload",
"actionDelete": "Delete", "actionDelete": "Delete",
"actionLogin": "Login",
"actionEdit": "Edit",
"actionSettings": "Settings",
"actionTags": "Tags",
"sourceWeb": "Web", "sourceWeb": "Web",
"sourceApi": "API", "sourceApi": "API",
"sourceAdmin": "Admin",
"colTime": "Time", "colTime": "Time",
"colUser": "User", "colUser": "User",
"colStorage": "Storage", "colStorage": "Storage",
@@ -487,7 +744,11 @@
"colFile": "File", "colFile": "File",
"colFolder": "Folder", "colFolder": "Folder",
"colSize": "Size", "colSize": "Size",
"colKey": "Path" "colKey": "Path",
"colIp": "IP address",
"colResult": "Result",
"resultSuccess": "Success",
"resultFailure": "Failed"
}, },
"image": { "image": {
"empty": "No images", "empty": "No images",
+287 -22
View File
@@ -97,7 +97,7 @@
"confirmPlaceholder": "再次输入密码", "confirmPlaceholder": "再次输入密码",
"allowRegistration": "允许其他用户注册", "allowRegistration": "允许其他用户注册",
"domainSeparation": "启用后台与图片域名分离", "domainSeparation": "启用后台与图片域名分离",
"domainSeparationHint": "管理后台与 API 使用网站域名,图片直链使用独立图片域名", "domainSeparationHint": "启用后,可以使用不同的域名访问后台和图片资源,便于配置 CDN 和自定义域名。",
"domainSeparationProxyHint": "需将两个域名解析到本机,并通过 Nginx、Caddy、NPM 等反代到端口 6892", "domainSeparationProxyHint": "需将两个域名解析到本机,并通过 Nginx、Caddy、NPM 等反代到端口 6892",
"domainSeparationProxyExample": "查看示例", "domainSeparationProxyExample": "查看示例",
"siteBaseUrl": "网站域名", "siteBaseUrl": "网站域名",
@@ -110,7 +110,18 @@
"migrateSubmit": "完成迁移", "migrateSubmit": "完成迁移",
"initSubmit": "创建并进入", "initSubmit": "创建并进入",
"migrateSuccess": "账号迁移完成", "migrateSuccess": "账号迁移完成",
"initSuccess": "初始化完成" "initSuccess": "初始化完成",
"restoreTitle": "从备份包恢复",
"restoreSubtitle": "上传 .phost.tar.gz 恢复整站数据",
"restoreHint": "恢复将覆盖当前全部数据。云存储密钥未包含在备份中,登录后请在存储页重新填写。",
"restoreUpload": "选择备份文件",
"restoreSubmit": "开始恢复",
"restoreProgress": "恢复中… {progress}/{total}",
"restoreSuccess": "恢复完成,请使用备份中的管理员账号登录",
"restoreFailed": "恢复失败",
"restoreSecretsHint": "云存储密钥未包含在备份中,登录后请在存储页重新填写",
"modeInit": "创建管理员",
"modeRestore": "从备份恢复"
}, },
"register": { "register": {
"title": "注册账号", "title": "注册账号",
@@ -155,6 +166,104 @@
"sessionTitle": "本次上传", "sessionTitle": "本次上传",
"sessionEmpty": "暂无本次上传" "sessionEmpty": "暂无本次上传"
}, },
"tags": {
"column": "标签",
"uploadLabel": "标签(可选)",
"addTag": "添加标签",
"searchOrCreate": "搜索或创建标签",
"createNamed": "创建标签 \"{name}\"",
"created": "已创建标签「{name}」",
"createFailed": "创建标签失败",
"updateFailed": "更新标签失败",
"filterAll": "全部标签",
"filterSelected": "已选 {n} 个",
"filterTitle": "按标签筛选",
"manage": "管理",
"manageTitle": "管理标签",
"manageImageTitle": "管理标签",
"manageSubtitle": "集中管理图片标签,支持新增、修改、删除与合并",
"newTag": "新建标签",
"addTag": "新增标签",
"mergeTags": "合并标签",
"searchName": "搜索标签名称",
"filterStatusAll": "全部状态",
"filterStatusUsed": "已使用",
"filterStatusUnused": "未使用",
"statTotal": "标签总数",
"statUsed": "已使用标签",
"statUnused": "未使用标签",
"statNew7d": "最近 7 天新增",
"colName": "标签名称",
"colImageCount": "图片数",
"colLastUsed": "最近使用",
"neverUsed": "从未使用",
"colActions": "操作",
"mergeIntoAction": "合并到…",
"mergeIntoTitle": "合并到…",
"mergeIntoSubtitle": "将标签「{name}」合并到其他标签",
"mergeIntoChoose": "选择要合并到的目标标签",
"mergeIrreversibleTitle": "此操作不可恢复",
"mergeIrreversible": "合并后,被合并的标签将被永久删除,其关联图片会归入保留的标签。此操作无法撤销。",
"mergeConfirmKeep": "将保留标签「{name}」",
"mergeWillDelete": "以下标签将被删除:{names}",
"totalCount": "共 {n} 个标签",
"sortByCount": "按数量",
"sortByName": "按名称",
"search": "搜索标签",
"namePlaceholder": "标签名称",
"customColor": "自定义颜色",
"pickColor": "选择颜色",
"preview": "预览",
"renamed": "标签已重命名",
"renameFailed": "重命名失败",
"colorFailed": "更新颜色失败",
"deleted": "已删除标签「{name}」",
"deleteFailed": "删除标签失败",
"deleteConfirmTitle": "确认删除标签",
"deleteConfirmDesc": "确定删除标签「{name}」?图片上的该标签将被移除,此操作不可恢复。",
"mergeSelectAtLeast": "请至少选择 2 个标签",
"mergeHint": "勾选多个标签后可合并;其余标签的图片将归入保留的标签",
"mergeSelected": "已选 {n} 个标签",
"mergeClear": "取消选择",
"mergeTitle": "合并标签",
"mergeSubtitle": "将多个标签合并为一个",
"mergeNote": "未选中的标签将被删除,其图片会归入保留的标签",
"mergeChooseTarget": "选择要保留的标签",
"mergeAction": "合并为…",
"mergeRow": "合并",
"mergeConfirm": "确认合并",
"merged": "标签已合并",
"mergeFailed": "合并失败",
"untagged": "无标签",
"untaggedAction": "+ 无标签",
"unlabeled": "未标记",
"selectedLabel": "已选标签 ({n})",
"clearSelected": "清空",
"selectAll": "全选",
"deselectAll": "取消全选",
"existingLabel": "已有标签 ({n})",
"commonTags": "常用标签",
"recentTags": "最近使用",
"moreTags": "还有 {n} 个标签",
"classifyHint": "标签仅用于分类,不影响图片实际存储路径",
"saved": "标签已保存",
"saveFailed": "保存标签失败",
"batchTagAll": "批量打标签",
"batchAddTitle": "添加标签",
"batchAddSubtitle": "已选 {n} 张图片",
"modeOr": "任一",
"modeAnd": "全部",
"batchTitle": "批量标签",
"batchSubtitle": "为已选 {n} 张图片更新标签",
"batchAdd": "添加标签",
"batchRemove": "移除标签",
"batchSuccess": "批量更新完成",
"batchFailed": "批量更新失败",
"noMatch": "无匹配标签",
"emptyHint": "暂无标签,可输入名称创建",
"settingsLink": "在图库中管理标签(新建、改色、合并、删除)",
"openManage": "打开标签管理"
},
"copy": { "copy": {
"url": "直链", "url": "直链",
"markdown": "Markdown", "markdown": "Markdown",
@@ -177,30 +286,48 @@
"back": "返回上传", "back": "返回上传",
"processing": "图片处理", "processing": "图片处理",
"clientCompress": "客户端预压缩", "clientCompress": "客户端预压缩",
"clientCompressHint": "上传前在浏览器端压缩(服务端仍会转 WebP)", "clientCompressHint": "在上传前于浏览器端压缩图片,减少上传体积(服务端仍会转 WebP)。",
"autoDeletePrefix": "自动删除超过", "autoDeletePrefix": "自动删除超过",
"autoDeleteSuffix": "天的图片", "autoDeleteSuffix": "天的图片",
"autoDeleteHint": "仅清理开启后上传的图片,不影响此前已存的图片", "autoDeleteHint": "自动清理指定天数前上传的图片,仅对开启后新上传的图片生效。",
"webpQuality": "WebP 压缩质量", "webpQuality": "WebP 压缩质量",
"webpQualityHint": "客户端预压缩质量(1–100),需开启「客户端预压缩」", "webpQualityHint": "转换为 WebP 格式时的图片质量,数值越高画质越好、体积越大。",
"current": "当前:{n}", "current": "当前:{n}",
"qualityHigh": "高质量", "qualityHigh": "高质量",
"qualityMedium": "中等质量", "qualityMedium": "中等质量",
"qualityLow": "有损压缩", "qualityLow": "有损压缩",
"convenience": "便捷功能", "convenience": "便捷功能",
"autoCopy": "上传成功自动复制链接", "autoCopy": "上传成功自动复制链接",
"autoCopyHint": "按所选格式复制到剪贴板" "autoCopyHint": "图片上传成功后,自动复制图片链接到剪贴板。"
}, },
"settings": { "settings": {
"title": "系统设置", "title": "系统设置",
"pageTitle": "设置与偏好", "pageTitle": "设置与偏好",
"pageSubtitle": "管理系统配置与操作日志", "pageSubtitle": "管理系统配置与操作日志",
"pageSubtitleBasic": "管理系统配置与上传偏好", "pageSubtitleBasic": "配置系统的基本选项,让 PicHost 更好地为你服务。",
"pageSubtitleDomains": "配置网站域名、图片域名以及图片存储路径等相关设置",
"pageSubtitleAccess": "配置图片访问安全策略,防止资源被恶意盗用。",
"pageSubtitleLogs": "查看用户上传、删除、修改与系统配置记录",
"searchPlaceholder": "搜索设置项…",
"searchEmpty": "无匹配项",
"restoreDefaults": "恢复默认",
"restoredDefaults": "已恢复默认设置",
"refererProtection": "防盗链设置",
"defaultCopyFormatHint": "设置上传后自动复制的链接格式。",
"systemVersionHint": "当前运行的 PicHost 版本。",
"badgeEnabled": "已启用",
"domainSeparationProxyTitle": "需要将两个域名解析到本机",
"domainSeparationProxyBody": "请将网站域名和图片域名都解析到本机,并通过 Nginx、Caddy、NPM 等反向代理到本机的 6892 端口。",
"siteBaseUrlRoleHint": "用于访问后台管理界面的网站域名。",
"imageBaseUrlRoleHint": "用于访问和显示图片资源的域名。",
"imageDomainSection": "图片域名",
"navBasic": "基础设置", "navBasic": "基础设置",
"navDomains": "域名与路径", "navDomains": "域名与路径",
"navAccess": "访问控制", "navAccess": "访问控制",
"navTags": "标签管理",
"navPreferences": "偏好设置", "navPreferences": "偏好设置",
"navLogs": "操作日志", "navLogs": "操作日志",
"pageSubtitleTags": "创建、重命名、合并或删除标签",
"systemVersion": "系统版本", "systemVersion": "系统版本",
"checkUpdate": "检查更新", "checkUpdate": "检查更新",
"saveSettings": "保存设置", "saveSettings": "保存设置",
@@ -211,25 +338,29 @@
"pathAndLinkHint": "控制图片直链格式与上传目录结构", "pathAndLinkHint": "控制图片直链格式与上传目录结构",
"domainSeparationSection": "域名分离", "domainSeparationSection": "域名分离",
"allowRegistration": "开放用户注册", "allowRegistration": "开放用户注册",
"allowRegistrationHint": "允许新用户自行注册(普通用户仅可见自己的图片)", "allowRegistrationHint": "允许新用户自行注册账号。",
"accessControl": "访问控制", "accessControl": "访问控制",
"refererHint": "Referer 防盗链,逗号分隔允许引用的域名,留空不限制", "refererHint": "通过 Referer 防盗链,限制哪些网站可以引用你的图片。",
"refererDomainsLabel": "允许引用的域名", "refererDomainsLabel": "允许引用的域名",
"refererTip": "多个域名请使用英文逗号 (,) 分隔,不支持通配符", "refererTip": "多个域名请使用英文逗号 (,) 分隔,不支持通配符",
"refererExamplesTitle": "推荐示例", "refererExamplesTitle": "推荐示例",
"refererExamplesSample": "example.com, static.example.com", "refererExamplesSample": "example.com, static.example.com",
"refererScenarioTitle": "常见场景", "refererScenarioTitle": "常见场景",
"refererScenarioDesc": "允许主站与静态站点引用图片", "refererScenarioDesc": "允许主站与静态站点引用图片",
"refererScenario1": "个人博客引用本站图片",
"refererScenario2": "企业官网与静态资源站",
"refererScenario3": "开发环境本地调试",
"refererScenario4": "留空表示不限制任何来源",
"refererEnabled": "已开启", "refererEnabled": "已开启",
"refererUnrestricted": "未限制", "refererUnrestricted": "未限制",
"loginVerification": "登录验证", "loginVerification": "登录验证",
"loginVerificationHint": "登录与注册时使用的人机验证方式,三选一", "loginVerificationHint": "登录与注册时使用的人机验证方式,三选一",
"loginVerificationSlider": "本地滑块", "loginVerificationSlider": "本地滑块",
"loginVerificationSliderHint": "内置滑块拼图,无需第三方服务", "loginVerificationSliderHint": "内置滑块验证,无需第三方服务。",
"loginVerificationTurnstile": "Cloudflare Turnstile", "loginVerificationTurnstile": "Cloudflare Turnstile",
"loginVerificationTurnstileHint": "在 Cloudflare 控制台创建 Widget,填写 Site Key 与 Secret Key", "loginVerificationTurnstileHint": "使用 Cloudflare 提供的人机验证服务,安全可靠。",
"loginVerificationCap": "Cap POW", "loginVerificationCap": "Cap POW",
"loginVerificationCapHint": "自托管 Cap Standalone,填写 API Endpoint 与 Secret Key", "loginVerificationCapHint": "使用基于工作量证明的人机验证,适合无第三方服务的环境。",
"turnstileSiteKey": "Turnstile Site Key", "turnstileSiteKey": "Turnstile Site Key",
"turnstileSiteKeyPlaceholder": "0x4AAAAAAA…", "turnstileSiteKeyPlaceholder": "0x4AAAAAAA…",
"turnstileSecretKey": "Turnstile Secret Key", "turnstileSecretKey": "Turnstile Secret Key",
@@ -262,9 +393,9 @@
"disableDomainSeparationConfirm": "确认关闭", "disableDomainSeparationConfirm": "确认关闭",
"domainSeparationRequired": "启用域名分离时需同时填写网站域名与图片域名", "domainSeparationRequired": "启用域名分离时需同时填写网站域名与图片域名",
"hideFolderInUrl": "使用简短图片链接", "hideFolderInUrl": "使用简短图片链接",
"hideFolderInUrlHint": "开启后链接仅含域名与文件名,例如 img.example.com/abc.webp;关闭后保留日期或自定义目录,例如 img.example.com/2026/08/abc.webp", "hideFolderInUrlHint": "启用后,生成的图片链接将使用简短格式(如 /abc123.png),不包含年月目录。",
"storageUseDatePath": "上传目录按年/月分组", "storageUseDatePath": "上传目录按年/月分组",
"storageUseDatePathHint": "开启后保存为 images/2026/08/xxx.webp;关闭则为 images/xxx.webp。仅影响启用后的新上传", "storageUseDatePathHint": "启用后,上传的图片将按 年/月 自动分组存储,如 2024/01/xxx.png,便于管理。",
"badgeEnv": ".env", "badgeEnv": ".env",
"badgeSaved": "已保存", "badgeSaved": "已保存",
"badgeDefault": "默认", "badgeDefault": "默认",
@@ -276,7 +407,7 @@
"apiTokenLine": "来源:{source}", "apiTokenLine": "来源:{source}",
"viewReleases": "查看发行版", "viewReleases": "查看发行版",
"updateAvailable": "有新版本 {version}", "updateAvailable": "有新版本 {version}",
"upToDate": "当前已是最新版本", "upToDate": "已是最新版本",
"checkUpdateFailed": "检查更新失败,请稍后重试", "checkUpdateFailed": "检查更新失败,请稍后重试",
"unsavedChanges": "有未保存的更改", "unsavedChanges": "有未保存的更改",
"manageToken": "管理 Token", "manageToken": "管理 Token",
@@ -388,7 +519,125 @@
"deleteConfirmBody": "确定删除「{name}」?此操作不可撤销。", "deleteConfirmBody": "确定删除「{name}」?此操作不可撤销。",
"secretsRequired": "新建存储需填写 Access Key 与 Secret Key", "secretsRequired": "新建存储需填写 Access Key 与 Secret Key",
"manageStorage": "管理对象存储", "manageStorage": "管理对象存储",
"manageStorageHint": "配置 R2 / S3 / COS 等多后端与直链策略" "manageStorageHint": "配置 R2 / S3 / COS 等多后端与直链策略",
"backup": {
"sectionTitle": "备份与迁移",
"sectionSubtitle": "整站备份恢复与跨后端图片迁移",
"siteTitle": "站点备份与恢复",
"siteSubtitle": "用于换机、灾备与整站恢复",
"siteFooterHint": "备份包含数据库与图片,不包含 secret_json 明文。",
"exportTitle": "创建站点备份",
"exportSubtitle": "打包数据库与全部图片为 .phost.tar.gz",
"exportAction": "开始备份",
"exportStarted": "备份任务已开始",
"exportFailed": "创建备份失败",
"exportPathHint": "导出文件保存在 data/backups/",
"exportIncludesTitle": "备份包含",
"exportIncludesDb": "数据库快照(pichost.db)",
"exportIncludesImages": "全部图片文件({count} 张)",
"exportExcludesSecrets": "不含云存储 secret.json 明文",
"exportConcurrencyHint": "同时仅可运行一个备份或迁移任务",
"estimateLoading": "正在估算体积…",
"estimateImageCountLabel": "图片总数",
"estimatePackageSizeLabel": "预计备份包",
"estimateDatabaseSnapshotLabel": "数据库快照",
"estimateStoragePathLabel": "保存位置",
"estimateStoragePathValue": "data/backups/",
"estimateImages": "图片 {count} 张 · {size}",
"estimateDatabase": "数据库约 {size}",
"estimateTotal": "合计约 {size}",
"restoreTitle": "从备份恢复",
"restoreSubtitle": "上传或选择服务器上的 .phost.tar.gz,预检后确认恢复",
"restoreUpload": "选择备份文件",
"restoreUploadLabel": "本地上传",
"restoreUploadHint": "点击选择 .phost.tar.gz 备份包",
"restoreUploadAction": "上传备份恢复",
"restoreServerAction": "选择服务器备份",
"restoreServerPackages": "服务器已有备份",
"restoreServerSelectPlaceholder": "选择备份包",
"restorePreview": "预检",
"restorePreviewConfirm": "预检并确认",
"restoreConfirm": "确认恢复",
"restoreConfirmTitle": "确认恢复站点",
"restoreConfirmSource": "来源:{name}",
"restoreOverwriteWarning": "覆盖模式将替换冲突图片与数据库,请确认已做好当前站点备份",
"restoreSelectRequired": "请选择或上传备份文件",
"restoreStarted": "恢复任务已开始",
"restoreFailed": "恢复失败",
"conflictMode": "冲突策略",
"conflictSkip": "跳过已存在图片",
"conflictOverwrite": "覆盖已存在图片与数据库",
"syncTitle": "跨后端同步",
"syncMigrateTitle": "跨后端迁移",
"syncMigrateSubtitle": "在已配置后端之间迁移图片",
"syncSubtitle": "在已配置的后端之间拷贝图片并更新索引",
"syncFrom": "源后端",
"syncTo": "目标后端",
"syncPendingImages": "待迁移图片",
"syncPendingSize": "预计体积",
"syncIncludesTitle": "同步说明",
"syncIncludesCopy": "拷贝源端图片文件到目标后端",
"syncIncludesIndex": "更新索引中的 storage_backend_id",
"syncIncludesConfig": "不修改站点配置与其它后端数据",
"syncDryRun": "仅预览 Dry Run",
"syncSetDefaultAfter": "迁移后设为默认后端",
"syncStartMigrate": "开始迁移",
"syncPreviewOnly": "预览",
"syncFooterHint": "仅迁移图片文件与索引,不影响站点配置。",
"syncDeleteSource": "同步后删除源端文件",
"syncSetDefault": "同步后将目标设为默认",
"syncPreview": "预检并开始",
"syncConfirm": "开始同步",
"syncConfirmTitle": "确认跨后端同步",
"syncDeleteWarning": "将删除源后端上的图片文件,此操作不可撤销",
"syncSelectRequired": "请选择源与目标后端",
"syncSameBackend": "源与目标不能相同",
"syncStarted": "同步任务已开始",
"syncFailed": "同步失败",
"previewFailed": "预检失败",
"previewImages": "图片数量",
"previewNew": "新增图片",
"previewConflicts": "冲突图片",
"previewCreated": "备份时间",
"previewSize": "数据量",
"jobsTitle": "最近任务",
"jobsSubtitle": "查看备份、恢复与迁移进度",
"jobsEmpty": "暂无备份或迁移任务",
"jobsEmptyHint": "导出、恢复或同步开始后,进度会显示在这里",
"jobsUnit": "条任务",
"colTask": "任务",
"colType": "类型",
"colStatus": "状态",
"colProgress": "进度",
"colMessage": "说明",
"colCreated": "创建时间",
"colActions": "操作",
"jobTypeExport": "站点导出",
"jobTypeRestore": "站点恢复",
"jobTypeSync": "跨后端同步",
"statusPending": "等待中",
"statusRunning": "进行中",
"statusDone": "已完成",
"statusFailed": "失败",
"jobFailedUnknown": "未知错误",
"download": "下载",
"jobView": "查看",
"retry": "重试",
"retryStarted": "重试任务已开始",
"retryFailed": "重试失败",
"jobRunning": "已有任务正在运行,请稍后再试",
"migrateIn": "迁入",
"migrateOut": "迁出",
"migrateInHint": "从默认后端拷贝图片到此后端",
"migrateOutHint": "将图片从此后端迁出",
"syncDraftApplied": "已填入同步表单,请确认后开始",
"syncNeedTwoBackends": "至少需要两个存储后端才能同步",
"selectBackend": "选择后端",
"syncConfirmRoute": "{from} → {to}",
"cancel": "取消",
"cancelDone": "任务已取消",
"cancelFailed": "取消任务失败"
}
}, },
"stats": { "stats": {
"title": "图库", "title": "图库",
@@ -465,20 +714,28 @@
}, },
"logs": { "logs": {
"pageTitle": "操作日志", "pageTitle": "操作日志",
"pageSubtitle": "查看您的上传与删除记录", "pageSubtitle": "查看您的操作记录",
"pageSubtitleAdmin": "查看所有用户的上传与删除记录", "pageSubtitleAdmin": "查看所有用户的操作记录",
"loadFailed": "加载操作日志失败", "loadFailed": "加载操作日志失败",
"empty": "暂无操作记录", "empty": "暂无操作记录",
"entriesUnit": "条记录", "entriesUnit": "条记录",
"filterActionAll": "全部操作", "filterActionAll": "全部操作",
"filterSourceAll": "全部来源", "filterSourceAll": "全部来源",
"filterUserAll": "全部用户", "filterUserAll": "全部用户",
"searchPlaceholder": "搜索文件名", "searchPlaceholder": "搜索文件名、路径或 IP",
"dateFrom": "开始日期",
"dateTo": "结束日期",
"dateRangeSeparator": "~",
"summaryAll": "全部 · 共 {total} 条记录,上传 {upload} 条,删除 {delete} 条", "summaryAll": "全部 · 共 {total} 条记录,上传 {upload} 条,删除 {delete} 条",
"actionUpload": "上传", "actionUpload": "上传",
"actionDelete": "删除", "actionDelete": "删除",
"actionLogin": "登录",
"actionEdit": "编辑",
"actionSettings": "设置",
"actionTags": "标签",
"sourceWeb": "网页", "sourceWeb": "网页",
"sourceApi": "API", "sourceApi": "API",
"sourceAdmin": "管理后台",
"colTime": "时间", "colTime": "时间",
"colUser": "用户", "colUser": "用户",
"colStorage": "存储", "colStorage": "存储",
@@ -487,7 +744,11 @@
"colFile": "文件名", "colFile": "文件名",
"colFolder": "目录", "colFolder": "目录",
"colSize": "大小", "colSize": "大小",
"colKey": "路径" "colKey": "路径",
"colIp": "IP 地址",
"colResult": "操作结果",
"resultSuccess": "成功",
"resultFailure": "失败"
}, },
"image": { "image": {
"empty": "暂无图片", "empty": "暂无图片",
@@ -593,11 +854,15 @@
"image": "上传图片,主字段", "image": "上传图片,主字段",
"file": "兼容字段,单图上传", "file": "兼容字段,单图上传",
"files": "兼容字段,多图上传", "files": "兼容字段,多图上传",
"token": "Twikoo 协议兼容,表单 token" "token": "Twikoo 协议兼容,表单 token",
"tagIds": "可选,JSON 数组或重复字段,上传后自动打标"
}, },
"list": { "list": {
"limit": "每页条数,默认 20,最大 100", "limit": "每页条数,默认 20,最大 100",
"page": "页码,从 1 开始" "page": "页码,从 1 开始",
"tagIds": "按标签筛选,逗号分隔 ID;与 untagged、tagMode 配合",
"tagMode": "多标签时 or(默认)或 and",
"untagged": "设为 1 仅显示无标签图片"
}, },
"search": { "search": {
"q": "搜索关键词,必填" "q": "搜索关键词,必填"
+29 -6
View File
@@ -1,12 +1,12 @@
{ {
"name": "pichost", "name": "pichost",
"version": "1.2.8", "version": "1.4.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "pichost", "name": "pichost",
"version": "1.2.8", "version": "1.4.0",
"hasInstallScript": true, "hasInstallScript": true,
"license": "GPL-3.0-only", "license": "GPL-3.0-only",
"dependencies": { "dependencies": {
@@ -17,11 +17,13 @@
"cap-widget": "^0.1.57", "cap-widget": "^0.1.57",
"nuxt": "^4.4.8", "nuxt": "^4.4.8",
"sharp": "^0.35.3", "sharp": "^0.35.3",
"tailwindcss": "^4.3.1" "tailwindcss": "^4.3.1",
"tar": "^7.5.22"
}, },
"devDependencies": { "devDependencies": {
"@nuxt/eslint": "^1.16.0", "@nuxt/eslint": "^1.16.0",
"@types/node": "^22.15.0", "@types/node": "^22.15.0",
"@types/tar": "^6.1.13",
"eslint": "^10.6.0", "eslint": "^10.6.0",
"mermaid": "^11.17.2", "mermaid": "^11.17.2",
"typescript": "^6.0.3", "typescript": "^6.0.3",
@@ -8772,6 +8774,27 @@
"integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==", "integrity": "sha512-60BCwRFOZCQhDncwQdxxeOEEkbc5dIMccYLwbxsS4TUNeVECQ/pBJ0j09mrHOl/JJvpRPGwO9SvE4nR2Nb/a4Q==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/tar": {
"version": "6.1.13",
"resolved": "https://registry.npmmirror.com/@types/tar/-/tar-6.1.13.tgz",
"integrity": "sha512-IznnlmU5f4WcGTh2ltRu/Ijpmk8wiWXfF0VA4s+HPjHZgvFggk1YaIkbo5krX/zUCzWF8N/l4+W/LNxnvAJ8nw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
"minipass": "^4.0.0"
}
},
"node_modules/@types/tar/node_modules/minipass": {
"version": "4.2.8",
"resolved": "https://registry.npmmirror.com/minipass/-/minipass-4.2.8.tgz",
"integrity": "sha512-fNzuVyifolSLFL4NzpF+wEF4qrgqaaKX0haXPQEdQ7NKAN+WecoKMHV09YcuL/DHxrUsYQOK3MiuDf7Ip2OXfQ==",
"dev": true,
"license": "ISC",
"engines": {
"node": ">=8"
}
},
"node_modules/@types/trusted-types": { "node_modules/@types/trusted-types": {
"version": "2.0.7", "version": "2.0.7",
"resolved": "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz", "resolved": "https://registry.npmmirror.com/@types/trusted-types/-/trusted-types-2.0.7.tgz",
@@ -18797,9 +18820,9 @@
} }
}, },
"node_modules/tar": { "node_modules/tar": {
"version": "7.5.20", "version": "7.5.22",
"resolved": "https://registry.npmmirror.com/tar/-/tar-7.5.20.tgz", "resolved": "https://registry.npmmirror.com/tar/-/tar-7.5.22.tgz",
"integrity": "sha512-9FcyK4PA6+WbzlTM9WhQm6vB5W7cP7dUiPsv1g7YDwEQnQ1CGpK3MGlKk/ITVWMk05kHZuBhmVhiv8LZoy/PFQ==", "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
"license": "BlueOak-1.0.0", "license": "BlueOak-1.0.0",
"dependencies": { "dependencies": {
"@isaacs/fs-minipass": "^4.0.0", "@isaacs/fs-minipass": "^4.0.0",
+7 -3
View File
@@ -1,6 +1,6 @@
{ {
"name": "pichost", "name": "pichost",
"version": "1.2.8", "version": "1.4.0",
"description": "Self-hosted image hosting for your NAS / home server — Nuxt admin UI, local disk or S3-compatible storage, server-side WebP compression, referer protection, Twikoo/EasyImage compatible.", "description": "Self-hosted image hosting for your NAS / home server — Nuxt admin UI, local disk or S3-compatible storage, server-side WebP compression, referer protection, Twikoo/EasyImage compatible.",
"homepage": "https://github.com/O96u/PicHost#readme", "homepage": "https://github.com/O96u/PicHost#readme",
"repository": { "repository": {
@@ -34,9 +34,11 @@
"test:watch": "vitest", "test:watch": "vitest",
"start": "node .output/server/index.mjs", "start": "node .output/server/index.mjs",
"reset-password": "node server/cli/reset-password.mjs", "reset-password": "node server/cli/reset-password.mjs",
"migrate": "node server/cli/migrate-to-single-images.mjs",
"slider": "node server/cli/slider.mjs", "slider": "node server/cli/slider.mjs",
"clear-domains": "node server/cli/clear-domains.mjs", "clear-domains": "node server/cli/clear-domains.mjs",
"backup-export": "node server/cli/backup-export.mjs",
"backup-restore": "node server/cli/backup-restore.mjs",
"storage-sync": "node server/cli/storage-sync.mjs",
"docs:prepare": "node docs-site/copy-screenshots.mjs", "docs:prepare": "node docs-site/copy-screenshots.mjs",
"docs:dev": "npm run docs:prepare && vitepress dev docs-site", "docs:dev": "npm run docs:prepare && vitepress dev docs-site",
"docs:build": "npm run docs:prepare && vitepress build docs-site", "docs:build": "npm run docs:prepare && vitepress build docs-site",
@@ -50,11 +52,13 @@
"cap-widget": "^0.1.57", "cap-widget": "^0.1.57",
"nuxt": "^4.4.8", "nuxt": "^4.4.8",
"sharp": "^0.35.3", "sharp": "^0.35.3",
"tailwindcss": "^4.3.1" "tailwindcss": "^4.3.1",
"tar": "^7.5.22"
}, },
"devDependencies": { "devDependencies": {
"@nuxt/eslint": "^1.16.0", "@nuxt/eslint": "^1.16.0",
"@types/node": "^22.15.0", "@types/node": "^22.15.0",
"@types/tar": "^6.1.13",
"eslint": "^10.6.0", "eslint": "^10.6.0",
"mermaid": "^11.17.2", "mermaid": "^11.17.2",
"typescript": "^6.0.3", "typescript": "^6.0.3",
+40
View File
@@ -0,0 +1,40 @@
import { requireAdminAuth } from '../../../utils/access'
import { getBackupExportEstimate } from '../../../utils/backup/stats'
import { getBackupsDir, isSafeBackupFilename } from '../../../utils/backup/paths'
import { promises as fs } from 'node:fs'
import { join } from 'node:path'
export default defineEventHandler(async (event) => {
await requireAdminAuth(event)
const estimate = await getBackupExportEstimate()
const packages = await (async () => {
try {
await fs.mkdir(getBackupsDir(), { recursive: true })
const entries = await fs.readdir(getBackupsDir(), { withFileTypes: true })
const items = await Promise.all(
entries
.filter(entry => entry.isFile() && isSafeBackupFilename(entry.name))
.map(async (entry) => {
const full = join(getBackupsDir(), entry.name)
const fileStat = await fs.stat(full)
return {
name: entry.name,
bytes: fileStat.size,
modifiedAt: fileStat.mtime.toISOString()
}
})
)
items.sort((a, b) => b.modifiedAt.localeCompare(a.modifiedAt))
return items
} catch {
return []
}
})()
return {
estimate,
backupsDir: getBackupsDir(),
packages
}
})
+26
View File
@@ -0,0 +1,26 @@
import { requireAdminAuth } from '../../../utils/access'
import { createApiError } from '../../../utils/api-error'
import { serializeBackupJob } from '../../../utils/backup/api'
import { getBackupExportEstimate } from '../../../utils/backup/stats'
import { startFullExportJob } from '../../../utils/backup/runner'
export default defineEventHandler(async (event) => {
await requireAdminAuth(event)
const config = useRuntimeConfig(event)
const appVersion = String(config.appVersion ?? '0.0.0')
const estimate = await getBackupExportEstimate()
try {
const job = startFullExportJob(appVersion)
return {
job: serializeBackupJob(job),
estimate
}
} catch (error) {
if (error instanceof Error && error.message === 'BACKUP_JOB_RUNNING') {
createApiError(event, 'CONFLICT', '已有备份或迁移任务正在运行', 409)
}
throw error
}
})
Loaded 100 of 159 files, more files were not shown because too many files have changed in this diff. Show more