Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ed4692f5e |
No files matched your search
@@ -4,6 +4,20 @@
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.4.2] - 2026-09-23
|
||||
|
||||
### 修复
|
||||
|
||||
- 图库批量打标:管理员/跨归属场景下标签解析与失败提示
|
||||
- 上传鉴权:`Auth-Token` 与表单 `token` 优先于会话;兼容全局 `API_UPLOAD_TOKEN`(上传归属首位管理员)
|
||||
|
||||
### 改进
|
||||
|
||||
- **API 页**:每账号单一 API Token,界面与文档统一
|
||||
- **上传 API**:仅支持 `tagNames`(按名创建或复用标签);Twikoo 兼容路由同步
|
||||
- **标签管理**:按图片数/最近使用排序;桌面列布局;窄屏卡片列表
|
||||
- **API 文档**:参数表列宽,避免 form-data 列异常换行
|
||||
|
||||
## [1.4.1] - 2026-09-16
|
||||
|
||||
### 新增
|
||||
|
||||
+449
-130
@@ -8,12 +8,15 @@ import {
|
||||
TAG_COLOR_EDIT_CANDIDATE_COUNT
|
||||
} from '~/utils/tag-colors'
|
||||
|
||||
const props = withDefaults(defineProps<{
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
tags: ImageTag[]
|
||||
embedded?: boolean
|
||||
}>(), {
|
||||
}>(),
|
||||
{
|
||||
embedded: false
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
const emit = defineEmits<{
|
||||
changed: []
|
||||
@@ -27,7 +30,9 @@ 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 newColor = ref(
|
||||
pickDefaultTagColorFromCandidates(newColorCandidates.value, [])
|
||||
)
|
||||
const search = ref('')
|
||||
const statusFilter = ref<'all' | 'used' | 'unused'>('all')
|
||||
const selectedIds = ref<Set<number>>(new Set())
|
||||
@@ -47,6 +52,10 @@ const saving = ref(false)
|
||||
const page = ref(1)
|
||||
const pageSize = ref(10)
|
||||
|
||||
type TagSortKey = 'imageCount' | 'lastUsedAt'
|
||||
const sortKey = ref<TagSortKey>('imageCount')
|
||||
const sortDir = ref<'asc' | 'desc'>('desc')
|
||||
|
||||
const stats = computed(() => {
|
||||
const now = Date.now()
|
||||
const sevenDaysAgo = now - 7 * 24 * 60 * 60 * 1000
|
||||
@@ -71,15 +80,31 @@ const stats = computed(() => {
|
||||
|
||||
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
|
||||
const list = 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 dir = sortDir.value === 'asc' ? 1 : -1
|
||||
return list.sort((a, b) => {
|
||||
let cmp = 0
|
||||
if (sortKey.value === 'imageCount') {
|
||||
cmp = (a.imageCount ?? 0) - (b.imageCount ?? 0)
|
||||
} else {
|
||||
cmp = lastUsedSortTime(a) - lastUsedSortTime(b)
|
||||
}
|
||||
if (cmp !== 0) return cmp * dir
|
||||
return a.name.localeCompare(b.name)
|
||||
})
|
||||
})
|
||||
|
||||
const totalPages = computed(() => Math.max(1, Math.ceil(filteredTags.value.length / pageSize.value)))
|
||||
const totalPages = computed(() =>
|
||||
Math.max(1, Math.ceil(filteredTags.value.length / pageSize.value))
|
||||
)
|
||||
|
||||
const paginatedTags = computed(() => {
|
||||
const start = (page.value - 1) * pageSize.value
|
||||
@@ -96,7 +121,8 @@ watch(filteredTags, (list) => {
|
||||
}
|
||||
})
|
||||
|
||||
const selectedList = computed(() =>
|
||||
const selectedList = computed(
|
||||
() =>
|
||||
[...selectedIds.value]
|
||||
.map(id => props.tags.find(tag => tag.id === id))
|
||||
.filter(Boolean) as ImageTag[]
|
||||
@@ -104,12 +130,14 @@ const selectedList = computed(() =>
|
||||
|
||||
const selectedCount = computed(() => selectedIds.value.size)
|
||||
|
||||
const allPageSelected = computed(() =>
|
||||
const allPageSelected = computed(
|
||||
() =>
|
||||
paginatedTags.value.length > 0
|
||||
&& paginatedTags.value.every(tag => selectedIds.value.has(tag.id))
|
||||
)
|
||||
|
||||
const mergeSourceTags = computed(() =>
|
||||
const mergeSourceTags = computed(
|
||||
() =>
|
||||
mergeSourceIds.value
|
||||
.map(id => props.tags.find(tag => tag.id === id))
|
||||
.filter(Boolean) as ImageTag[]
|
||||
@@ -119,7 +147,11 @@ 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))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
(b.imageCount ?? 0) - (a.imageCount ?? 0)
|
||||
|| a.name.localeCompare(b.name)
|
||||
)
|
||||
})
|
||||
|
||||
const mergeTagsToDelete = computed(() => {
|
||||
@@ -127,8 +159,8 @@ const mergeTagsToDelete = computed(() => {
|
||||
return mergeSourceTags.value.filter(tag => tag.id !== mergeTargetId.value)
|
||||
})
|
||||
|
||||
const mergeKeepTag = computed(() =>
|
||||
props.tags.find(tag => tag.id === mergeTargetId.value) ?? null
|
||||
const mergeKeepTag = computed(
|
||||
() => props.tags.find(tag => tag.id === mergeTargetId.value) ?? null
|
||||
)
|
||||
|
||||
const statusItems = computed(() => [
|
||||
@@ -137,28 +169,71 @@ const statusItems = computed(() => [
|
||||
{ label: t('tags.filterStatusUnused'), value: 'unused' }
|
||||
])
|
||||
|
||||
const statValueClass = computed(() =>
|
||||
'mt-2 text-2xl font-semibold tabular-nums text-highlighted'
|
||||
function tagSortTime(iso: string | null | undefined): number {
|
||||
if (!iso) return 0
|
||||
const time = new Date(iso).getTime()
|
||||
return Number.isNaN(time) ? 0 : time
|
||||
}
|
||||
|
||||
function lastUsedSortTime(tag: ImageTag): number {
|
||||
if ((tag.imageCount ?? 0) === 0) return 0
|
||||
return tagSortTime(tag.lastUsedAt)
|
||||
}
|
||||
|
||||
function toggleSort(key: TagSortKey) {
|
||||
if (sortKey.value === key) {
|
||||
sortDir.value = sortDir.value === 'asc' ? 'desc' : 'asc'
|
||||
} else {
|
||||
sortKey.value = key
|
||||
sortDir.value = 'desc'
|
||||
}
|
||||
page.value = 1
|
||||
}
|
||||
|
||||
function sortIcon(key: TagSortKey): string {
|
||||
if (sortKey.value !== key) return 'i-lucide-arrow-up-down'
|
||||
return sortDir.value === 'asc' ? 'i-lucide-arrow-up' : 'i-lucide-arrow-down'
|
||||
}
|
||||
|
||||
function sortIconClass(key: TagSortKey): string {
|
||||
const base = 'size-3 shrink-0'
|
||||
return sortKey.value === key
|
||||
? `${base} opacity-70`
|
||||
: `${base} opacity-40`
|
||||
}
|
||||
|
||||
const statValueClass = computed(
|
||||
() => 'mt-2 text-2xl font-semibold tabular-nums text-highlighted'
|
||||
)
|
||||
|
||||
const tableTextClass = computed(() => 'text-sm')
|
||||
|
||||
const tagRowClass = 'flex items-center gap-x-3 px-3'
|
||||
|
||||
const tagNameColClass = 'min-w-0 flex-1 basis-0 pr-8 sm:pr-12'
|
||||
|
||||
const tagRightGroupClass
|
||||
= 'ml-auto flex shrink-0 items-center gap-x-8 sm:gap-x-10'
|
||||
|
||||
const tagCountColClass
|
||||
= 'w-44 shrink-0 text-left tabular-nums whitespace-nowrap sm:w-48'
|
||||
|
||||
const tagLastColClass
|
||||
= 'w-[10.5rem] shrink-0 whitespace-nowrap text-xs text-muted'
|
||||
|
||||
const tagActionsColClass = 'w-[9.5rem] shrink-0'
|
||||
|
||||
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',
|
||||
try {
|
||||
return new Date(tag.lastUsedAt).toLocaleString(locale.value, {
|
||||
hour12: false
|
||||
})
|
||||
} catch {
|
||||
return t('tags.neverUsed')
|
||||
}
|
||||
}
|
||||
|
||||
function toggleSelect(id: number) {
|
||||
@@ -191,7 +266,10 @@ function usedColorsExcept(tagId?: number) {
|
||||
function refreshNewTagColor() {
|
||||
const used = usedColorsExcept()
|
||||
newColorCandidates.value = pickTagColorCandidates(used)
|
||||
newColor.value = pickDefaultTagColorFromCandidates(newColorCandidates.value, used)
|
||||
newColor.value = pickDefaultTagColorFromCandidates(
|
||||
newColorCandidates.value,
|
||||
used
|
||||
)
|
||||
}
|
||||
|
||||
function toggleCreating() {
|
||||
@@ -303,7 +381,10 @@ async function confirmDelete() {
|
||||
selectedIds.value.delete(tag.id)
|
||||
selectedIds.value = new Set(selectedIds.value)
|
||||
emit('changed')
|
||||
toast.add({ title: t('tags.deleted', { name: tag.name }), color: 'success' })
|
||||
toast.add({
|
||||
title: t('tags.deleted', { name: tag.name }),
|
||||
color: 'success'
|
||||
})
|
||||
} catch {
|
||||
toast.add({ title: t('tags.deleteFailed'), color: 'error' })
|
||||
} finally {
|
||||
@@ -318,7 +399,9 @@ function openBatchMerge() {
|
||||
}
|
||||
mergeMode.value = 'batch'
|
||||
mergeSourceIds.value = [...selectedIds.value]
|
||||
const sorted = selectedList.value.sort((a, b) => (b.imageCount ?? 0) - (a.imageCount ?? 0))
|
||||
const sorted = selectedList.value.sort(
|
||||
(a, b) => (b.imageCount ?? 0) - (a.imageCount ?? 0)
|
||||
)
|
||||
mergeTargetId.value = sorted[0]?.id ?? null
|
||||
mergeOpen.value = true
|
||||
}
|
||||
@@ -335,14 +418,18 @@ function openSingleMerge(tag: ImageTag) {
|
||||
|
||||
function requestMergeConfirm() {
|
||||
if (!mergeTargetId.value) return
|
||||
const sourceIds = mergeSourceIds.value.filter(id => id !== mergeTargetId.value)
|
||||
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)
|
||||
const sourceIds = mergeSourceIds.value.filter(
|
||||
id => id !== mergeTargetId.value
|
||||
)
|
||||
if (!sourceIds.length) return
|
||||
saving.value = true
|
||||
try {
|
||||
@@ -365,13 +452,15 @@ async function confirmMerge() {
|
||||
<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">
|
||||
<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') }}
|
||||
{{ t("tags.statTotal") }}
|
||||
</div>
|
||||
<p :class="statValueClass">
|
||||
{{ stats.total }}
|
||||
@@ -379,13 +468,15 @@ async function confirmMerge() {
|
||||
</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">
|
||||
<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') }}
|
||||
{{ t("tags.statUsed") }}
|
||||
</div>
|
||||
<p :class="statValueClass">
|
||||
{{ stats.used }}
|
||||
@@ -393,13 +484,15 @@ async function confirmMerge() {
|
||||
</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">
|
||||
<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') }}
|
||||
{{ t("tags.statUnused") }}
|
||||
</div>
|
||||
<p :class="statValueClass">
|
||||
{{ stats.unused }}
|
||||
@@ -407,13 +500,15 @@ async function confirmMerge() {
|
||||
</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">
|
||||
<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') }}
|
||||
{{ t("tags.statNew7d") }}
|
||||
</div>
|
||||
<p :class="statValueClass">
|
||||
{{ stats.newIn7Days }}
|
||||
@@ -443,7 +538,7 @@ async function confirmMerge() {
|
||||
icon="i-lucide-plus"
|
||||
@click="toggleCreating"
|
||||
>
|
||||
{{ t('tags.addTag') }}
|
||||
{{ t("tags.addTag") }}
|
||||
</UButton>
|
||||
<UButton
|
||||
type="button"
|
||||
@@ -454,7 +549,7 @@ async function confirmMerge() {
|
||||
:disabled="selectedCount < 2"
|
||||
@click="openBatchMerge"
|
||||
>
|
||||
{{ t('tags.mergeTags') }}
|
||||
{{ t("tags.mergeTags") }}
|
||||
</UButton>
|
||||
</div>
|
||||
</div>
|
||||
@@ -464,7 +559,7 @@ async function confirmMerge() {
|
||||
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 }) }}
|
||||
{{ t("tags.mergeSelected", { n: selectedCount }) }}
|
||||
</span>
|
||||
<UButton
|
||||
size="xs"
|
||||
@@ -472,7 +567,7 @@ async function confirmMerge() {
|
||||
color="neutral"
|
||||
@click="clearSelection"
|
||||
>
|
||||
{{ t('tags.mergeClear') }}
|
||||
{{ t("tags.mergeClear") }}
|
||||
</UButton>
|
||||
</div>
|
||||
|
||||
@@ -498,11 +593,9 @@ async function confirmMerge() {
|
||||
class="shrink-0 pt-1"
|
||||
>
|
||||
<p class="mb-1.5 text-xs text-muted">
|
||||
{{ t('tags.preview') }}
|
||||
{{ t("tags.preview") }}
|
||||
</p>
|
||||
<TagBadge
|
||||
:tag="{ id: 0, name: newName.trim(), color: newColor }"
|
||||
/>
|
||||
<TagBadge :tag="{ id: 0, name: newName.trim(), color: newColor }" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-end gap-2 border-t border-default pt-3">
|
||||
@@ -510,9 +603,13 @@ async function confirmMerge() {
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
color="neutral"
|
||||
@click="() => { creating = false }"
|
||||
@click="
|
||||
() => {
|
||||
creating = false;
|
||||
}
|
||||
"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
{{ t("common.cancel") }}
|
||||
</UButton>
|
||||
<UButton
|
||||
size="sm"
|
||||
@@ -521,59 +618,73 @@ async function confirmMerge() {
|
||||
:disabled="!newName.trim()"
|
||||
@click="handleCreate"
|
||||
>
|
||||
{{ t('common.save') }}
|
||||
{{ 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"
|
||||
<div
|
||||
v-if="!paginatedTags.length"
|
||||
class="px-3 py-12 text-center text-sm text-muted"
|
||||
>
|
||||
{{ tags.length ? t("tags.noMatch") : t("tags.emptyHint") }}
|
||||
</div>
|
||||
|
||||
<!-- 手机:卡片列表 -->
|
||||
<template v-else>
|
||||
<div class="sm:hidden">
|
||||
<div
|
||||
class="flex items-center gap-2 border-b border-default bg-elevated/60 px-3 py-2.5 text-xs text-muted"
|
||||
>
|
||||
<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'"
|
||||
<span class="min-w-0 flex-1 font-medium">{{ t("tags.colName") }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-0.5 font-medium text-inherit"
|
||||
@click="toggleSort('imageCount')"
|
||||
>
|
||||
<td class="px-3 py-3 align-middle">
|
||||
{{ t("tags.colImageCount") }}
|
||||
<UIcon
|
||||
:name="sortIcon('imageCount')"
|
||||
:class="sortIconClass('imageCount')"
|
||||
/>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex shrink-0 items-center gap-0.5 font-medium text-inherit"
|
||||
@click="toggleSort('lastUsedAt')"
|
||||
>
|
||||
{{ t("tags.colLastUsed") }}
|
||||
<UIcon
|
||||
:name="sortIcon('lastUsedAt')"
|
||||
:class="sortIconClass('lastUsedAt')"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<article
|
||||
v-for="tag in paginatedTags"
|
||||
:key="`mobile-${tag.id}`"
|
||||
class="border-b border-default px-3 py-3 last:border-b-0"
|
||||
:class="selectedIds.has(tag.id) ? 'bg-primary/5' : ''"
|
||||
>
|
||||
<div class="flex items-start gap-2">
|
||||
<UCheckbox
|
||||
class="mt-0.5"
|
||||
:model-value="selectedIds.has(tag.id)"
|
||||
@update:model-value="toggleSelect(tag.id)"
|
||||
/>
|
||||
</td>
|
||||
<td class="px-3 py-3 align-middle">
|
||||
<div class="min-w-0 flex-1">
|
||||
<UInput
|
||||
v-if="renamingId === tag.id"
|
||||
v-model="renameValue"
|
||||
size="sm"
|
||||
class="max-w-xs"
|
||||
class="w-full max-w-none"
|
||||
autofocus
|
||||
@keydown.enter.prevent="finishRename(tag.id)"
|
||||
@keydown.esc.prevent="cancelRename"
|
||||
@@ -583,16 +694,21 @@ async function confirmMerge() {
|
||||
v-else
|
||||
:tag="tag"
|
||||
size="sm"
|
||||
class="max-w-full truncate"
|
||||
/>
|
||||
</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">
|
||||
<div
|
||||
class="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 text-xs text-muted"
|
||||
>
|
||||
<span class="tabular-nums">
|
||||
{{ t("tags.colImageCount") }} {{ tag.imageCount ?? 0 }}
|
||||
</span>
|
||||
<span class="min-w-0 break-all">
|
||||
{{ formatLastUsed(tag) }}
|
||||
</td>
|
||||
<td class="px-3 py-3 align-middle">
|
||||
<div class="flex items-center justify-end gap-0.5">
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-2 flex flex-wrap justify-end gap-0.5">
|
||||
<UButton
|
||||
type="button"
|
||||
size="xs"
|
||||
@@ -605,7 +721,11 @@ async function confirmMerge() {
|
||||
<UPopover
|
||||
:open="colorPickerId === tag.id"
|
||||
:content="{ side: 'bottom', align: 'end' }"
|
||||
@update:open="(open) => { colorPickerId = open ? tag.id : null }"
|
||||
@update:open="
|
||||
(open) => {
|
||||
colorPickerId = open ? tag.id : null;
|
||||
}
|
||||
"
|
||||
>
|
||||
<UButton
|
||||
type="button"
|
||||
@@ -658,19 +778,178 @@ async function confirmMerge() {
|
||||
@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>
|
||||
</article>
|
||||
</div>
|
||||
|
||||
<!-- 桌面:表格 -->
|
||||
<div class="hidden sm:block">
|
||||
<div
|
||||
class="border-b border-default bg-elevated/60 text-xs text-muted"
|
||||
:class="[tagRowClass, tableTextClass, 'py-2.5']"
|
||||
>
|
||||
<div class="flex w-10 shrink-0 justify-center">
|
||||
<UCheckbox
|
||||
:model-value="allPageSelected"
|
||||
:disabled="!paginatedTags.length"
|
||||
@update:model-value="toggleSelectAll"
|
||||
/>
|
||||
</div>
|
||||
<div :class="[tagNameColClass, 'font-medium']">
|
||||
{{ t("tags.colName") }}
|
||||
</div>
|
||||
<div :class="tagRightGroupClass">
|
||||
<div :class="[tagCountColClass, 'font-medium']">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-0.5 font-medium text-inherit"
|
||||
@click="toggleSort('imageCount')"
|
||||
>
|
||||
{{ t("tags.colImageCount") }}
|
||||
<UIcon
|
||||
:name="sortIcon('imageCount')"
|
||||
:class="sortIconClass('imageCount')"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<div :class="[tagLastColClass, 'font-medium text-muted']">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-0.5 font-medium text-inherit"
|
||||
@click="toggleSort('lastUsedAt')"
|
||||
>
|
||||
{{ t("tags.colLastUsed") }}
|
||||
<UIcon
|
||||
:name="sortIcon('lastUsedAt')"
|
||||
:class="sortIconClass('lastUsedAt')"
|
||||
/>
|
||||
</button>
|
||||
</div>
|
||||
<div :class="[tagActionsColClass, 'text-right font-medium']">
|
||||
{{ t("tags.colActions") }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-for="tag in paginatedTags"
|
||||
:key="tag.id"
|
||||
class="border-b border-default last:border-b-0"
|
||||
:class="[
|
||||
tagRowClass,
|
||||
tableTextClass,
|
||||
'py-0',
|
||||
selectedIds.has(tag.id) ? 'bg-primary/5' : 'hover:bg-elevated/40'
|
||||
]"
|
||||
>
|
||||
<div class="flex w-10 shrink-0 justify-center py-3">
|
||||
<UCheckbox
|
||||
:model-value="selectedIds.has(tag.id)"
|
||||
@update:model-value="toggleSelect(tag.id)"
|
||||
/>
|
||||
</div>
|
||||
<div :class="[tagNameColClass, 'py-3']">
|
||||
<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"
|
||||
/>
|
||||
</div>
|
||||
<div :class="[tagRightGroupClass, 'py-3']">
|
||||
<div :class="[tagCountColClass, 'text-muted']">
|
||||
{{ tag.imageCount ?? 0 }}
|
||||
</div>
|
||||
<div :class="tagLastColClass">
|
||||
{{ formatLastUsed(tag) }}
|
||||
</div>
|
||||
<div
|
||||
:class="[
|
||||
tagActionsColClass,
|
||||
'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>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<PaginationBar
|
||||
@@ -680,28 +959,46 @@ async function confirmMerge() {
|
||||
:total="filteredTags.length"
|
||||
:page-size="pageSize"
|
||||
:page-size-options="[10, 20, 30, 50]"
|
||||
@update:page="(value) => { page = value }"
|
||||
@update:page-size="(value) => { pageSize = value }"
|
||||
@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')"
|
||||
: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') }}
|
||||
{{ 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'"
|
||||
:class="
|
||||
mergeTargetId === tag.id
|
||||
? 'border-primary/40 bg-primary/5'
|
||||
: 'hover:bg-elevated'
|
||||
"
|
||||
>
|
||||
<input
|
||||
v-model="mergeTargetId"
|
||||
@@ -711,7 +1008,7 @@ async function confirmMerge() {
|
||||
>
|
||||
<TagBadge :tag="tag" />
|
||||
<span class="ml-auto text-sm text-muted">
|
||||
{{ t('common.countImages', { count: tag.imageCount ?? 0 }) }}
|
||||
{{ t("common.countImages", { count: tag.imageCount ?? 0 }) }}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
@@ -719,14 +1016,18 @@ async function confirmMerge() {
|
||||
|
||||
<template v-else>
|
||||
<p class="mb-2 text-sm text-muted">
|
||||
{{ t('tags.mergeIntoChoose') }}
|
||||
{{ 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'"
|
||||
:class="
|
||||
mergeTargetId === tag.id
|
||||
? 'border-primary/40 bg-primary/5'
|
||||
: 'hover:bg-elevated'
|
||||
"
|
||||
>
|
||||
<input
|
||||
v-model="mergeTargetId"
|
||||
@@ -736,7 +1037,7 @@ async function confirmMerge() {
|
||||
>
|
||||
<TagBadge :tag="tag" />
|
||||
<span class="ml-auto text-sm text-muted">
|
||||
{{ t('common.countImages', { count: tag.imageCount ?? 0 }) }}
|
||||
{{ t("common.countImages", { count: tag.imageCount ?? 0 }) }}
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
@@ -748,9 +1049,13 @@ async function confirmMerge() {
|
||||
<UButton
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="() => { mergeOpen = false }"
|
||||
@click="
|
||||
() => {
|
||||
mergeOpen = false;
|
||||
}
|
||||
"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
{{ t("common.cancel") }}
|
||||
</UButton>
|
||||
<UButton
|
||||
color="primary"
|
||||
@@ -758,7 +1063,7 @@ async function confirmMerge() {
|
||||
:disabled="!mergeTargetId"
|
||||
@click="requestMergeConfirm"
|
||||
>
|
||||
{{ t('tags.mergeConfirm') }}
|
||||
{{ t("tags.mergeConfirm") }}
|
||||
</UButton>
|
||||
</div>
|
||||
</template>
|
||||
@@ -772,12 +1077,14 @@ async function confirmMerge() {
|
||||
<template #body>
|
||||
<div class="space-y-3 text-sm">
|
||||
<p v-if="mergeKeepTag">
|
||||
{{ t('tags.mergeConfirmKeep', { name: mergeKeepTag.name }) }}
|
||||
{{ t("tags.mergeConfirmKeep", { name: mergeKeepTag.name }) }}
|
||||
</p>
|
||||
<p v-if="mergeTagsToDelete.length">
|
||||
{{ t('tags.mergeWillDelete', {
|
||||
names: mergeTagsToDelete.map(tag => tag.name).join('、')
|
||||
}) }}
|
||||
{{
|
||||
t("tags.mergeWillDelete", {
|
||||
names: mergeTagsToDelete.map((tag) => tag.name).join("、")
|
||||
})
|
||||
}}
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -787,9 +1094,13 @@ async function confirmMerge() {
|
||||
<UButton
|
||||
variant="outline"
|
||||
color="neutral"
|
||||
@click="() => { mergeConfirmOpen = false }"
|
||||
@click="
|
||||
() => {
|
||||
mergeConfirmOpen = false;
|
||||
}
|
||||
"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
{{ t("common.cancel") }}
|
||||
</UButton>
|
||||
<UButton
|
||||
color="primary"
|
||||
@@ -797,7 +1108,7 @@ async function confirmMerge() {
|
||||
:loading="saving"
|
||||
@click="confirmMerge"
|
||||
>
|
||||
{{ t('tags.mergeConfirm') }}
|
||||
{{ t("tags.mergeConfirm") }}
|
||||
</UButton>
|
||||
</div>
|
||||
</template>
|
||||
@@ -806,16 +1117,24 @@ async function confirmMerge() {
|
||||
<UModal
|
||||
v-model:open="deleteOpen"
|
||||
:title="t('tags.deleteConfirmTitle')"
|
||||
:description="deleteTarget ? t('tags.deleteConfirmDesc', { name: deleteTarget.name }) : ''"
|
||||
: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 }"
|
||||
@click="
|
||||
() => {
|
||||
deleteOpen = false;
|
||||
}
|
||||
"
|
||||
>
|
||||
{{ t('common.cancel') }}
|
||||
{{ t("common.cancel") }}
|
||||
</UButton>
|
||||
<UButton
|
||||
color="error"
|
||||
@@ -823,7 +1142,7 @@ async function confirmMerge() {
|
||||
:loading="saving"
|
||||
@click="confirmDelete"
|
||||
>
|
||||
{{ t('common.delete') }}
|
||||
{{ t("common.delete") }}
|
||||
</UButton>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -38,19 +38,26 @@ const { t } = useI18n()
|
||||
</h3>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full min-w-[32rem] text-left text-sm">
|
||||
<table class="w-full min-w-[36rem] table-fixed text-left text-sm">
|
||||
<colgroup>
|
||||
<col class="w-[5.5rem]">
|
||||
<col class="w-[3.5rem]">
|
||||
<col class="w-[5.75rem]">
|
||||
<col class="w-[3.25rem]">
|
||||
<col>
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr class="border-b border-default text-xs text-muted">
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramName') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramType') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramLocation') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
|
||||
{{ t('api.paramRequired') }}
|
||||
</th>
|
||||
<th class="px-4 py-2.5 font-medium">
|
||||
@@ -64,20 +71,20 @@ const { t } = useI18n()
|
||||
:key="param.name"
|
||||
class="border-b border-default last:border-b-0"
|
||||
>
|
||||
<td class="px-4 py-2.5 font-mono text-xs">
|
||||
<td class="whitespace-nowrap px-4 py-2.5 font-mono text-xs">
|
||||
{{ param.name }}
|
||||
<span
|
||||
v-if="param.required"
|
||||
class="text-error"
|
||||
>*</span>
|
||||
</td>
|
||||
<td class="px-4 py-2.5 text-muted">
|
||||
<td class="whitespace-nowrap px-4 py-2.5 text-muted">
|
||||
{{ param.type }}
|
||||
</td>
|
||||
<td class="px-4 py-2.5 text-muted">
|
||||
<td class="whitespace-nowrap px-4 py-2.5 text-muted">
|
||||
{{ param.location }}
|
||||
</td>
|
||||
<td class="px-4 py-2.5">
|
||||
<td class="whitespace-nowrap px-4 py-2.5">
|
||||
<UBadge
|
||||
:color="param.required ? 'primary' : 'neutral'"
|
||||
variant="subtle"
|
||||
@@ -86,7 +93,7 @@ const { t } = useI18n()
|
||||
{{ param.required ? t('api.required') : t('api.optional') }}
|
||||
</UBadge>
|
||||
</td>
|
||||
<td class="px-4 py-2.5 text-muted">
|
||||
<td class="px-4 py-2.5 leading-relaxed text-muted break-words">
|
||||
{{ t(param.descriptionKey) }}
|
||||
</td>
|
||||
</tr>
|
||||
|
||||
@@ -75,15 +75,6 @@ async function copyToken() {
|
||||
:description="t('api.envOverrideDesc')"
|
||||
/>
|
||||
|
||||
<UAlert
|
||||
v-else-if="!isAdmin"
|
||||
color="info"
|
||||
variant="subtle"
|
||||
icon="i-lucide-info"
|
||||
:title="t('api.personalTitle')"
|
||||
:description="t('api.personalDesc')"
|
||||
/>
|
||||
|
||||
<UAlert
|
||||
v-else-if="!token && !loading"
|
||||
color="info"
|
||||
|
||||
@@ -74,13 +74,6 @@ export function buildApiDocs(ctx: ApiDocsContext): ApiDocEndpoint[] {
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.token'
|
||||
},
|
||||
{
|
||||
name: 'tagIds',
|
||||
type: 'string',
|
||||
location: 'form-data',
|
||||
required: false,
|
||||
descriptionKey: 'api.params.upload.tagIds'
|
||||
},
|
||||
{
|
||||
name: 'tagNames',
|
||||
type: 'string',
|
||||
|
||||
@@ -11,6 +11,7 @@ export function useImageUpload() {
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
const { compressEnabled, clientWebpQuality, lastTagIds } = useUploadPreferences()
|
||||
const { items: tagItems } = useTags()
|
||||
const uploading = ref(false)
|
||||
const progressItems = ref<UploadProgressItem[]>([])
|
||||
const lastUploadResult = ref<UploadResponse | null>(null)
|
||||
@@ -60,7 +61,12 @@ export function useImageUpload() {
|
||||
|
||||
const tagIds = options?.tagIds ?? lastTagIds.value
|
||||
if (tagIds.length) {
|
||||
formData.append('tagIds', JSON.stringify(tagIds))
|
||||
const names = tagIds
|
||||
.map(id => tagItems.value.find(tag => tag.id === id)?.name)
|
||||
.filter((name): name is string => Boolean(name))
|
||||
if (names.length) {
|
||||
formData.append('tagNames', JSON.stringify(names))
|
||||
}
|
||||
lastTagIds.value = tagIds
|
||||
}
|
||||
|
||||
|
||||
+15
-31
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
interface SettingsResponse {
|
||||
interface UserTokenResponse {
|
||||
apiUploadToken: string
|
||||
tokenSource: 'env' | 'db' | 'none'
|
||||
envTokenOverride: boolean
|
||||
@@ -16,7 +16,7 @@ const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus,
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
const settings = ref<SettingsResponse | null>(null)
|
||||
const tokenSettings = ref<UserTokenResponse | null>(null)
|
||||
const loading = ref(false)
|
||||
const regenerating = ref(false)
|
||||
const confirmRegenerateOpen = ref(false)
|
||||
@@ -25,19 +25,17 @@ const newToken = ref('')
|
||||
const activeEndpointId = ref('upload')
|
||||
|
||||
const baseUrl = computed(() => {
|
||||
const configured = settings.value?.env.siteBaseUrl
|
||||
const configured = tokenSettings.value?.env.siteBaseUrl
|
||||
if (configured) return configured
|
||||
if (import.meta.client) {
|
||||
return window.location.origin
|
||||
}
|
||||
return settings.value?.env.imageBaseUrl ?? ''
|
||||
return tokenSettings.value?.env.imageBaseUrl ?? ''
|
||||
})
|
||||
|
||||
const tokenDisplay = computed(() => settings.value?.apiUploadToken ?? '')
|
||||
const tokenDisplay = computed(() => tokenSettings.value?.apiUploadToken ?? '')
|
||||
const hasToken = computed(() => tokenDisplay.value.length > 0)
|
||||
const canRegenerate = computed(() =>
|
||||
!settings.value?.envTokenOverride && !loading.value
|
||||
)
|
||||
const canRegenerate = computed(() => !loading.value)
|
||||
|
||||
const authHeader = computed(() =>
|
||||
hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN'
|
||||
@@ -54,11 +52,10 @@ const activeEndpoint = computed(() =>
|
||||
apiDocs.value.find(endpoint => endpoint.id === activeEndpointId.value) ?? apiDocs.value[0]
|
||||
)
|
||||
|
||||
async function loadSettings() {
|
||||
async function loadTokenSettings() {
|
||||
loading.value = true
|
||||
try {
|
||||
const endpoint = isAdmin.value ? '/api/settings' : '/api/user/api-token'
|
||||
settings.value = await $fetch<SettingsResponse>(endpoint, {
|
||||
tokenSettings.value = await $fetch<UserTokenResponse>('/api/user/api-token', {
|
||||
credentials: 'include'
|
||||
})
|
||||
} catch (error: unknown) {
|
||||
@@ -66,6 +63,7 @@ async function loadSettings() {
|
||||
if (isAuthenticated.value) {
|
||||
toast.add({ title: t('api.loadFailed'), color: 'error' })
|
||||
}
|
||||
tokenSettings.value = null
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -80,31 +78,18 @@ async function confirmRegenerate() {
|
||||
confirmRegenerateOpen.value = false
|
||||
regenerating.value = true
|
||||
try {
|
||||
const endpoint = isAdmin.value
|
||||
? '/api/settings/api-token/regenerate'
|
||||
: '/api/user/api-token/regenerate'
|
||||
const response = await $fetch<{ apiUploadToken: string }>(
|
||||
endpoint,
|
||||
'/api/user/api-token/regenerate',
|
||||
{ method: 'POST', credentials: 'include' }
|
||||
)
|
||||
newToken.value = response.apiUploadToken
|
||||
regenerateResultOpen.value = true
|
||||
await loadSettings()
|
||||
await loadTokenSettings()
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
if (isAuthenticated.value) {
|
||||
const status = typeof error === 'object' && error !== null && 'statusCode' in error
|
||||
? (error as { statusCode: number }).statusCode
|
||||
: 0
|
||||
if (status === 409) {
|
||||
toast.add({
|
||||
title: t('api.regenerateEnvBlocked'),
|
||||
color: 'warning'
|
||||
})
|
||||
} else {
|
||||
toast.add({ title: t('api.regenerateFailed'), color: 'error' })
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
regenerating.value = false
|
||||
}
|
||||
@@ -126,16 +111,16 @@ onMounted(async () => {
|
||||
}
|
||||
await checkSession()
|
||||
if (isAuthenticated.value) {
|
||||
await loadSettings()
|
||||
await loadTokenSettings()
|
||||
}
|
||||
})
|
||||
|
||||
watch(isAuthenticated, async (authed, prev) => {
|
||||
if (authed && prev === false) {
|
||||
await nextTick()
|
||||
await loadSettings()
|
||||
await loadTokenSettings()
|
||||
} else {
|
||||
settings.value = null
|
||||
tokenSettings.value = null
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -174,8 +159,7 @@ watch(isAuthenticated, async (authed, prev) => {
|
||||
:loading="loading"
|
||||
:regenerating="regenerating"
|
||||
:can-regenerate="canRegenerate"
|
||||
:token-source="settings?.tokenSource"
|
||||
:env-token-override="settings?.envTokenOverride"
|
||||
token-source="db"
|
||||
:is-admin="isAdmin"
|
||||
@regenerate="requestRegenerate"
|
||||
/>
|
||||
|
||||
@@ -57,7 +57,7 @@ const {
|
||||
|
||||
const { items: tagItems, fetchTags, batchUpdateTags } = useTags()
|
||||
|
||||
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth()
|
||||
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, getFetchErrorMessage } = useAuth()
|
||||
const toast = useToast()
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -256,7 +256,10 @@ async function confirmBatchTags(tagIds: number[], action: 'add' | 'remove') {
|
||||
await Promise.all([reloadGallery(), fetchStats(), fetchTags(true)])
|
||||
} catch (error: unknown) {
|
||||
handleAuthError(error)
|
||||
toast.add({ title: t('tags.batchFailed'), color: 'error' })
|
||||
toast.add({
|
||||
title: getFetchErrorMessage(error, t('tags.batchFailed')),
|
||||
color: 'error'
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -12,10 +12,10 @@ All REST calls use:
|
||||
Auth-Token: YOUR_TOKEN
|
||||
```
|
||||
|
||||
| Token type | How to obtain | Notes |
|
||||
| ---------- | ------------- | ----- |
|
||||
| **Global** | Admin **API** page or `API_UPLOAD_TOKEN` env | Env wins and blocks UI regenerate |
|
||||
| **Personal** | Each user’s **API** page | Uploads belong to that user |
|
||||
| Token | How to obtain | Notes |
|
||||
| ----- | ------------- | ----- |
|
||||
| **API token** | **API** page after sign-in (one per account, auto-created) | `Auth-Token` header; uploads and tagNames belong to that account |
|
||||
| **Legacy site token** | `API_UPLOAD_TOKEN` env or old admin setting | Still accepted; uploads belong to the **first admin**. Twikoo form `token` also accepts each user’s API token |
|
||||
|
||||
Form uploads may use field `token` (Twikoo protocol).
|
||||
|
||||
@@ -31,10 +31,10 @@ Upload one or more images via `image`; also accepts `file`, `files`. Stored unde
|
||||
curl -X POST "https://admin.example.com/api/images/upload" \
|
||||
-H "Auth-Token: YOUR_TOKEN" \
|
||||
-F "image=@./demo.png" \
|
||||
-F 'tagIds=[1,2]'
|
||||
-F 'tagNames=["blog","screenshot"]'
|
||||
```
|
||||
|
||||
Optional form field `tagIds`: JSON array string or repeated fields. Tags do **not** change storage paths under `images/`.
|
||||
Optional form field `tagNames`: JSON array or comma-separated names. Tags apply to the user bound to the token (**global token cannot tag**). Tags do **not** change storage paths under `images/`.
|
||||
|
||||
### 2. List images
|
||||
|
||||
|
||||
@@ -4,6 +4,16 @@ Version history and notable changes. The full log is also in the repo root [CHAN
|
||||
|
||||
---
|
||||
|
||||
## [1.4.2] — 2026-09-23
|
||||
|
||||
### Fixed
|
||||
|
||||
- Gallery batch tagging and upload token auth (incl. legacy `API_UPLOAD_TOKEN`)
|
||||
|
||||
### Improved
|
||||
|
||||
- Single API token per account; upload `tagNames` only; tag management sort/mobile layout; API doc table layout
|
||||
|
||||
## [1.4.1] — 2026-09-16
|
||||
|
||||
### Added
|
||||
|
||||
@@ -12,10 +12,10 @@ PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API*
|
||||
Auth-Token: YOUR_TOKEN
|
||||
```
|
||||
|
||||
| Token 类型 | 获取方式 | 说明 |
|
||||
| ---------- | -------- | ---- |
|
||||
| **全局 Token** | 管理员 **API** 页生成;或 `API_UPLOAD_TOKEN` 环境变量 | 环境变量优先且锁定后台重新生成 |
|
||||
| **个人 Token** | 各用户 **API** 页 | 仅用于该用户脚本,上传归属本人 |
|
||||
| Token | 获取方式 | 说明 |
|
||||
| ----- | -------- | ---- |
|
||||
| **API Token** | 登录后 **API** 页(每账号一个,自动生成) | 请求头 `Auth-Token`;上传与 tagNames 归属该账号 |
|
||||
| **遗留全站 Token** | 环境变量 `API_UPLOAD_TOKEN` 或旧版后台配置 | 仍可用;上传归属**首个管理员**账号。Twikoo 表单 `token` 亦支持各账号 API Token |
|
||||
|
||||
表单上传仍可使用字段 `token`(Twikoo 协议)。
|
||||
|
||||
@@ -31,10 +31,10 @@ Auth-Token: YOUR_TOKEN
|
||||
curl -X POST "https://admin.example.com/api/images/upload" \
|
||||
-H "Auth-Token: YOUR_TOKEN" \
|
||||
-F "image=@./demo.png" \
|
||||
-F 'tagIds=[1,2]'
|
||||
-F 'tagNames=["博客","截图"]'
|
||||
```
|
||||
|
||||
可选表单字段 `tagIds`:JSON 数组字符串(如 `[1,2]`)或重复字段,上传成功后自动打标。存储路径仍为 `images/年/月/id.webp`,**不会**因标签创建子目录。
|
||||
可选表单字段 `tagNames`:JSON 数组或逗号分隔名称;上传成功后自动打标。存储路径仍为 `images/年/月/id.webp`,**不会**因标签创建子目录。
|
||||
|
||||
### 2. 获取图片列表
|
||||
|
||||
|
||||
@@ -4,6 +4,16 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
|
||||
|
||||
---
|
||||
|
||||
## [1.4.2] — 2026-09-23
|
||||
|
||||
### 修复
|
||||
|
||||
- 图库批量打标与上传 Token 鉴权(含 `API_UPLOAD_TOKEN` 兼容)
|
||||
|
||||
### 改进
|
||||
|
||||
- API 页单 Token;上传 `tagNames`;标签管理排序与移动端布局;API 文档表格式
|
||||
|
||||
## [1.4.1] — 2026-09-16
|
||||
|
||||
### 新增
|
||||
|
||||
@@ -13,8 +13,7 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
|
||||
| 系统设置(`/settings`) | ✓ | — |
|
||||
| 开放注册开关 | ✓ | — |
|
||||
| 登录人机验证方式(滑块 / Turnstile / Cap) | ✓ | — |
|
||||
| 全局 API Token 管理 | ✓ | — |
|
||||
| 个人 API Token | ✓ | ✓ |
|
||||
| API Token(每账号一个) | ✓ | ✓ |
|
||||
| 图库统计概览(含注册用户数) | ✓ | 部分 |
|
||||
| 标签管理(设置 → 标签管理) | ✓ | — |
|
||||
| 操作日志(设置 → 操作日志) | ✓ | — |
|
||||
@@ -26,9 +25,8 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
|
||||
| 场景 | 鉴权方式 | 图片归属 / 可见范围 |
|
||||
| ---- | -------- | ------------------- |
|
||||
| 网页上传 | Session Cookie | 当前登录用户 |
|
||||
| API 上传 + **个人 Token** | `Auth-Token` 头 | Token 所属用户 |
|
||||
| API 上传 + **全局 Token** | `Auth-Token` 头 | 管理员(`userId` 为空) |
|
||||
| Twikoo `POST /api/index.php` | 表单 `token` | 与全局 Token 相同 |
|
||||
| API 上传 | `Auth-Token` 或表单 `token` | Token 对应账号(遗留 `API_UPLOAD_TOKEN` 归属首个管理员) |
|
||||
| Twikoo `POST /api/index.php` | 表单 `token` | 同上 |
|
||||
| 图库列表 / 搜索 / 删除 | Session 或 Token | 普通用户仅自己;管理员全部 |
|
||||
| 图片直链 `GET /images/...` | 无(Referer 防盗链) | 知道 URL 即可访问 |
|
||||
|
||||
@@ -59,14 +57,11 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
|
||||
- **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好
|
||||
- **自动删除**:管理员可设全局策略;用户可设个人策略。启用后仅影响 **之后新上传** 的图片
|
||||
|
||||
## API Token 说明
|
||||
## API Token
|
||||
|
||||
| 类型 | 谁管理 | 上传归属 | 典型用途 |
|
||||
| ---- | ------ | -------- | -------- |
|
||||
| **全局 Token** | 管理员(API 页) | 管理员账号 | Twikoo、站点级脚本 |
|
||||
| **个人 Token** | 各用户(API 页) | 该用户 | 个人博客、私有脚本 |
|
||||
|
||||
若设置了环境变量 `API_UPLOAD_TOKEN`,则全局 Token 被锁定,见 [环境变量](./configuration.md)。
|
||||
- **每个账号一个 Token**(含管理员),在 **API** 页查看或重新生成;首次打开会自动创建
|
||||
- 上传、`tagNames` 打标、图库接口均归属 **该 Token 所属账号**
|
||||
- 环境变量 **`API_UPLOAD_TOKEN`**(旧部署)仍可作为鉴权密钥,上传归属 **首个管理员**,见 [环境变量](./configuration.md)
|
||||
|
||||
## 相关
|
||||
|
||||
|
||||
@@ -196,6 +196,7 @@
|
||||
"colName": "Tag name",
|
||||
"colImageCount": "Images",
|
||||
"colLastUsed": "Last used",
|
||||
"colCreatedAt": "Created",
|
||||
"neverUsed": "Never used",
|
||||
"colActions": "Actions",
|
||||
"mergeIntoAction": "Merge into…",
|
||||
@@ -824,13 +825,13 @@
|
||||
"pagePlaceholder": "Page"
|
||||
},
|
||||
"api": {
|
||||
"tokenTitle": "API Token",
|
||||
"tokenTitle": "API token",
|
||||
"envOverrideTitle": "Token overridden by environment",
|
||||
"envOverrideDesc": "Restart after changing API_UPLOAD_TOKEN; cannot regenerate in UI.",
|
||||
"personalTitle": "Personal API token",
|
||||
"personalDesc": "For your scripts only; uploads belong to your account.",
|
||||
"notConfiguredTitle": "No token configured",
|
||||
"notConfiguredDesc": "Click Regenerate to create a token for Auth-Token on all endpoints below.",
|
||||
"notConfiguredDesc": "A token is created automatically on first visit, or click Regenerate.",
|
||||
"regenerate": "Regenerate",
|
||||
"tokenSourceEnv": "Source: API_UPLOAD_TOKEN environment variable",
|
||||
"tokenSourceDb": "Source: generated in app (can regenerate)",
|
||||
@@ -879,8 +880,7 @@
|
||||
"file": "Compatibility field, single file",
|
||||
"files": "Compatibility field, multiple files",
|
||||
"token": "Twikoo protocol form token",
|
||||
"tagIds": "Optional JSON array or repeated fields; tag images by ID after upload",
|
||||
"tagNames": "Optional JSON array or comma-separated names; creates missing tags, reuses existing"
|
||||
"tagNames": "Optional JSON array or comma-separated names; creates or reuses tags"
|
||||
},
|
||||
"list": {
|
||||
"limit": "Page size, default 20, max 100",
|
||||
|
||||
@@ -196,6 +196,7 @@
|
||||
"colName": "标签名称",
|
||||
"colImageCount": "图片数",
|
||||
"colLastUsed": "最近使用",
|
||||
"colCreatedAt": "创建时间",
|
||||
"neverUsed": "从未使用",
|
||||
"colActions": "操作",
|
||||
"mergeIntoAction": "合并到…",
|
||||
@@ -830,7 +831,7 @@
|
||||
"personalTitle": "个人 API Token",
|
||||
"personalDesc": "此 Token 仅用于您自己的脚本上传,上传的图片归属您的账号。",
|
||||
"notConfiguredTitle": "尚未配置 Token",
|
||||
"notConfiguredDesc": "点击「重新生成」创建 Token,用于下方所有接口的 Auth-Token 鉴权。",
|
||||
"notConfiguredDesc": "首次打开会自动创建 Token,或点击「重新生成」。",
|
||||
"regenerate": "重新生成",
|
||||
"tokenSourceEnv": "来源:环境变量 API_UPLOAD_TOKEN",
|
||||
"tokenSourceDb": "来源:后台生成(可重新生成)",
|
||||
@@ -879,8 +880,7 @@
|
||||
"file": "兼容字段,单图上传",
|
||||
"files": "兼容字段,多图上传",
|
||||
"token": "Twikoo 协议兼容,表单 token",
|
||||
"tagIds": "可选,JSON 数组或重复字段,上传后按 ID 打标",
|
||||
"tagNames": "可选,JSON 数组或逗号分隔;名称不存在则自动创建,存在则复用"
|
||||
"tagNames": "可选,JSON 数组或逗号分隔;名称不存在则创建,存在则复用"
|
||||
},
|
||||
"list": {
|
||||
"limit": "每页条数,默认 20,最大 100",
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "pichost",
|
||||
"version": "1.4.1",
|
||||
"version": "1.4.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "pichost",
|
||||
"version": "1.4.1",
|
||||
"version": "1.4.2",
|
||||
"hasInstallScript": true,
|
||||
"license": "GPL-3.0-only",
|
||||
"dependencies": {
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pichost",
|
||||
"version": "1.4.1",
|
||||
"version": "1.4.2",
|
||||
"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",
|
||||
"repository": {
|
||||
|
||||
@@ -32,6 +32,9 @@ function validateKeys(keys: string[]): void {
|
||||
export default defineEventHandler(async (event) => {
|
||||
await requireApiOrAdminAuth(event)
|
||||
const user = await getCurrentUser(event)
|
||||
if (!user) {
|
||||
createApiError(event, 'UNAUTHORIZED', '批量打标需要登录', 401)
|
||||
}
|
||||
const body = await readBody<BatchTagsBody>(event)
|
||||
|
||||
const keys = Array.isArray(body?.keys)
|
||||
@@ -70,10 +73,10 @@ export default defineEventHandler(async (event) => {
|
||||
try {
|
||||
for (const key of keys) {
|
||||
if (action === 'add') {
|
||||
addTagsToImage(key, tagIds, user!.id, user!.role === 'admin')
|
||||
addTagsToImage(key, tagIds, user.id, user.role === 'admin')
|
||||
} else {
|
||||
for (const tagId of tagIds) {
|
||||
removeTagFromImage(key, tagId, user!.id, user!.role === 'admin')
|
||||
removeTagFromImage(key, tagId, user.id, user.role === 'admin')
|
||||
}
|
||||
}
|
||||
updated++
|
||||
@@ -88,7 +91,7 @@ export default defineEventHandler(async (event) => {
|
||||
originalName: action === 'add'
|
||||
? `批量打标(${keys.length} 张)`
|
||||
: `批量移除标签(${keys.length} 张)`,
|
||||
userId: user!.id
|
||||
userId: user.id
|
||||
})
|
||||
|
||||
return { success: true, updated }
|
||||
|
||||
@@ -14,7 +14,6 @@ import { createApiError } from '../../utils/api-error'
|
||||
import { checkUploadRateLimit } from '../../utils/rate-limit'
|
||||
import { readMultipartFormFieldValues } from '../../utils/multipart-form'
|
||||
import {
|
||||
parseTagIdsParam,
|
||||
parseTagNamesParam,
|
||||
resolveUploadTagIds
|
||||
} from '../../utils/tags'
|
||||
@@ -34,13 +33,11 @@ export default defineEventHandler(async (event) => {
|
||||
checkUploadRateLimit(event, formToken)
|
||||
|
||||
const source = verifyApiUploadToken(event) ? 'api' : 'web'
|
||||
const uploadUserId = await getUploadUserId(event)
|
||||
const uploadUserId = await getUploadUserId(event, formToken)
|
||||
|
||||
const tagIdsRaw = readMultipartFormFieldValues(formData, 'tagIds')
|
||||
const tagNamesRaw = readMultipartFormFieldValues(formData, 'tagNames')
|
||||
const uploadTagIdsInput = parseTagIdsParam(tagIdsRaw.length === 1 ? tagIdsRaw[0] : tagIdsRaw)
|
||||
const uploadTagNames = parseTagNamesParam(tagNamesRaw.length === 1 ? tagNamesRaw[0] : tagNamesRaw)
|
||||
const resolvedTags = resolveUploadTagIds(uploadUserId, uploadTagIdsInput, uploadTagNames)
|
||||
const resolvedTags = resolveUploadTagIds(uploadUserId, uploadTagNames)
|
||||
if ('message' in resolvedTags) {
|
||||
createApiError(event, 'INVALID_REQUEST', resolvedTags.message, 400)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { readMultipartFormData } from 'h3'
|
||||
import { verifyUploadTokenValue } from '../../utils/access'
|
||||
import { verifyUploadTokenValue, getUploadUserId } from '../../utils/access'
|
||||
import { checkUploadRateLimit } from '../../utils/rate-limit'
|
||||
import {
|
||||
detectMimeFromSignature,
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
mimeMatchesDeclared,
|
||||
processSingleImageUpload
|
||||
} from '../../utils/process-image-upload'
|
||||
import { getApiUploadToken } from '../../utils/env'
|
||||
|
||||
/** EasyImages 2.0 兼容上传(Twikoo IMAGE_CDN=easyimage) */
|
||||
export default defineEventHandler(async (event) => {
|
||||
@@ -29,15 +28,14 @@ export default defineEventHandler(async (event) => {
|
||||
: ''
|
||||
|
||||
if (!devBypass) {
|
||||
if (!getApiUploadToken(event)) {
|
||||
return easyImageError(500, '服务端未配置 API_UPLOAD_TOKEN')
|
||||
}
|
||||
if (!verifyUploadTokenValue(event, token)) {
|
||||
if (!token || !verifyUploadTokenValue(event, token)) {
|
||||
return easyImageError(401, 'token 错误或无效')
|
||||
}
|
||||
checkUploadRateLimit(event, token)
|
||||
}
|
||||
|
||||
const uploadUserId = await getUploadUserId(event, token)
|
||||
|
||||
const imagePart = formData.find(
|
||||
part => part.name === 'image' && part.data?.length
|
||||
)
|
||||
@@ -60,7 +58,8 @@ export default defineEventHandler(async (event) => {
|
||||
const result = await processSingleImageUpload(event, {
|
||||
bytes,
|
||||
filename: imagePart.filename,
|
||||
source: 'api'
|
||||
source: 'api',
|
||||
userId: uploadUserId
|
||||
})
|
||||
|
||||
if ('error' in result) {
|
||||
|
||||
+58
-11
@@ -1,5 +1,5 @@
|
||||
import type { H3Event } from 'h3'
|
||||
import { findUserByApiToken } from './db'
|
||||
import { findUserByApiToken, getPrimaryAdminUserId } from './db'
|
||||
import { getAdminSecret, getApiUploadToken } from './env'
|
||||
import { createApiError } from './api-error'
|
||||
import {
|
||||
@@ -85,10 +85,29 @@ export function verifyGlobalApiUploadToken(event: H3Event): boolean {
|
||||
return timingSafeEqual(token, expected)
|
||||
}
|
||||
|
||||
export function resolveUserIdFromApiToken(event: H3Event): number | null {
|
||||
const token = extractApiToken(event)
|
||||
if (!token) return null
|
||||
return findUserByApiToken(token)?.id ?? null
|
||||
function resolveUserIdFromTokenValue(token: string): number | null {
|
||||
const trimmed = token.trim()
|
||||
if (!trimmed) return null
|
||||
return findUserByApiToken(trimmed)?.id ?? null
|
||||
}
|
||||
|
||||
/** 从 Auth-Token 请求头或表单 token 解析个人 API Token 对应用户(非全站 Token) */
|
||||
export function resolveUserIdFromApiToken(
|
||||
event: H3Event,
|
||||
extraToken?: string
|
||||
): number | null {
|
||||
const headerToken = extractApiToken(event)
|
||||
if (headerToken) {
|
||||
const fromHeader = resolveUserIdFromTokenValue(headerToken)
|
||||
if (fromHeader !== null) return fromHeader
|
||||
}
|
||||
|
||||
if (extraToken) {
|
||||
const fromForm = resolveUserIdFromTokenValue(extraToken)
|
||||
if (fromForm !== null) return fromForm
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function verifyApiUploadToken(event: H3Event): boolean {
|
||||
@@ -222,20 +241,48 @@ export function resolveActivitySource(event: H3Event): 'api' | 'web' {
|
||||
return verifyApiUploadToken(event) ? 'api' : 'web'
|
||||
}
|
||||
|
||||
export async function getUploadUserId(event: H3Event): Promise<number | null> {
|
||||
function resolveUploadOwnerFromGlobalToken(
|
||||
event: H3Event,
|
||||
formToken?: string
|
||||
): number | null {
|
||||
const expected = getApiUploadToken(event)
|
||||
if (!expected) return null
|
||||
|
||||
const headerToken = extractApiToken(event)
|
||||
if (headerToken && timingSafeEqual(headerToken, expected)) {
|
||||
return getPrimaryAdminUserId()
|
||||
}
|
||||
|
||||
const trimmedForm = formToken?.trim()
|
||||
if (trimmedForm && timingSafeEqual(trimmedForm, expected)) {
|
||||
return getPrimaryAdminUserId()
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export async function getUploadUserId(
|
||||
event: H3Event,
|
||||
formToken?: string
|
||||
): Promise<number | null> {
|
||||
if (devBypass(event)) {
|
||||
return null
|
||||
}
|
||||
|
||||
const userIdFromToken = resolveUserIdFromApiToken(event)
|
||||
const userIdFromToken = resolveUserIdFromApiToken(event, formToken)
|
||||
if (userIdFromToken !== null) {
|
||||
return userIdFromToken
|
||||
}
|
||||
|
||||
if (verifyGlobalApiUploadToken(event)) {
|
||||
return null
|
||||
const user = await getCurrentUser(event)
|
||||
if (user) {
|
||||
return user.id
|
||||
}
|
||||
|
||||
const user = await getCurrentUser(event)
|
||||
return user?.id ?? null
|
||||
const globalOwnerId = resolveUploadOwnerFromGlobalToken(event, formToken)
|
||||
if (globalOwnerId !== null) {
|
||||
return globalOwnerId
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -414,6 +414,14 @@ export function listAdminUserIds(): Set<number> {
|
||||
return new Set(rows.map(row => row.id))
|
||||
}
|
||||
|
||||
/** 首个管理员(按 id),用于遗留全站 Token 上传归属 */
|
||||
export function getPrimaryAdminUserId(): number | null {
|
||||
const row = getDb().prepare(`
|
||||
SELECT id FROM users WHERE role = 'admin' ORDER BY id ASC LIMIT 1
|
||||
`).get() as { id: number } | undefined
|
||||
return row?.id ?? null
|
||||
}
|
||||
|
||||
export function setUserAutoDeleteDays(userId: number, days: number): void {
|
||||
setUserAutoDeletePolicy(userId, days)
|
||||
}
|
||||
|
||||
@@ -67,14 +67,11 @@ describe('parseTagNamesParam', () => {
|
||||
|
||||
describe('resolveUploadTagIds', () => {
|
||||
it('returns empty when no tags requested', () => {
|
||||
expect(resolveUploadTagIds(1, [], [])).toEqual({ tagIds: [] })
|
||||
expect(resolveUploadTagIds(1, [])).toEqual({ tagIds: [] })
|
||||
})
|
||||
|
||||
it('requires user when tags are requested', () => {
|
||||
expect(resolveUploadTagIds(null, [1], [])).toMatchObject({
|
||||
message: expect.stringContaining('API Token')
|
||||
})
|
||||
expect(resolveUploadTagIds(null, [], ['博客'])).toMatchObject({
|
||||
it('requires user when tag names are requested', () => {
|
||||
expect(resolveUploadTagIds(null, ['博客'])).toMatchObject({
|
||||
message: expect.stringContaining('API Token')
|
||||
})
|
||||
})
|
||||
|
||||
+104
-29
@@ -1,5 +1,6 @@
|
||||
import { getDb } from './db'
|
||||
import { getImageIndexRow } from './image-index'
|
||||
import { toCanonicalImageKey } from './image-key'
|
||||
|
||||
export const TAG_COLOR_PRESETS = [
|
||||
'#22c55e',
|
||||
@@ -310,17 +311,65 @@ function assertTagsOwnedByUser(userId: number, tagIds: number[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
function resolveImageOwnerUserId(key: string): number | null {
|
||||
const row = getImageIndexRow(key)
|
||||
return row?.user_id ?? null
|
||||
function resolveIndexedImageKey(key: string): string | null {
|
||||
if (getImageIndexRow(key)) return key
|
||||
const canonical = toCanonicalImageKey(key)
|
||||
if (canonical && getImageIndexRow(canonical)) return canonical
|
||||
return null
|
||||
}
|
||||
|
||||
/** 打标时标签归属的用户:无上传者的索引图用操作者自己的标签 */
|
||||
function resolveTagOwnerUserId(
|
||||
imageOwnerUserId: number | null,
|
||||
actorUserId: number
|
||||
): number {
|
||||
return imageOwnerUserId ?? actorUserId
|
||||
}
|
||||
|
||||
/**
|
||||
* 管理员给他人图片打标时,将操作者选中的 tagId 按名称映射到图片所有者的标签。
|
||||
*/
|
||||
export function resolveTagIdsForImageTagging(
|
||||
actorUserId: number,
|
||||
tagIds: number[],
|
||||
imageOwnerUserId: number | null,
|
||||
isAdmin: boolean
|
||||
): number[] {
|
||||
const tagOwnerUserId = resolveTagOwnerUserId(imageOwnerUserId, actorUserId)
|
||||
const unique = [...new Set(tagIds)]
|
||||
if (!unique.length) return []
|
||||
|
||||
if (tagOwnerUserId === actorUserId || !isAdmin) {
|
||||
assertTagsOwnedByUser(tagOwnerUserId, unique)
|
||||
return unique
|
||||
}
|
||||
|
||||
const resolved: number[] = []
|
||||
for (const tagId of unique) {
|
||||
const row = getTagById(tagId)
|
||||
if (!row) {
|
||||
throw new Error('TAG_NOT_FOUND')
|
||||
}
|
||||
if (row.user_id === tagOwnerUserId) {
|
||||
resolved.push(tagId)
|
||||
continue
|
||||
}
|
||||
if (row.user_id === actorUserId) {
|
||||
resolved.push(findOrCreateTagByName(tagOwnerUserId, row.name).id)
|
||||
continue
|
||||
}
|
||||
throw new Error('TAG_NOT_FOUND')
|
||||
}
|
||||
return [...new Set(resolved)]
|
||||
}
|
||||
|
||||
export function assertCanTagImage(key: string, actorUserId: number, isAdmin: boolean): void {
|
||||
const ownerId = resolveImageOwnerUserId(key)
|
||||
if (ownerId == null) {
|
||||
const indexedKey = resolveIndexedImageKey(key)
|
||||
if (!indexedKey) {
|
||||
throw new Error('IMAGE_NOT_FOUND')
|
||||
}
|
||||
if (!isAdmin && ownerId !== actorUserId) {
|
||||
const ownerId = getImageIndexRow(indexedKey)!.user_id
|
||||
if (!isAdmin && (ownerId === null || ownerId !== actorUserId)) {
|
||||
throw new Error('FORBIDDEN')
|
||||
}
|
||||
}
|
||||
@@ -332,19 +381,27 @@ export function addTagsToImage(
|
||||
isAdmin: boolean
|
||||
): TagItem[] {
|
||||
ensureTagSchema()
|
||||
assertCanTagImage(key, actorUserId, isAdmin)
|
||||
const ownerId = resolveImageOwnerUserId(key)!
|
||||
const uniqueTagIds = [...new Set(tagIds)]
|
||||
assertTagsOwnedByUser(ownerId, uniqueTagIds)
|
||||
const indexedKey = resolveIndexedImageKey(key)
|
||||
if (!indexedKey) {
|
||||
throw new Error('IMAGE_NOT_FOUND')
|
||||
}
|
||||
assertCanTagImage(indexedKey, actorUserId, isAdmin)
|
||||
const imageOwnerUserId = getImageIndexRow(indexedKey)!.user_id
|
||||
const uniqueTagIds = resolveTagIdsForImageTagging(
|
||||
actorUserId,
|
||||
tagIds,
|
||||
imageOwnerUserId,
|
||||
isAdmin
|
||||
)
|
||||
|
||||
const insert = getDb().prepare(`
|
||||
INSERT OR IGNORE INTO image_tags (image_key, tag_id) VALUES (?, ?)
|
||||
`)
|
||||
for (const tagId of uniqueTagIds) {
|
||||
insert.run(key, tagId)
|
||||
insert.run(indexedKey, tagId)
|
||||
}
|
||||
|
||||
return getTagsForImageKeys([key]).get(key) ?? []
|
||||
return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
|
||||
}
|
||||
|
||||
export function removeTagFromImage(
|
||||
@@ -354,15 +411,27 @@ export function removeTagFromImage(
|
||||
isAdmin: boolean
|
||||
): TagItem[] {
|
||||
ensureTagSchema()
|
||||
assertCanTagImage(key, actorUserId, isAdmin)
|
||||
const ownerId = resolveImageOwnerUserId(key)!
|
||||
assertTagsOwnedByUser(ownerId, [tagId])
|
||||
const indexedKey = resolveIndexedImageKey(key)
|
||||
if (!indexedKey) {
|
||||
throw new Error('IMAGE_NOT_FOUND')
|
||||
}
|
||||
assertCanTagImage(indexedKey, actorUserId, isAdmin)
|
||||
const imageOwnerUserId = getImageIndexRow(indexedKey)!.user_id
|
||||
const [resolvedTagId] = resolveTagIdsForImageTagging(
|
||||
actorUserId,
|
||||
[tagId],
|
||||
imageOwnerUserId,
|
||||
isAdmin
|
||||
)
|
||||
if (resolvedTagId == null) {
|
||||
return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
|
||||
}
|
||||
|
||||
getDb().prepare(`
|
||||
DELETE FROM image_tags WHERE image_key = ? AND tag_id = ?
|
||||
`).run(key, tagId)
|
||||
`).run(indexedKey, resolvedTagId)
|
||||
|
||||
return getTagsForImageKeys([key]).get(key) ?? []
|
||||
return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
|
||||
}
|
||||
|
||||
export function setImageTags(
|
||||
@@ -372,20 +441,28 @@ export function setImageTags(
|
||||
isAdmin: boolean
|
||||
): TagItem[] {
|
||||
ensureTagSchema()
|
||||
assertCanTagImage(key, actorUserId, isAdmin)
|
||||
const ownerId = resolveImageOwnerUserId(key)!
|
||||
const uniqueTagIds = [...new Set(tagIds)]
|
||||
assertTagsOwnedByUser(ownerId, uniqueTagIds)
|
||||
const indexedKey = resolveIndexedImageKey(key)
|
||||
if (!indexedKey) {
|
||||
throw new Error('IMAGE_NOT_FOUND')
|
||||
}
|
||||
assertCanTagImage(indexedKey, actorUserId, isAdmin)
|
||||
const imageOwnerUserId = getImageIndexRow(indexedKey)!.user_id
|
||||
const uniqueTagIds = resolveTagIdsForImageTagging(
|
||||
actorUserId,
|
||||
tagIds,
|
||||
imageOwnerUserId,
|
||||
isAdmin
|
||||
)
|
||||
|
||||
const db = getDb()
|
||||
db.exec('BEGIN')
|
||||
try {
|
||||
db.prepare('DELETE FROM image_tags WHERE image_key = ?').run(key)
|
||||
db.prepare('DELETE FROM image_tags WHERE image_key = ?').run(indexedKey)
|
||||
const insert = db.prepare(`
|
||||
INSERT INTO image_tags (image_key, tag_id) VALUES (?, ?)
|
||||
`)
|
||||
for (const tagId of uniqueTagIds) {
|
||||
insert.run(key, tagId)
|
||||
insert.run(indexedKey, tagId)
|
||||
}
|
||||
db.exec('COMMIT')
|
||||
} catch (error) {
|
||||
@@ -393,7 +470,7 @@ export function setImageTags(
|
||||
throw error
|
||||
}
|
||||
|
||||
return getTagsForImageKeys([key]).get(key) ?? []
|
||||
return getTagsForImageKeys([indexedKey]).get(indexedKey) ?? []
|
||||
}
|
||||
|
||||
export function attachTagsAfterUpload(
|
||||
@@ -529,22 +606,20 @@ export function resolveTagIdsFromNames(userId: number, names: readonly string[])
|
||||
|
||||
export function resolveUploadTagIds(
|
||||
userId: number | null,
|
||||
tagIds: number[],
|
||||
tagNames: string[]
|
||||
): { tagIds: number[] } | { message: string } {
|
||||
if (!tagIds.length && !tagNames.length) {
|
||||
if (!tagNames.length) {
|
||||
return { tagIds: [] }
|
||||
}
|
||||
|
||||
if (userId == null) {
|
||||
return {
|
||||
message: '打标签需要登录或使用绑定用户的 API Token'
|
||||
message: '使用 tagNames 时请登录或通过 Auth-Token / 表单 token 提供有效 API Token'
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const fromNames = tagNames.length ? resolveTagIdsFromNames(userId, tagNames) : []
|
||||
return { tagIds: [...new Set([...tagIds, ...fromNames])] }
|
||||
return { tagIds: resolveTagIdsFromNames(userId, tagNames) }
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
switch (error.message) {
|
||||
|
||||
Reference in new issue
Block a user