5 Commits
Author SHA1 Message Date
O96u 05cc3895f1 release: v1.4.4
docs / build (push) Canceled after 0s
docs / deploy (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
GitHub Release / release (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
Update Cap login verification so hashwx challenges solve, while older SHA-256 keys still work.
2026-10-10 13:26:42 +08:00
O96u 424bfd9090 fix: give each test worker its own SQLite database
Parallel Vitest workers were opening data/pichost.db together, so host-isolation failed with database is locked.
2026-10-09 15:52:03 +08:00
O96u 10baf9d489 fix: run Telegram storage tests on an isolated database
CI workers were sharing one SQLite file, so schema setup locked and storage_object_refs was missing.
2026-10-09 15:47:09 +08:00
O96u cc19dc6435 release: v1.4.3
GitHub Release / release (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
Add a Telegram channel or group storage backend, with proxied image URLs and an optional API proxy.
2026-10-09 15:39:24 +08:00
O96u 4ed4692f5e release: v1.4.2
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
Fix batch tagging and upload token auth; single API token and tagNames-only upload; tag management sort and responsive layout.
2026-09-23 15:38:46 +08:00
54 changed files with 2286 additions and 348 deletions

No files matched your search

+34
View File
@@ -4,6 +4,40 @@
## [Unreleased]
## [1.4.4] - 2026-10-10
### 修复
- Cap 登录验证支持新的 hashwx 挑战,旧的 SHA-256 site key 仍可使用
- 求解用的 wasm 改由本站提供,不再依赖 jsDelivr
## [1.4.3] - 2026-10-09
### 新增
- **Telegram 存储后端**:用 Bot 把图片存入频道或群组(含私有);直链仍由 PicHost 代理,不暴露 Bot Token
- 可选 HTTP/HTTPS API 代理,供服务器访问 Telegram
- 群组升级为超级群组时自动改用新的 Chat ID
### 说明
- 单文件约 20MB,同一聊天约 20 条/分钟
- 图库删除会尝试删除对应 Telegram 消息;备份包不含 Bot Token
## [1.4.2] - 2026-09-23
### 修复
- 图库批量打标:管理员/跨归属场景下标签解析与失败提示
- 上传鉴权:`Auth-Token` 与表单 `token` 优先于会话;兼容全局 `API_UPLOAD_TOKEN`(上传归属首位管理员)
### 改进
- **API 页**:每账号单一 API Token,界面与文档统一
- **上传 API**:仅支持 `tagNames`(按名创建或复用标签);Twikoo 兼容路由同步
- **标签管理**:按图片数/最近使用排序;桌面列布局;窄屏卡片列表
- **API 文档**:参数表列宽,避免 form-data 列异常换行
## [1.4.1] - 2026-09-16
### 新增
+2 -2
View File
@@ -55,7 +55,7 @@
- **Drag, click, or Ctrl+V paste** — server-side WebP, Referer hotlink protection
- **Multi-user** — login with slider, Turnstile, or Cap verification; optional registration; users see only their images
- **Multi-backend storage** — local disk + S3-compatible (R2 / COS / OSS / AWS); hybrid `proxy` / `public` URLs
- **Multi-backend storage** — local disk + S3-compatible (R2 / COS / OSS / AWS) + Telegram channel/group; hybrid `proxy` / `public` URLs
- **Gallery** — browse, search, filter by storage/source/tags, grid/list views, batch delete and batch tagging; stats overview and source breakdown; image detail modal with link formats
- **Tags** — per-user colored tags; tag on upload (single or batch); manage in Settings (create, recolor, merge, delete); API supports `tagIds` and batch tagging
- **Backup & migration** — full-site export/restore (`.phost.tar.gz`), cross-backend sync; restore from backup on uninitialized `/setup`
@@ -70,7 +70,7 @@
| Backend | [Nitro](https://nitro.build) (`node-server`) · REST API |
| Data | SQLite · local `data/pichost.db` |
| Images | [sharp](https://sharp.pixelplumbing.com) (server-side WebP) |
| Storage | Local disk · S3-compatible ([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS, etc.) |
| Storage | Local disk · S3-compatible ([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS, etc.) · Telegram channel/group |
| i18n | [@nuxtjs/i18n](https://i18n.nuxtjs.org) (zh-CN / English) |
| Quality & docs | [Vitest](https://vitest.dev) · [VitePress](https://vitepress.dev) docs site |
| Deploy | Docker · Node.js 22 |
+2 -2
View File
@@ -55,7 +55,7 @@
- **拖拽 / 点击 / Ctrl+V 粘贴**上传;服务端 WebP 压缩、Referer 防盗链
- **多用户**:账号密码登录(滑块 / Turnstile / Cap 人机验证)、可选开放注册;普通用户仅见自己的图片
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public`
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS)+ Telegram 频道/群组;混合直链 `proxy` / `public`
- **图库**:浏览、搜索、按存储/来源/标签筛选、网格/列表切换、批量删除与批量打标;统计概览与来源分布;点击图片查看详情与多格式链接
- **标签**:每用户独立标签、彩色标记;上传后单张/批量打标;设置页管理(新建、改色、合并、删除);API 支持 `tagIds` 与批量打标
- **备份与迁移**:整站导出/恢复(`.phost.tar.gz`)、跨后端同步;setup 未初始化时可从备份恢复
@@ -70,7 +70,7 @@
| 后端 | [Nitro](https://nitro.build)(`node-server`)· REST API |
| 数据 | SQLite · 本地 `data/pichost.db` |
| 图片处理 | [sharp](https://sharp.pixelplumbing.com)(服务端 WebP 压缩) |
| 存储 | 本地磁盘 · S3 兼容([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS 等) |
| 存储 | 本地磁盘 · S3 兼容([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS 等)· Telegram 频道/群组 |
| 国际化 | [@nuxtjs/i18n](https://i18n.nuxtjs.org)(简体中文 / English) |
| 质量与文档 | [Vitest](https://vitest.dev) · [VitePress](https://vitepress.dev) 文档站 |
| 部署 | Docker · Node.js 22 |
+14 -2
View File
@@ -1,6 +1,4 @@
<script setup lang="ts">
import 'cap-widget'
const props = defineProps<{
apiEndpoint: string
}>()
@@ -13,6 +11,19 @@ const emit = defineEmits<{
const { t } = useI18n()
const widgetRef = ref<HTMLElement | null>(null)
const ready = ref(false)
onMounted(async () => {
const capWindow = window as Window & {
CAP_CUSTOM_WASM_URL?: string
CAP_CUSTOM_HASHWX_URL?: string
}
// SHA-256 与 hashwx 的求解器都放在本站 /cap,避免组件去 jsDelivr 拉 wasm。
capWindow.CAP_CUSTOM_WASM_URL = '/cap/cap_wasm_bg.wasm'
capWindow.CAP_CUSTOM_HASHWX_URL = '/cap/hashwx.wasm'
await import('cap-widget')
ready.value = true
})
function onSolve(event: Event) {
const token = (event as CustomEvent<{ token: string }>).detail?.token
@@ -37,6 +48,7 @@ defineExpose({ reset })
<template>
<ClientOnly>
<cap-widget
v-if="ready"
ref="widgetRef"
:data-cap-api-endpoint="props.apiEndpoint"
:data-cap-i18n-initial-state="t('auth.capInitialState')"
+449 -130
View File
@@ -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 totalPages = computed(() => Math.max(1, Math.ceil(filteredTags.value.length / pageSize.value)))
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 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>
+16 -9
View File
@@ -38,19 +38,26 @@ const { t } = useI18n()
</h3>
</div>
<div class="overflow-x-auto">
<table class="w-full min-w-[32rem] text-left text-sm">
<table class="w-full min-w-[36rem] table-fixed text-left text-sm">
<colgroup>
<col class="w-[5.5rem]">
<col class="w-[3.5rem]">
<col class="w-[5.75rem]">
<col class="w-[3.25rem]">
<col>
</colgroup>
<thead>
<tr class="border-b border-default text-xs text-muted">
<th class="px-4 py-2.5 font-medium">
{{ t('api.paramName') }}
</th>
<th class="px-4 py-2.5 font-medium">
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
{{ t('api.paramType') }}
</th>
<th class="px-4 py-2.5 font-medium">
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
{{ t('api.paramLocation') }}
</th>
<th class="px-4 py-2.5 font-medium">
<th class="whitespace-nowrap px-4 py-2.5 font-medium">
{{ t('api.paramRequired') }}
</th>
<th class="px-4 py-2.5 font-medium">
@@ -64,20 +71,20 @@ const { t } = useI18n()
:key="param.name"
class="border-b border-default last:border-b-0"
>
<td class="px-4 py-2.5 font-mono text-xs">
<td class="whitespace-nowrap px-4 py-2.5 font-mono text-xs">
{{ param.name }}
<span
v-if="param.required"
class="text-error"
>*</span>
</td>
<td class="px-4 py-2.5 text-muted">
<td class="whitespace-nowrap px-4 py-2.5 text-muted">
{{ param.type }}
</td>
<td class="px-4 py-2.5 text-muted">
<td class="whitespace-nowrap px-4 py-2.5 text-muted">
{{ param.location }}
</td>
<td class="px-4 py-2.5">
<td class="whitespace-nowrap px-4 py-2.5">
<UBadge
:color="param.required ? 'primary' : 'neutral'"
variant="subtle"
@@ -86,7 +93,7 @@ const { t } = useI18n()
{{ param.required ? t('api.required') : t('api.optional') }}
</UBadge>
</td>
<td class="px-4 py-2.5 text-muted">
<td class="px-4 py-2.5 leading-relaxed text-muted break-words">
{{ t(param.descriptionKey) }}
</td>
</tr>
-9
View File
@@ -75,15 +75,6 @@ async function copyToken() {
:description="t('api.envOverrideDesc')"
/>
<UAlert
v-else-if="!isAdmin"
color="info"
variant="subtle"
icon="i-lucide-info"
:title="t('api.personalTitle')"
:description="t('api.personalDesc')"
/>
<UAlert
v-else-if="!token && !loading"
color="info"
+11 -7
View File
@@ -21,13 +21,17 @@ const emit = defineEmits<{
const { t } = useI18n()
const typeIcon = computed(() =>
props.backend.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
)
const typeIcon = computed(() => {
if (props.backend.type === 'local') return 'i-lucide-hard-drive'
if (props.backend.type === 'telegram') return 'i-lucide-send'
return 'i-lucide-cloud'
})
const typeLabel = computed(() =>
props.backend.type === 'local' ? t('storage.backendLocal') : t('storage.backendCloud')
)
const typeLabel = computed(() => {
if (props.backend.type === 'local') return t('storage.backendLocal')
if (props.backend.type === 'telegram') return t('storage.backendTelegram')
return t('storage.backendCloud')
})
const actionsDisabled = computed(() => props.envOverride || props.busy)
@@ -38,7 +42,7 @@ function canSetDefault() {
}
function canEdit() {
return props.backend.type === 's3'
return props.backend.type === 's3' || props.backend.type === 'telegram'
}
function canToggle() {
+107 -9
View File
@@ -2,9 +2,10 @@
import type { QuotaUnit } from '~/composables/useFileSize'
import type { StorageBackendItem } from '~/types/storage'
type StorageProvider = 'r2' | 'cos' | 'oss' | 'aws' | 'custom'
type StorageProvider = 'r2' | 'cos' | 'oss' | 'aws' | 'custom' | 'telegram'
export interface StorageFormPayload {
backendType: 's3' | 'telegram'
name: string
provider: StorageProvider
config: {
@@ -13,10 +14,13 @@ export interface StorageFormPayload {
bucket: string
prefix?: string
forcePathStyle: boolean
chatId?: string
apiProxyUrl?: string
}
secrets: {
accessKeyId: string
secretAccessKey: string
botToken: string
}
servingMode: 'proxy' | 'public'
publicUrl: string
@@ -47,11 +51,18 @@ const prefix = ref('')
const forcePathStyle = ref(false)
const accessKeyId = ref('')
const secretAccessKey = ref('')
const chatId = ref('')
const botToken = ref('')
const apiProxyUrl = ref('')
const servingMode = ref<'proxy' | 'public'>('proxy')
const publicUrl = ref('')
const quotaValue = ref('')
const quotaUnit = ref<QuotaUnit>('GB')
const isTelegram = computed(() =>
provider.value === 'telegram' || props.backend?.type === 'telegram'
)
const quotaUnitOptions = computed(() =>
QUOTA_UNITS.map(unit => ({ label: unit, value: unit }))
)
@@ -61,7 +72,8 @@ const providerOptions = computed(() => [
{ label: t('storage.providerCos'), value: 'cos' as const },
{ label: t('storage.providerOss'), value: 'oss' as const },
{ label: t('storage.providerAws'), value: 'aws' as const },
{ label: t('storage.providerCustom'), value: 'custom' as const }
{ label: t('storage.providerCustom'), value: 'custom' as const },
{ label: t('storage.providerTelegram'), value: 'telegram' as const }
])
const servingModeOptions = computed(() => [
@@ -79,6 +91,10 @@ function applyProviderTemplate(value: StorageProvider) {
if (props.createMode) {
name.value = providerLabel(value)
}
if (value === 'telegram') {
servingMode.value = 'proxy'
return
}
switch (value) {
case 'r2':
endpoint.value = 'https://{account_id}.r2.cloudflarestorage.com'
@@ -114,9 +130,7 @@ function detectProvider(config: StorageBackendItem['config']): StorageProvider {
return 'custom'
}
function loadBackend(backend: StorageBackendItem | null | undefined) {
if (!backend || backend.type !== 's3') {
if (props.createMode) {
function resetCreateDefaults() {
name.value = ''
provider.value = 'r2'
applyProviderTemplate('r2')
@@ -124,11 +138,36 @@ function loadBackend(backend: StorageBackendItem | null | undefined) {
prefix.value = ''
accessKeyId.value = ''
secretAccessKey.value = ''
chatId.value = ''
botToken.value = ''
apiProxyUrl.value = ''
servingMode.value = 'proxy'
publicUrl.value = ''
quotaValue.value = ''
quotaUnit.value = 'GB'
}
function loadBackend(backend: StorageBackendItem | null | undefined) {
if (!backend) {
if (props.createMode) resetCreateDefaults()
return
}
if (backend.type === 'telegram') {
name.value = backend.name
provider.value = 'telegram'
chatId.value = backend.config.chatId ?? ''
apiProxyUrl.value = backend.config.apiProxyUrl ?? ''
botToken.value = ''
const quota = bytesToQuotaInput(backend.quotaBytes)
quotaValue.value = quota.value
quotaUnit.value = quota.unit
servingMode.value = 'proxy'
return
}
if (backend.type !== 's3') {
if (props.createMode) resetCreateDefaults()
return
}
@@ -157,7 +196,9 @@ watch(provider, (value) => {
})
function handleSubmit() {
const backendType = isTelegram.value ? 'telegram' : 's3'
emit('submit', {
backendType,
name: name.value.trim() || providerLabel(provider.value),
provider: provider.value,
config: {
@@ -165,13 +206,16 @@ function handleSubmit() {
region: region.value.trim() || 'auto',
bucket: bucket.value.trim(),
prefix: prefix.value.trim() || undefined,
forcePathStyle: forcePathStyle.value
forcePathStyle: forcePathStyle.value,
chatId: chatId.value.trim() || undefined,
apiProxyUrl: apiProxyUrl.value.trim() || undefined
},
secrets: {
accessKeyId: accessKeyId.value.trim(),
secretAccessKey: secretAccessKey.value.trim()
secretAccessKey: secretAccessKey.value.trim(),
botToken: botToken.value.trim()
},
servingMode: servingMode.value,
servingMode: isTelegram.value ? 'proxy' : servingMode.value,
publicUrl: publicUrl.value.trim(),
quotaValue: String(quotaValue.value ?? '').trim(),
quotaUnit: quotaUnit.value
@@ -190,6 +234,7 @@ function handleSubmit() {
v-model="provider"
:items="providerOptions"
class="w-full"
:disabled="!createMode && backend?.type === 'telegram'"
/>
</div>
@@ -201,6 +246,58 @@ function handleSubmit() {
/>
</div>
<template v-if="isTelegram">
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.telegramChatId') }}
<span class="text-error">*</span>
</label>
<UInput
v-model="chatId"
:placeholder="t('storage.telegramChatIdPlaceholder')"
class="w-full font-mono text-sm"
required
/>
<p class="text-xs text-muted">
{{ t('storage.telegramChatIdHint') }}
</p>
</div>
<div class="space-y-2">
<label class="text-sm">
{{ t('storage.telegramBotToken') }}
<span
v-if="createMode"
class="text-error"
>*</span>
</label>
<UInput
v-model="botToken"
type="password"
:placeholder="backend?.secretsMasked.botToken || ''"
class="w-full font-mono text-sm"
:required="createMode"
/>
</div>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.telegramApiProxy') }}</label>
<UInput
v-model="apiProxyUrl"
:placeholder="t('storage.telegramApiProxyPlaceholder')"
class="w-full font-mono text-sm"
/>
<p class="text-xs text-muted">
{{ t('storage.telegramApiProxyHint') }}
</p>
</div>
<p class="text-xs text-muted">
{{ t('storage.telegramServingHint') }}
</p>
</template>
<template v-else>
<div class="space-y-2">
<label class="text-sm">{{ t('storage.endpoint') }}</label>
<UInput
@@ -300,6 +397,7 @@ function handleSubmit() {
class="w-full font-mono text-sm"
/>
</div>
</template>
<div class="space-y-2">
<label class="text-sm">
@@ -324,7 +422,7 @@ function handleSubmit() {
/>
</div>
<p class="text-xs text-muted">
{{ t('storage.quotaHint') }}
{{ isTelegram ? t('storage.telegramQuotaHint') : t('storage.quotaHint') }}
</p>
</div>
@@ -22,6 +22,13 @@ const items = computed(() => [
boxClass: 'border-blue-500/20 bg-blue-500/5',
title: t('storage.supportedS3Title'),
desc: t('storage.supportedS3Desc')
},
{
icon: 'i-lucide-send',
iconClass: 'text-sky-500',
boxClass: 'border-sky-500/20 bg-sky-500/5',
title: t('storage.backendTelegram'),
desc: t('storage.supportedTelegramDesc')
}
])
</script>
-7
View File
@@ -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',
+7 -1
View File
@@ -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
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
interface SettingsResponse {
interface UserTokenResponse {
apiUploadToken: string
tokenSource: 'env' | 'db' | 'none'
envTokenOverride: boolean
@@ -16,7 +16,7 @@ const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus,
const toast = useToast()
const { t } = useI18n()
const settings = ref<SettingsResponse | null>(null)
const tokenSettings = ref<UserTokenResponse | null>(null)
const loading = ref(false)
const regenerating = ref(false)
const confirmRegenerateOpen = ref(false)
@@ -25,19 +25,17 @@ const newToken = ref('')
const activeEndpointId = ref('upload')
const baseUrl = computed(() => {
const configured = settings.value?.env.siteBaseUrl
const configured = tokenSettings.value?.env.siteBaseUrl
if (configured) return configured
if (import.meta.client) {
return window.location.origin
}
return settings.value?.env.imageBaseUrl ?? ''
return tokenSettings.value?.env.imageBaseUrl ?? ''
})
const tokenDisplay = computed(() => settings.value?.apiUploadToken ?? '')
const tokenDisplay = computed(() => tokenSettings.value?.apiUploadToken ?? '')
const hasToken = computed(() => tokenDisplay.value.length > 0)
const canRegenerate = computed(() =>
!settings.value?.envTokenOverride && !loading.value
)
const canRegenerate = computed(() => !loading.value)
const authHeader = computed(() =>
hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN'
@@ -54,11 +52,10 @@ const activeEndpoint = computed(() =>
apiDocs.value.find(endpoint => endpoint.id === activeEndpointId.value) ?? apiDocs.value[0]
)
async function loadSettings() {
async function loadTokenSettings() {
loading.value = true
try {
const endpoint = isAdmin.value ? '/api/settings' : '/api/user/api-token'
settings.value = await $fetch<SettingsResponse>(endpoint, {
tokenSettings.value = await $fetch<UserTokenResponse>('/api/user/api-token', {
credentials: 'include'
})
} catch (error: unknown) {
@@ -66,6 +63,7 @@ async function loadSettings() {
if (isAuthenticated.value) {
toast.add({ title: t('api.loadFailed'), color: 'error' })
}
tokenSettings.value = null
} finally {
loading.value = false
}
@@ -80,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"
/>
+5 -2
View File
@@ -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'
})
}
}
+34 -3
View File
@@ -93,16 +93,42 @@ const { quotaToBytes } = useFileSize()
function buildPatchBody(payload: StorageFormPayload) {
const quotaBytes = quotaToBytes(payload.quotaValue, payload.quotaUnit)
if (payload.backendType === 'telegram') {
const body: Record<string, unknown> = {
type: 'telegram',
name: payload.name,
quotaBytes,
config: {
chatId: payload.config.chatId,
apiProxyUrl: payload.config.apiProxyUrl
}
}
if (payload.secrets.botToken) {
body.secrets = { botToken: payload.secrets.botToken }
}
return body
}
const body: Record<string, unknown> = {
type: 's3',
name: payload.name,
provider: payload.provider,
servingMode: payload.servingMode,
publicUrl: payload.publicUrl,
quotaBytes,
config: payload.config
config: {
endpoint: payload.config.endpoint,
region: payload.config.region,
bucket: payload.config.bucket,
prefix: payload.config.prefix,
forcePathStyle: payload.config.forcePathStyle
}
}
if (payload.secrets.accessKeyId || payload.secrets.secretAccessKey) {
body.secrets = payload.secrets
body.secrets = {
accessKeyId: payload.secrets.accessKeyId,
secretAccessKey: payload.secrets.secretAccessKey
}
}
return body
}
@@ -128,7 +154,12 @@ async function onFormSubmit(payload: StorageFormPayload) {
}
if (formMode.value === 'create') {
if (!payload.secrets.accessKeyId || !payload.secrets.secretAccessKey) {
if (payload.backendType === 'telegram') {
if (!payload.secrets.botToken || !payload.config.chatId) {
toast.add({ title: t('storage.telegramSecretsRequired'), color: 'warning' })
return
}
} else if (!payload.secrets.accessKeyId || !payload.secrets.secretAccessKey) {
toast.add({ title: t('storage.secretsRequired'), color: 'warning' })
return
}
+1 -1
View File
@@ -40,7 +40,7 @@ export interface ImageItem {
storage?: {
id: string
name: string
type: 'local' | 's3'
type: 'local' | 's3' | 'telegram'
}
/** 上传来源:网页或 API(来自活动日志) */
uploadSource?: 'web' | 'api'
+4 -1
View File
@@ -11,17 +11,20 @@ export interface StorageCapacity {
export interface StorageBackendItem {
id: string
name: string
type: 'local' | 's3'
type: 'local' | 's3' | 'telegram'
config: {
endpoint?: string
region?: string
bucket?: string
prefix?: string
forcePathStyle?: boolean
chatId?: string
apiProxyUrl?: string
}
secretsMasked: {
accessKeyId?: string
secretAccessKey?: string
botToken?: string
}
servingMode: ServingMode
publicUrl: string
+6 -6
View File
@@ -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
+22
View File
@@ -4,6 +4,28 @@ Version history and notable changes. The full log is also in the repo root [CHAN
---
## [1.4.4] — 2026-10-10
### Fixed
- Cap login verification supports hashwx challenges and still accepts older SHA-256 site keys
## [1.4.3] — 2026-10-09
### Added
- **Telegram storage backend**: store images in a channel or group; public URLs stay on PicHost; optional API proxy
## [1.4.2] — 2026-09-23
### Fixed
- Gallery batch tagging and upload token auth (incl. legacy `API_UPLOAD_TOKEN`)
### Improved
- Single API token per account; upload `tagNames` only; tag management sort/mobile layout; API doc table layout
## [1.4.1] — 2026-09-16
### Added
+21 -4
View File
@@ -1,6 +1,6 @@
# Storage
PicHost supports **local disk** and **S3-compatible object storage** (Cloudflare R2, Tencent COS, Alibaba OSS, AWS S3, etc.). Admins manage backends at **Storage** (`/storage`); new uploads go to the **default** backend. The page shows a **storage overview** (total, used, remaining, usage rate, capacity chart) plus per-backend cards and supported backend types.
PicHost supports **local disk**, **S3-compatible object storage** (Cloudflare R2, Tencent COS, Alibaba OSS, AWS S3, etc.), and a **Telegram channel or group**. Admins manage backends at **Storage** (`/storage`); new uploads go to the **default** backend. The page shows a **storage overview** (total, used, remaining, usage rate, capacity chart) plus per-backend cards and supported backend types.
![Storage management](/screenshots/storage.png)
@@ -23,11 +23,11 @@ All **keys** start with `images/`. The upload API does **not** accept a `folder`
## Adding a backend
1. Sign in as admin → **Storage** → **Add backend**.
2. Choose **local disk** or **S3-compatible** (R2 / COS / OSS presets).
3. Enter connection details (bucket, endpoint, keys).
2. Choose **local disk**, **S3-compatible** (R2 / COS / OSS presets), or **Telegram channel**.
3. Enter connection details (bucket, endpoint, keys, or Bot Token / Chat ID).
4. **Set as default** so new uploads use it.
New object-storage backends get an auto-generated **storage ID** prefix: `local` for disk; `r2-*` for R2; `cos-*` for COS; `oss-*` for OSS; `s3-*` for AWS S3 and custom S3-compatible endpoints (immutable after creation; the image index references this ID).
New backends get an auto-generated **storage ID** prefix: `local` for disk; `r2-*` for R2; `cos-*` for COS; `oss-*` for OSS; `s3-*` for AWS S3 and custom S3-compatible endpoints; `tg-*` for Telegram (immutable after creation; the image index references this ID).
### Cloudflare R2
@@ -40,6 +40,23 @@ New object-storage backends get an auto-generated **storage ID** prefix: `local`
The **cloudflare** branch streamlines R2-only deploys; see branch notes on the [docs overview](./index.md).
### Telegram channel or group
A bot posts each image into a channel or group (private chats work). Visitors still load PicHost URLs; the app never redirects to a Telegram file URL.
1. Create a bot with [@BotFather](https://t.me/BotFather) and copy the token.
2. Make the bot an admin of the channel or group (post messages; also grant delete messages if gallery deletes should remove the Telegram post).
3. On the Storage page choose **Telegram channel**, then enter the Chat ID (supergroups and channels are usually `-100…`), the bot token, and a quota.
4. If the server cannot reach `api.telegram.org` directly, set an optional HTTP/HTTPS API proxy (for example `http://127.0.0.1:7890`).
Limits and behavior:
- Practical per-file cap is about **20MB** (the smaller of this and the site upload limit applies)
- About **20 messages per minute** per chat; faster batches fail with a retry hint
- Serving mode is always **proxy**
- Gallery delete tries to delete the Telegram message. If an upload reaches the chat but PicHost cannot store a file id, that message is removed when possible
- Full backups download files through the bot and are subject to the rate limit. Packages do not include the bot token; enter it again after restore. Restoring onto a default Telegram backend re-uploads images into the chat
### Environment variables (optional)
Some installs seed a default S3 backend via `STORAGE_BACKEND=s3`, `S3_ENDPOINT`, `S3_BUCKET`, `S3_ACCESS_KEY`, `S3_SECRET_KEY`, `S3_REGION`. **UI-configured backends live in SQLite** alongside env-based defaults.
+1 -1
View File
@@ -20,7 +20,7 @@ features:
- title: Drag, click, paste
details: Server-side WebP compression and Referer hotlink protection.
- title: Multi-backend storage
details: Local disk plus S3-compatible backends (R2 / COS / OSS / AWS); proxy or public URLs.
details: Local disk, S3-compatible backends (R2 / COS / OSS / AWS), and Telegram; proxy or public URLs.
- title: Users & RBAC
details: Admin and regular users; global and per-user API tokens; gallery scoped by owner.
- title: Zero-config Docker
+6 -6
View File
@@ -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. 获取图片列表
+22
View File
@@ -4,6 +4,28 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
---
## [1.4.4] — 2026-10-10
### 修复
- Cap 登录验证支持 hashwx,并继续兼容旧的 SHA-256 site key
## [1.4.3] — 2026-10-09
### 新增
- **Telegram 存储后端**:频道/群组存图,直链仍经 PicHost;可选 API 代理
## [1.4.2] — 2026-09-23
### 修复
- 图库批量打标与上传 Token 鉴权(含 `API_UPLOAD_TOKEN` 兼容)
### 改进
- API 页单 Token;上传 `tagNames`;标签管理排序与移动端布局;API 文档表格式
## [1.4.1] — 2026-09-16
### 新增
+21 -4
View File
@@ -1,6 +1,6 @@
# 存储
PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、腾讯云 COS、阿里云 OSS、AWS S3 等)。管理员在 **存储**(`/storage`)页管理后端;新上传写入 **默认后端**。页面顶部展示 **存储总览**(总量、已用、剩余、使用率与容量分布),下方为各后端卡片与支持的后端类型说明。
PicHost 支持 **本地磁盘**、**S3 兼容对象存储**(Cloudflare R2、腾讯云 COS、阿里云 OSS、AWS S3 等)与 **Telegram 频道/群组**。管理员在 **存储**(`/storage`)页管理后端;新上传写入 **默认后端**。页面顶部展示 **存储总览**(总量、已用、剩余、使用率与容量分布),下方为各后端卡片与支持的后端类型说明。
![存储管理](/screenshots/storage.png)
@@ -23,11 +23,11 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
## 添加存储后端
1. 以管理员登录,打开 **存储** → **添加存储**。
2. 选择类型:**本地磁盘** 或 **S3 兼容**(含 R2 / COS / OSS 预设)。
3. 填写连接信息(桶名、Endpoint、Access Key 等)。
2. 选择类型:**本地磁盘**、**S3 兼容**(含 R2 / COS / OSS 预设)或 **Telegram 频道**。
3. 填写连接信息(桶名、Endpoint、Access Key,或 Bot Token / Chat ID 等)。
4. 保存后可 **设默认**,新上传将写入该后端。
新建对象存储后端的 **存储标识** 按类型自动生成前缀:本地为 `local`;R2 为 `r2-*`;COS 为 `cos-*`;OSS 为 `oss-*`;AWS S3 及自定义 S3 兼容为 `s3-*`(创建后不可修改,图片索引会引用该 ID)。
新建后端的 **存储标识** 按类型自动生成前缀:本地为 `local`;R2 为 `r2-*`;COS 为 `cos-*`;OSS 为 `oss-*`;AWS S3 及自定义 S3 兼容为 `s3-*`;Telegram 为 `tg-*`(创建后不可修改,图片索引会引用该 ID)。
### Cloudflare R2 要点
@@ -40,6 +40,23 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
若仓库 **cloudflare** 分支专用于「仅 R2」部署,也可用环境变量预设,见 [文档首页](./index.md) 分支说明。
### Telegram 频道 / 群组
用 Bot 把图片发进指定频道或群组(含私有频道),访客仍通过 PicHost 直链访问,不会跳到 Telegram 文件地址。
1. 在 [@BotFather](https://t.me/BotFather) 创建 Bot,取得 Token。
2. 把 Bot 设为频道或群组管理员(需要发消息;若希望图库删除时同步删掉群消息,还需要删除消息权限)。
3. 在存储页选择 **Telegram 频道**,填写 Chat ID(超级群组/频道多为 `-100…`)、Bot Token,以及套餐配额。
4. 服务器若不能直连 `api.telegram.org`,可填写可选的 HTTP/HTTPS API 代理(如 `http://127.0.0.1:7890`)。
限制与行为:
- 单文件实际上限约 **20MB**(超过站点上传限制时,以更小者为准)
- 同一频道大约 **20 条消息/分钟**;批量上传过快会失败并提示稍后重试
- 直链固定为 **proxy**,不能改为公开 URL
- 图库删除会尝试删除对应的 Telegram 消息;上传失败且未记下文件编号时,会尽量撤回刚发出的消息
- 整站备份会经 Bot 拉取文件,耗时并受上述频率限制;备份包不含 Bot Token,恢复后需重新填写。恢复到 Telegram 默认后端时,会把图片重新发进频道
### 环境变量(可选)
部分部署用环境变量初始化默认 S3 后端(如 `STORAGE_BACKEND=s3`、`S3_ENDPOINT`、`S3_BUCKET`、`S3_ACCESS_KEY`、`S3_SECRET_KEY`、`S3_REGION`)。**UI 中配置的后端信息存于 SQLite**,与环境变量并存时以管理界面为准管理多后端。
+7 -12
View File
@@ -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)
## 相关
+1 -1
View File
@@ -20,7 +20,7 @@ features:
- title: 拖拽 / 粘贴上传
details: 支持点击、拖拽与 Ctrl+V 粘贴;服务端 WebP 压缩与 Referer 防盗链。
- title: 多后端存储
details: 本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);proxy 或 public 直链模式。
details: 本地磁盘 + S3 兼容(R2 / COS / OSS / AWS)+ Telegram 频道/群组;proxy 或 public 直链。
- title: 多用户与权限
details: 管理员与普通用户 RBAC;全局 Token 与个人 Token;图库按归属隔离。
- title: Docker 零配置
+17 -4
View File
@@ -196,6 +196,7 @@
"colName": "Tag name",
"colImageCount": "Images",
"colLastUsed": "Last used",
"colCreatedAt": "Created",
"neverUsed": "Never used",
"colActions": "Actions",
"mergeIntoAction": "Merge into…",
@@ -454,6 +455,18 @@
"providerOss": "Alibaba OSS",
"providerAws": "AWS S3",
"providerCustom": "Custom",
"providerTelegram": "Telegram channel",
"backendTelegram": "Telegram",
"telegramChatId": "Chat ID",
"telegramChatIdPlaceholder": "-1001234567890",
"telegramChatIdHint": "Channel or group ID; the bot must be an admin. Private channels work.",
"telegramBotToken": "Bot Token",
"telegramApiProxy": "API proxy (optional)",
"telegramApiProxyPlaceholder": "http://127.0.0.1:7890",
"telegramApiProxyHint": "HTTP/HTTPS proxy for PicHost → Telegram API; leave empty for direct access.",
"telegramServingHint": "Image URLs are always served through PicHost, never redirected to Telegram.",
"telegramQuotaHint": "Telegram practical limit is ~20MB per file and ~20 messages/min per channel.",
"telegramSecretsRequired": "Bot Token and Chat ID are required",
"endpoint": "Endpoint",
"region": "Region",
"bucket": "Bucket",
@@ -515,6 +528,7 @@
"supportedR2Desc": "Highly available, low-cost object storage",
"supportedS3Title": "S3 compatible",
"supportedS3Desc": "Storage services compatible with the Amazon S3 API",
"supportedTelegramDesc": "Store images in a Telegram channel or group; good for light unlimited storage",
"footerTip": "The default backend receives all new uploads",
"statTotal": "Total",
"statUsed": "Used",
@@ -824,13 +838,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 +893,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",
+16 -3
View File
@@ -196,6 +196,7 @@
"colName": "标签名称",
"colImageCount": "图片数",
"colLastUsed": "最近使用",
"colCreatedAt": "创建时间",
"neverUsed": "从未使用",
"colActions": "操作",
"mergeIntoAction": "合并到…",
@@ -454,6 +455,18 @@
"providerOss": "阿里云 OSS",
"providerAws": "AWS S3",
"providerCustom": "自定义",
"providerTelegram": "Telegram 频道",
"backendTelegram": "Telegram",
"telegramChatId": "Chat ID",
"telegramChatIdPlaceholder": "-1001234567890",
"telegramChatIdHint": "频道或群组 ID;Bot 须为管理员。私有频道可用。",
"telegramBotToken": "Bot Token",
"telegramApiProxy": "API 代理(可选)",
"telegramApiProxyPlaceholder": "http://127.0.0.1:7890",
"telegramApiProxyHint": "PicHost 访问 Telegram API 时使用的 HTTP/HTTPS 代理;留空为直连。",
"telegramServingHint": "图片直链固定经 PicHost 代理,不会跳转到 Telegram。",
"telegramQuotaHint": "Telegram 单文件实际可读上限约 20MB;频道约 20 条/分钟。",
"telegramSecretsRequired": "请填写 Bot Token 与 Chat ID",
"endpoint": "Endpoint",
"region": "Region",
"bucket": "Bucket",
@@ -515,6 +528,7 @@
"supportedR2Desc": "高可用、低成本的对象存储",
"supportedS3Title": "S3 兼容",
"supportedS3Desc": "兼容 Amazon S3 协议的存储服务",
"supportedTelegramDesc": "用 Telegram 频道/群组存图,适合轻量与无限容量场景",
"footerTip": "默认存储后端将自动接收所有新上传的图片",
"statTotal": "总量",
"statUsed": "已用",
@@ -830,7 +844,7 @@
"personalTitle": "个人 API Token",
"personalDesc": "此 Token 仅用于您自己的脚本上传,上传的图片归属您的账号。",
"notConfiguredTitle": "尚未配置 Token",
"notConfiguredDesc": "点击「重新生成」创建 Token,用于下方所有接口的 Auth-Token 鉴权。",
"notConfiguredDesc": "首次打开会自动创建 Token,或点击「重新生成」。",
"regenerate": "重新生成",
"tokenSourceEnv": "来源:环境变量 API_UPLOAD_TOKEN",
"tokenSourceDb": "来源:后台生成(可重新生成)",
@@ -879,8 +893,7 @@
"file": "兼容字段,单图上传",
"files": "兼容字段,多图上传",
"token": "Twikoo 协议兼容,表单 token",
"tagIds": "可选,JSON 数组或重复字段,上传后按 ID 打标",
"tagNames": "可选,JSON 数组或逗号分隔;名称不存在则自动创建,存在则复用"
"tagNames": "可选,JSON 数组或逗号分隔;名称不存在则创建,存在则复用"
},
"list": {
"limit": "每页条数,默认 20,最大 100",
+7
View File
@@ -50,6 +50,13 @@ export default defineNuxtConfig({
nitro: {
preset: 'node-server',
publicAssets: [
{
baseURL: '/cap',
dir: join(rootDir, 'node_modules/@cap.js/wasm/browser'),
maxAge: 60 * 60 * 24 * 30
}
],
scheduledTasks: {
'0 3 * * *': ['auto-delete']
}
+24 -7
View File
@@ -1,24 +1,26 @@
{
"name": "pichost",
"version": "1.4.1",
"version": "1.4.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pichost",
"version": "1.4.1",
"version": "1.4.4",
"hasInstallScript": true,
"license": "GPL-3.0-only",
"dependencies": {
"@aws-sdk/client-s3": "^3.876.0",
"@cap.js/wasm": "^0.0.8",
"@iconify-json/lucide": "^1.2.114",
"@nuxt/ui": "^4.9.0",
"@nuxtjs/i18n": "^10.6.0",
"cap-widget": "^0.1.57",
"cap-widget": "^0.1.58",
"nuxt": "^4.4.8",
"sharp": "^0.35.3",
"tailwindcss": "^4.3.1",
"tar": "^7.5.22"
"tar": "^7.5.22",
"undici": "^7.30.0"
},
"devDependencies": {
"@nuxt/eslint": "^1.16.0",
@@ -1047,6 +1049,12 @@
"dev": true,
"license": "MIT"
},
"node_modules/@cap.js/wasm": {
"version": "0.0.8",
"resolved": "https://registry.npmmirror.com/@cap.js/wasm/-/wasm-0.0.8.tgz",
"integrity": "sha512-rX+4/v2sz4GKLnygXHOS89O7c4GM2qNQcDJP6Y2cyGwoKjg83bsfWHt1TWr9GBzHpFADvju5fvLWYds21nS8sA==",
"license": "Apache-2.0"
},
"node_modules/@capsizecss/unpack": {
"version": "4.0.1",
"resolved": "https://registry.npmmirror.com/@capsizecss/unpack/-/unpack-4.0.1.tgz",
@@ -10729,9 +10737,9 @@
"license": "CC-BY-4.0"
},
"node_modules/cap-widget": {
"version": "0.1.57",
"resolved": "https://registry.npmmirror.com/cap-widget/-/cap-widget-0.1.57.tgz",
"integrity": "sha512-SyIK5XgYIFSDgH683M9KpfBmDSDB0ZfPZQBxL6MggNrjjnbIQYpbsNpj0S7PC/wXp7oJgAuBD2vtJnN9jJghBg==",
"version": "0.1.58",
"resolved": "https://registry.npmmirror.com/cap-widget/-/cap-widget-0.1.58.tgz",
"integrity": "sha512-7iS/Q++AaiVvWR8xvMSxRwGWY+fV1ZADJNwPzLk4P1gibCmCbS5G6MGOtoUjsj9OxI9+0nkewW6gRsOGDCOZZA==",
"license": "Apache-2.0"
},
"node_modules/ccount": {
@@ -19181,6 +19189,15 @@
"node": ">=18.12.0"
}
},
"node_modules/undici": {
"version": "7.30.0",
"resolved": "https://registry.npmmirror.com/undici/-/undici-7.30.0.tgz",
"integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==",
"license": "MIT",
"engines": {
"node": ">=20.18.1"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",
+5 -3
View File
@@ -1,6 +1,6 @@
{
"name": "pichost",
"version": "1.4.1",
"version": "1.4.4",
"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": {
@@ -46,14 +46,16 @@
},
"dependencies": {
"@aws-sdk/client-s3": "^3.876.0",
"@cap.js/wasm": "^0.0.8",
"@iconify-json/lucide": "^1.2.114",
"@nuxt/ui": "^4.9.0",
"@nuxtjs/i18n": "^10.6.0",
"cap-widget": "^0.1.57",
"cap-widget": "^0.1.58",
"nuxt": "^4.4.8",
"sharp": "^0.35.3",
"tailwindcss": "^4.3.1",
"tar": "^7.5.22"
"tar": "^7.5.22",
"undici": "^7.30.0"
},
"devDependencies": {
"@nuxt/eslint": "^1.16.0",
+34 -2
View File
@@ -9,6 +9,11 @@ import {
type StorageBackendPatch
} from '../../../utils/storage-backends'
import { parseS3Config, validateS3Config } from '../../../utils/storage/s3'
import {
parseTelegramConfig,
validateTelegramConfig,
validateApiProxyUrl
} from '../../../utils/storage/telegram'
import { parseQuotaBytes } from '../../../utils/storage-capacity'
import type { ServingMode } from '../../../utils/storage/types'
@@ -20,10 +25,13 @@ interface StoragePatchBody {
bucket?: string
prefix?: string
forcePathStyle?: boolean
chatId?: string
apiProxyUrl?: string
}
secrets?: {
accessKeyId?: string
secretAccessKey?: string
botToken?: string
}
servingMode?: ServingMode
publicUrl?: string
@@ -63,6 +71,26 @@ export default defineEventHandler(async (event) => {
patch.name = body.name.trim() || row.name
}
if (body.config !== undefined && row.type === 'telegram') {
const current = parseTelegramConfig(row.config_json) ?? { chatId: '' }
const apiProxyUrl = body.config.apiProxyUrl?.trim() ?? current.apiProxyUrl ?? ''
const next = {
chatId: body.config.chatId?.trim() ?? current.chatId,
apiProxyUrl: apiProxyUrl || undefined
}
const error = validateTelegramConfig(next)
if (error) {
createApiError(event, 'INVALID_REQUEST', error, 400)
}
if (apiProxyUrl) {
const proxyError = validateApiProxyUrl(apiProxyUrl)
if (proxyError) {
createApiError(event, 'INVALID_REQUEST', proxyError, 400)
}
}
patch.config = next
}
if (body.config !== undefined && row.type === 's3') {
const current = parseS3Config(row.config_json) ?? {
endpoint: '',
@@ -87,7 +115,11 @@ export default defineEventHandler(async (event) => {
patch.secrets = body.secrets
}
if (body.servingMode !== undefined) {
if (body.secrets !== undefined && row.type === 'telegram') {
patch.secrets = body.secrets
}
if (body.servingMode !== undefined && row.type !== 'telegram') {
if (body.servingMode !== 'proxy' && body.servingMode !== 'public') {
createApiError(event, 'INVALID_REQUEST', '访问方式无效', 400)
}
@@ -99,7 +131,7 @@ export default defineEventHandler(async (event) => {
}
if (body.quotaBytes !== undefined) {
if (row.type === 's3') {
if (row.type === 's3' || row.type === 'telegram') {
const quotaBytes = parseQuotaBytes(body.quotaBytes)
if (!quotaBytes) {
createApiError(event, 'INVALID_REQUEST', '请填写有效的存储套餐总量', 400)
+53
View File
@@ -2,13 +2,19 @@ import { requireAdminAuth } from '../../../utils/access'
import { createApiError } from '../../../utils/api-error'
import {
insertStorageBackend,
insertTelegramBackend,
isStorageEnvConfigured
} from '../../../utils/storage-backends'
import { validateS3Config } from '../../../utils/storage/s3'
import {
validateTelegramConfig,
validateApiProxyUrl
} from '../../../utils/storage/telegram'
import { parseQuotaBytes } from '../../../utils/storage-capacity'
import type { ServingMode } from '../../../utils/storage/types'
interface StorageCreateBody {
type?: 's3' | 'telegram'
name?: string
provider?: string
config?: {
@@ -17,10 +23,13 @@ interface StorageCreateBody {
bucket?: string
prefix?: string
forcePathStyle?: boolean
chatId?: string
apiProxyUrl?: string
}
secrets?: {
accessKeyId?: string
secretAccessKey?: string
botToken?: string
}
servingMode?: ServingMode
publicUrl?: string
@@ -40,6 +49,50 @@ export default defineEventHandler(async (event) => {
(): StorageCreateBody => ({})
)
const backendType = body.type === 'telegram' ? 'telegram' : 's3'
if (backendType === 'telegram') {
const name = body.name?.trim() || 'Telegram 频道'
const chatId = body.config?.chatId?.trim() ?? ''
const apiProxyUrl = body.config?.apiProxyUrl?.trim() ?? ''
const botToken = body.secrets?.botToken?.trim() ?? ''
if (!chatId || !botToken) {
createApiError(event, 'INVALID_REQUEST', 'Bot Token 与 Chat ID 不能为空', 400)
}
const config = {
chatId,
apiProxyUrl: apiProxyUrl || undefined
}
const configError = validateTelegramConfig(config)
if (configError) {
createApiError(event, 'INVALID_REQUEST', configError, 400)
}
if (apiProxyUrl) {
const proxyError = validateApiProxyUrl(apiProxyUrl)
if (proxyError) {
createApiError(event, 'INVALID_REQUEST', proxyError, 400)
}
}
const quotaBytes = parseQuotaBytes(body.quotaBytes)
if (!quotaBytes) {
createApiError(event, 'INVALID_REQUEST', '请填写有效的存储套餐总量', 400)
}
const id = insertTelegramBackend({
name,
config,
secrets: { botToken },
quotaBytes,
enabled: body.enabled,
isDefault: body.isDefault
})
return { success: true, id }
}
const name = body.name?.trim() || 'S3 兼容存储'
const config = {
endpoint: body.config?.endpoint?.trim() ?? '',
+6 -3
View File
@@ -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 }
+2 -5
View File
@@ -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)
}
+5 -1
View File
@@ -106,7 +106,11 @@ export default defineEventHandler(async (event) => {
? {
id: row.backend_id,
name: row.backend_name ?? row.backend_id,
type: (row.backend_type === 'local' ? 'local' : 's3') as 'local' | 's3'
type: (row.backend_type === 'local'
? 'local'
: row.backend_type === 'telegram'
? 'telegram'
: 's3') as 'local' | 's3' | 'telegram'
}
: null,
ipAddress: row.ip_address,
+6 -7
View File
@@ -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) {
+22
View File
@@ -0,0 +1,22 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterAll, beforeAll } from 'vitest'
import { closeDb } from '../utils/db'
const workerId = process.env.VITEST_POOL_ID ?? String(process.pid)
const dataDir = mkdtempSync(join(tmpdir(), `pichost-test-${workerId}-`))
process.env.DATA_DIR = dataDir
beforeAll(() => {
closeDb()
})
afterAll(() => {
closeDb()
try {
rmSync(dataDir, { recursive: true, force: true })
} catch {
// Windows may still hold the sqlite file for a moment after close
}
})
+58 -11
View File
@@ -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
}
+6 -1
View File
@@ -7,6 +7,7 @@ import {
listStorageBackendRows
} from '../storage-backends'
import { parseS3Config } from '../storage/s3'
import { parseTelegramConfig } from '../storage/telegram'
import { createImageStream } from '../storage'
import { copyDatabaseSnapshot } from './db-snapshot'
import { markJobDone, markJobFailed, updateBackupJob } from './jobs'
@@ -27,7 +28,11 @@ function buildStorageBackendsMeta(): StorageBackendMetaExport[] {
id: row.id,
name: row.name,
type: row.type,
config: row.type === 's3' ? (parseS3Config(row.config_json) ?? {}) : {},
config: row.type === 's3'
? (parseS3Config(row.config_json) ?? {})
: row.type === 'telegram'
? (parseTelegramConfig(row.config_json) ?? {})
: {},
servingMode: row.serving_mode,
publicUrl: row.public_url,
quotaBytes: row.quota_bytes,
+8
View File
@@ -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)
}
+2 -1
View File
@@ -131,7 +131,8 @@ describe('shouldBlockSiteHostImageRequest', () => {
siteHost,
requestHost: siteHost,
method: 'GET',
pathname: '/'
pathname: '/',
hideFolder: false
})).toBe(false)
})
+9 -5
View File
@@ -12,8 +12,8 @@ import { generateImageKey } from './image-key'
import { buildImageItem, sanitizeOriginalName } from './image-response'
import { getStorageLayout, getWebpQuality } from './env'
import {
formatMaxFileSizeMessage,
getMaxFileSizeBytes,
formatEffectiveMaxFileSizeMessage,
getEffectiveMaxFileSizeBytes,
isMimeTypeAllowed,
isPreserveOriginalUpload
} from './upload-policy'
@@ -73,13 +73,13 @@ export async function processSingleImageUpload(
const originalName = sanitizeOriginalName(input.filename ?? 'image')
const bytes = input.bytes
if (bytes.byteLength > getMaxFileSizeBytes()) {
if (bytes.byteLength > getEffectiveMaxFileSizeBytes()) {
return {
error: {
name: originalName,
error: {
code: 'FILE_TOO_LARGE',
message: formatMaxFileSizeMessage()
message: formatEffectiveMaxFileSizeMessage()
}
}
}
@@ -144,12 +144,16 @@ export async function processSingleImageUpload(
name: originalName,
source: input.source ?? 'web'
})
const detail = error instanceof Error ? error.message.trim() : ''
const message = detail.startsWith('Telegram') || detail.includes('群组')
? detail
: '上传失败,请稍后重试'
return {
error: {
name: originalName,
error: {
code: 'UPLOAD_FAILED',
message: '上传失败,请稍后重试'
message
}
}
}
+155 -5
View File
@@ -1,28 +1,99 @@
import type { DatabaseSync } from 'node:sqlite'
import { getDb } from './db'
import { LocalStorageBackend } from './storage/local'
import { deleteStorageObjectRefsForBackend } from './storage/storage-object-refs'
import {
parseS3Config,
parseS3Secrets,
S3StorageBackend
} from './storage/s3'
import {
parseTelegramConfig,
parseTelegramSecrets,
TelegramStorageBackend
} from './storage/telegram'
import type {
S3BackendConfig,
ServingMode,
StorageBackendInfo,
StorageBackendRow,
StorageBackendType
StorageBackendType,
TelegramBackendConfig,
TelegramBackendSecrets
} from './storage/types'
export const LOCAL_BACKEND_ID = 'local'
export const S3_BACKEND_ID = 's3-primary'
const STORAGE_SCHEMA_TELEGRAM_KEY = 'storage_schema_telegram_v1'
function migrateStorageBackendTelegramType(database: DatabaseSync): void {
const flag = database.prepare(`
SELECT value FROM settings WHERE key = ?
`).get(STORAGE_SCHEMA_TELEGRAM_KEY) as { value?: string } | undefined
if (flag?.value === '1') {
return
}
const tableRow = database.prepare(`
SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'storage_backends'
`).get() as { sql?: string } | undefined
const needsRebuild = Boolean(
tableRow?.sql && !tableRow.sql.includes('telegram')
)
if (!needsRebuild) {
database.prepare(`
INSERT OR REPLACE INTO settings (key, value, updated_at)
VALUES (?, '1', ?)
`).run(STORAGE_SCHEMA_TELEGRAM_KEY, new Date().toISOString())
return
}
database.exec('PRAGMA foreign_keys = OFF')
database.exec('BEGIN')
try {
database.exec(`
CREATE TABLE storage_backends_new (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK(type IN ('local', 's3', 'telegram')),
config_json TEXT NOT NULL DEFAULT '{}',
secret_json TEXT NOT NULL DEFAULT '{}',
serving_mode TEXT NOT NULL DEFAULT 'proxy' CHECK(serving_mode IN ('proxy', 'public')),
public_url TEXT NOT NULL DEFAULT '',
quota_bytes INTEGER,
enabled INTEGER NOT NULL DEFAULT 1,
is_default INTEGER NOT NULL DEFAULT 0,
sort_order INTEGER NOT NULL DEFAULT 0
)
`)
database.exec(`
INSERT INTO storage_backends_new
SELECT * FROM storage_backends
`)
database.exec('DROP TABLE storage_backends')
database.exec('ALTER TABLE storage_backends_new RENAME TO storage_backends')
database.prepare(`
INSERT OR REPLACE INTO settings (key, value, updated_at)
VALUES (?, '1', ?)
`).run(STORAGE_SCHEMA_TELEGRAM_KEY, new Date().toISOString())
database.exec('COMMIT')
} catch (error) {
database.exec('ROLLBACK')
throw error
} finally {
database.exec('PRAGMA foreign_keys = ON')
}
}
function migrateStorageTables(database: DatabaseSync): void {
database.exec(`
CREATE TABLE IF NOT EXISTS storage_backends (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
type TEXT NOT NULL CHECK(type IN ('local', 's3')),
type TEXT NOT NULL CHECK(type IN ('local', 's3', 'telegram')),
config_json TEXT NOT NULL DEFAULT '{}',
secret_json TEXT NOT NULL DEFAULT '{}',
serving_mode TEXT NOT NULL DEFAULT 'proxy' CHECK(serving_mode IN ('proxy', 'public')),
@@ -47,7 +118,15 @@ function migrateStorageTables(database: DatabaseSync): void {
CREATE INDEX IF NOT EXISTS idx_images_backend_id ON images(backend_id);
CREATE INDEX IF NOT EXISTS idx_images_user_id ON images(user_id);
CREATE INDEX IF NOT EXISTS idx_images_folder ON images(folder);
CREATE TABLE IF NOT EXISTS storage_object_refs (
backend_id TEXT NOT NULL,
key TEXT NOT NULL,
ref_json TEXT NOT NULL,
PRIMARY KEY (backend_id, key),
FOREIGN KEY (backend_id) REFERENCES storage_backends(id)
);
`)
migrateStorageBackendTelegramType(database)
}
export function ensureStorageSchema(): void {
@@ -109,6 +188,8 @@ function rowToInfo(row: StorageBackendRow, _maskSecrets = true): StorageBackendI
} {
const config = row.type === 's3'
? (parseS3Config(row.config_json) ?? {})
: row.type === 'telegram'
? (parseTelegramConfig(row.config_json) ?? {})
: {}
let secretsMasked: Record<string, string> = {}
if (row.type === 's3') {
@@ -121,6 +202,11 @@ function rowToInfo(row: StorageBackendRow, _maskSecrets = true): StorageBackendI
? maskSecret(secrets.secretAccessKey)
: ''
}
} else if (row.type === 'telegram') {
const secrets = parseTelegramSecrets(row.secret_json)
secretsMasked = {
botToken: secrets?.botToken ? maskSecret(secrets.botToken) : ''
}
}
return {
@@ -213,7 +299,11 @@ export function setDefaultBackend(id: string): void {
export interface StorageBackendPatch {
name?: string
config?: Record<string, unknown>
secrets?: { accessKeyId?: string, secretAccessKey?: string }
secrets?: {
accessKeyId?: string
secretAccessKey?: string
botToken?: string
}
servingMode?: ServingMode
publicUrl?: string
quotaBytes?: number | null
@@ -234,6 +324,8 @@ export function updateStorageBackend(id: string, patch: StorageBackendPatch): vo
if (patch.config !== undefined) {
const current = row.type === 's3'
? (parseS3Config(row.config_json) ?? {})
: row.type === 'telegram'
? (parseTelegramConfig(row.config_json) ?? { chatId: '' })
: {}
configJson = JSON.stringify({ ...current, ...patch.config })
}
@@ -254,7 +346,20 @@ export function updateStorageBackend(id: string, patch: StorageBackendPatch): vo
secretJson = JSON.stringify(next)
}
const servingMode = patch.servingMode ?? row.serving_mode
if (patch.secrets !== undefined && row.type === 'telegram') {
const current = parseTelegramSecrets(row.secret_json) ?? { botToken: '' }
const next = {
botToken: patch.secrets.botToken?.trim()
? patch.secrets.botToken.trim()
: current.botToken
}
secretJson = JSON.stringify(next)
}
let servingMode = patch.servingMode ?? row.serving_mode
if (row.type === 'telegram') {
servingMode = 'proxy'
}
const publicUrl = patch.publicUrl ?? row.public_url
const quotaBytes = patch.quotaBytes !== undefined
? patch.quotaBytes
@@ -323,6 +428,15 @@ export function createBackendInstance(row: StorageBackendRow) {
)
}
if (row.type === 'telegram') {
const config = parseTelegramConfig(row.config_json)
const secrets = parseTelegramSecrets(row.secret_json)
if (!config || !secrets) {
throw new Error(`Invalid Telegram configuration for backend ${row.id}`)
}
return new TelegramStorageBackend(row.id, config, secrets)
}
const config = parseS3Config(row.config_json)
const secrets = parseS3Secrets(row.secret_json)
if (!config || !secrets) {
@@ -368,7 +482,7 @@ function getNextSortOrder(): number {
return row.max_order + 1
}
export type ObjectStorageIdPrefix = 'r2' | 'cos' | 'oss' | 's3'
export type ObjectStorageIdPrefix = 'r2' | 'cos' | 'oss' | 's3' | 'tg'
/** 根据表单预设或 endpoint 推断新建后端的 id 前缀 */
export function resolveObjectStorageIdPrefix(
@@ -438,6 +552,41 @@ export function insertStorageBackend(input: {
return id
}
export function insertTelegramBackend(input: {
id?: string
name: string
config: TelegramBackendConfig
secrets: TelegramBackendSecrets
quotaBytes?: number | null
enabled?: boolean
isDefault?: boolean
}): string {
ensureDefaultBackends()
const id = input.id ?? generateStorageBackendId('tg')
const sortOrder = getNextSortOrder()
getDb().prepare(`
INSERT INTO storage_backends
(id, name, type, config_json, secret_json, serving_mode, public_url,
quota_bytes, enabled, is_default, sort_order)
VALUES (?, ?, 'telegram', ?, ?, 'proxy', '', ?, ?, 0, ?)
`).run(
id,
input.name,
JSON.stringify(input.config),
JSON.stringify(input.secrets),
input.quotaBytes ?? null,
input.enabled === false ? 0 : 1,
sortOrder
)
if (input.isDefault) {
setDefaultBackend(id)
}
return id
}
export function deleteStorageBackend(id: string): void {
if (id === LOCAL_BACKEND_ID) {
throw new Error('Cannot delete local backend')
@@ -457,5 +606,6 @@ export function deleteStorageBackend(id: string): void {
throw new Error('Cannot delete the default backend')
}
deleteStorageObjectRefsForBackend(id)
getDb().prepare('DELETE FROM storage_backends WHERE id = ?').run(id)
}
+2 -2
View File
@@ -51,11 +51,11 @@ function buildQuotaCapacity(quotaBytes: number, indexBytes: number): StorageCapa
export async function buildBackendCapacity(
backendId: string,
backendType: 'local' | 's3',
backendType: 'local' | 's3' | 'telegram',
indexBytes: number,
quotaBytes: number | null
): Promise<StorageCapacity> {
if (backendType === 's3') {
if (backendType === 's3' || backendType === 'telegram') {
if (quotaBytes && quotaBytes > 0) {
return buildQuotaCapacity(quotaBytes, indexBytes)
}
+7
View File
@@ -1,3 +1,10 @@
export { getActiveBackend, getBackendForKey, getActiveBackendRow, getBackendRowForKey } from './resolver'
export { LocalStorageBackend } from './local'
export { S3StorageBackend, buildObjectKey, parseS3Config, validateS3Config } from './s3'
export {
TelegramStorageBackend,
parseTelegramConfig,
parseTelegramSecrets,
validateTelegramConfig,
TELEGRAM_MAX_FILE_BYTES
} from './telegram'
@@ -0,0 +1,44 @@
import { getDb } from '../db'
import type { TelegramObjectRef } from './types'
export function getStorageObjectRef(
backendId: string,
key: string
): TelegramObjectRef | null {
const row = getDb().prepare(`
SELECT ref_json FROM storage_object_refs
WHERE backend_id = ? AND key = ?
`).get(backendId, key) as { ref_json: string } | undefined
if (!row) return null
try {
return JSON.parse(row.ref_json) as TelegramObjectRef
} catch {
return null
}
}
export function setStorageObjectRef(
backendId: string,
key: string,
ref: TelegramObjectRef
): void {
getDb().prepare(`
INSERT INTO storage_object_refs (backend_id, key, ref_json)
VALUES (?, ?, ?)
ON CONFLICT(backend_id, key) DO UPDATE SET ref_json = excluded.ref_json
`).run(backendId, key, JSON.stringify(ref))
}
export function deleteStorageObjectRef(backendId: string, key: string): void {
getDb().prepare(`
DELETE FROM storage_object_refs WHERE backend_id = ? AND key = ?
`).run(backendId, key)
}
export function deleteStorageObjectRefsForBackend(backendId: string): void {
getDb().prepare(`
DELETE FROM storage_object_refs WHERE backend_id = ?
`).run(backendId)
}
+322
View File
@@ -0,0 +1,322 @@
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest'
import { closeDb } from '../db'
import {
parseTelegramConfig,
parseTelegramSecrets,
validateApiProxyUrl,
validateTelegramConfig,
TelegramStorageBackend,
TELEGRAM_MAX_FILE_BYTES
} from './telegram'
import {
deleteStorageObjectRef,
getStorageObjectRef
} from './storage-object-refs'
import {
ensureDefaultBackends,
ensureStorageSchema,
getStorageBackendRow,
insertTelegramBackend
} from '../storage-backends'
describe('telegram config', () => {
it('parses chat id and optional proxy', () => {
const config = parseTelegramConfig(JSON.stringify({
chatId: '-1001',
apiProxyUrl: 'http://127.0.0.1:7890'
}))
expect(config).toEqual({
chatId: '-1001',
apiProxyUrl: 'http://127.0.0.1:7890'
})
})
it('rejects invalid proxy protocol', () => {
expect(validateApiProxyUrl('socks5://127.0.0.1:1080')).toMatch(/http/)
})
it('accepts http proxy', () => {
expect(validateApiProxyUrl('http://127.0.0.1:7890')).toBeNull()
})
it('validates required chat id', () => {
expect(validateTelegramConfig({ chatId: '' })).toBeTruthy()
expect(validateTelegramConfig({ chatId: '-100' })).toBeNull()
})
it('parses bot token secret', () => {
expect(parseTelegramSecrets(JSON.stringify({ botToken: '123:abc' }))).toEqual({
botToken: '123:abc'
})
})
it('exposes 20MB limit constant', () => {
expect(TELEGRAM_MAX_FILE_BYTES).toBe(20 * 1024 * 1024)
})
})
describe('TelegramStorageBackend', () => {
const backendId = 'tg-test'
const key = 'images/2026/01/test.webp'
const tempDir = mkdtempSync(join(tmpdir(), 'pichost-tg-'))
const previousDataDir = process.env.DATA_DIR
beforeAll(() => {
process.env.DATA_DIR = tempDir
closeDb()
})
afterAll(() => {
closeDb()
if (previousDataDir === undefined) {
delete process.env.DATA_DIR
} else {
process.env.DATA_DIR = previousDataDir
}
rmSync(tempDir, { recursive: true, force: true })
})
beforeEach(() => {
ensureStorageSchema()
ensureDefaultBackends()
if (!getStorageBackendRow(backendId)) {
insertTelegramBackend({
id: backendId,
name: 'TG test',
config: { chatId: '-100' },
secrets: { botToken: 'token' },
quotaBytes: 1024 * 1024 * 1024,
enabled: false
})
}
vi.stubGlobal('fetch', vi.fn())
})
afterEach(() => {
try {
deleteStorageObjectRef(backendId, key)
} catch {
// schema setup may have failed before the ref table existed
}
vi.unstubAllGlobals()
})
it('retries sendDocument after supergroup chat id migration', async () => {
const fetchMock = vi.mocked(fetch)
fetchMock
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
ok: false,
description: 'Bad Request: group chat was upgraded to a supergroup chat',
parameters: { migrate_to_chat_id: -100999 }
})
} as Response)
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
ok: true,
result: {
message_id: 99,
document: { file_id: 'MIG', file_unique_id: 'UQ2' }
}
})
} as Response)
const backend = new TelegramStorageBackend(
backendId,
{ chatId: '-123' },
{ botToken: 'token' }
)
await backend.put(key, new Uint8Array([4, 5]), {
originalName: 'test.webp',
uploadedAt: new Date().toISOString(),
contentType: 'image/webp',
size: 2
})
expect(fetchMock).toHaveBeenCalledTimes(2)
const ref = getStorageObjectRef(backendId, key)
expect(ref?.fileId).toBe('MIG')
})
it('put accepts a single photo object and sticker file id', async () => {
const fetchMock = vi.mocked(fetch)
fetchMock.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
ok: true,
result: {
message_id: 8,
sticker: { file_id: 'stk', file_unique_id: 'us' }
}
})
} as Response)
const backend = new TelegramStorageBackend(
backendId,
{ chatId: '-100' },
{ botToken: 'token' }
)
await backend.put(key, new Uint8Array([1]), {
originalName: 'test.webp',
uploadedAt: new Date().toISOString(),
contentType: 'image/webp',
size: 1
})
expect(getStorageObjectRef(backendId, key)?.fileId).toBe('stk')
})
it('put accepts photo array when document is absent', async () => {
const fetchMock = vi.mocked(fetch)
fetchMock.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
ok: true,
result: {
message_id: 7,
photo: [
{ file_id: 'small', file_unique_id: 'u1', width: 90, height: 90 },
{ file_id: 'large', file_unique_id: 'u2', width: 800, height: 600 }
]
}
})
} as Response)
const backend = new TelegramStorageBackend(
backendId,
{ chatId: '-100' },
{ botToken: 'token' }
)
await backend.put(key, new Uint8Array([1]), {
originalName: 'test.png',
uploadedAt: new Date().toISOString(),
contentType: 'image/png',
size: 1
})
const ref = getStorageObjectRef(backendId, key)
expect(ref?.fileId).toBe('large')
})
it('put stores file ref after sendDocument', async () => {
const fetchMock = vi.mocked(fetch)
fetchMock.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
ok: true,
result: {
message_id: 42,
document: {
file_id: 'AAA',
file_unique_id: 'UQ'
}
}
})
} as Response)
const backend = new TelegramStorageBackend(
backendId,
{ chatId: '-100' },
{ botToken: 'token' }
)
await backend.put(key, new Uint8Array([1, 2, 3]), {
originalName: 'test.webp',
uploadedAt: new Date().toISOString(),
contentType: 'image/webp',
size: 3
})
const ref = getStorageObjectRef(backendId, key)
expect(ref?.fileId).toBe('AAA')
expect(ref?.messageId).toBe(42)
})
it('testConnection reports telegram errors', async () => {
const fetchMock = vi.mocked(fetch)
fetchMock.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ ok: false, description: 'Unauthorized' })
} as Response)
const backend = new TelegramStorageBackend(
backendId,
{ chatId: '-100' },
{ botToken: 'bad' }
)
const result = await backend.testConnection()
expect(result.ok).toBe(false)
expect(result.message).toContain('Unauthorized')
})
it('createStream downloads file bytes', async () => {
const fetchMock = vi.mocked(fetch)
fetchMock.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
ok: true,
result: {
message_id: 1,
document: { file_id: 'FILE1', file_unique_id: 'U1' }
}
})
} as Response)
const putBackend = new TelegramStorageBackend(
backendId,
{ chatId: '-100' },
{ botToken: 'token' }
)
await putBackend.put(key, new Uint8Array([1]), {
originalName: 'test.webp',
uploadedAt: new Date().toISOString(),
contentType: 'image/webp',
size: 1
})
fetchMock.mockReset()
fetchMock
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
ok: true,
result: { file_id: 'FILE1', file_path: 'photos/file.jpg' }
})
} as Response)
.mockResolvedValueOnce({
ok: true,
status: 200,
arrayBuffer: async () => new Uint8Array([9, 8, 7]).buffer
} as Response)
const backend = new TelegramStorageBackend(
backendId,
{ chatId: '-100' },
{ botToken: 'token' }
)
const stream = await backend.createStream(key)
const chunks: Buffer[] = []
for await (const chunk of stream) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk))
}
expect(Buffer.concat(chunks)).toEqual(Buffer.from([9, 8, 7]))
})
})
+510
View File
@@ -0,0 +1,510 @@
import { Readable } from 'node:stream'
import { getImageIndexAsStored } from '../image-index'
import { validateImageKey } from '../image-key'
import { logException } from '../logger'
import {
deleteStorageObjectRef,
getStorageObjectRef,
setStorageObjectRef
} from './storage-object-refs'
import type {
ServingMode,
StoredImage,
StoredImageMeta,
StorageBackend,
TelegramBackendConfig,
TelegramBackendSecrets,
TelegramObjectRef
} from './types'
export const TELEGRAM_MAX_FILE_BYTES = 20 * 1024 * 1024
const TELEGRAM_API_BASE = 'https://api.telegram.org'
export function parseTelegramConfig(raw: string): TelegramBackendConfig | null {
try {
const parsed = JSON.parse(raw) as Partial<TelegramBackendConfig>
if (!parsed.chatId?.trim()) return null
const apiProxyUrl = parsed.apiProxyUrl?.trim()
return {
chatId: parsed.chatId.trim(),
apiProxyUrl: apiProxyUrl || undefined
}
} catch {
return null
}
}
export function parseTelegramSecrets(raw: string): TelegramBackendSecrets | null {
try {
const parsed = JSON.parse(raw) as Partial<TelegramBackendSecrets>
if (!parsed.botToken?.trim()) return null
return { botToken: parsed.botToken.trim() }
} catch {
return null
}
}
export function validateTelegramConfig(config: TelegramBackendConfig): string | null {
if (!config.chatId.trim()) {
return 'Chat ID 不能为空'
}
if (config.apiProxyUrl) {
const error = validateApiProxyUrl(config.apiProxyUrl)
if (error) return error
}
return null
}
export function validateApiProxyUrl(url: string): string | null {
const trimmed = url.trim()
if (!trimmed) return null
try {
const parsed = new URL(trimmed)
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
return null
}
return 'API 代理仅支持 http:// 或 https:// 地址'
} catch {
return 'API 代理地址格式无效'
}
}
interface TelegramApiResponse<T> {
ok: boolean
result?: T
description?: string
parameters?: {
retry_after?: number
migrate_to_chat_id?: number
}
}
export class TelegramApiCallError extends Error {
readonly migrateToChatId?: number
constructor(description: string, migrateToChatId?: number) {
super(formatTelegramApiErrorMessage(description, migrateToChatId))
this.name = 'TelegramApiCallError'
this.migrateToChatId = migrateToChatId
}
}
function formatTelegramApiErrorMessage(
description: string,
migrateToChatId?: number
): string {
if (migrateToChatId != null) {
return `Telegram 群组已升级,请使用 Chat ID:${migrateToChatId}`
}
const lower = description.toLowerCase()
if (lower.includes('upgraded to a supergroup')) {
return '群组已升级为超级群组,请在存储设置中更新 Chat ID(新 ID 一般为 -100 开头,可向 @GetTheirIDBot 查询)'
}
return description
}
interface TelegramFileIdentity {
file_id: string
file_unique_id: string
}
interface TelegramSentMessage {
message_id: number
document?: TelegramFileIdentity & { file_name?: string, thumbnail?: TelegramFileIdentity }
photo?: TelegramFileIdentity[] | TelegramFileIdentity
animation?: TelegramFileIdentity & { thumbnail?: TelegramFileIdentity }
video?: TelegramFileIdentity & { thumbnail?: TelegramFileIdentity }
sticker?: TelegramFileIdentity & { thumbnail?: TelegramFileIdentity }
audio?: TelegramFileIdentity
voice?: TelegramFileIdentity
video_note?: TelegramFileIdentity
}
function asFileIdentity(value: unknown): TelegramFileIdentity | null {
if (!value || typeof value !== 'object') return null
const rec = value as Partial<TelegramFileIdentity>
if (typeof rec.file_id !== 'string' || !rec.file_id) return null
return {
file_id: rec.file_id,
file_unique_id: typeof rec.file_unique_id === 'string' ? rec.file_unique_id : ''
}
}
function photoList(photo: TelegramSentMessage['photo']): TelegramFileIdentity[] {
if (!photo) return []
if (Array.isArray(photo)) {
return photo.map(asFileIdentity).filter((item): item is TelegramFileIdentity => item != null)
}
const single = asFileIdentity(photo)
return single ? [single] : []
}
function fileRefFromSentMessage(
message: TelegramSentMessage
): TelegramObjectRef | null {
const messageId = message.message_id
const document = asFileIdentity(message.document)
if (document) {
return {
fileId: document.file_id,
fileUniqueId: document.file_unique_id,
messageId
}
}
const photos = photoList(message.photo)
const largest = photos.at(-1)
if (largest) {
return {
fileId: largest.file_id,
fileUniqueId: largest.file_unique_id,
messageId
}
}
for (const media of [
message.sticker,
message.animation,
message.video,
message.audio,
message.voice,
message.video_note
]) {
const file = asFileIdentity(media)
if (file) {
return {
fileId: file.file_id,
fileUniqueId: file.file_unique_id,
messageId
}
}
}
return null
}
interface TelegramFile {
file_id: string
file_unique_id: string
file_path?: string
file_size?: number
}
function apiUrl(botToken: string, method: string): string {
return `${TELEGRAM_API_BASE}/bot${botToken}/${method}`
}
function fileDownloadUrl(botToken: string, filePath: string): string {
return `${TELEGRAM_API_BASE}/file/bot${botToken}/${filePath}`
}
async function telegramFetch(
url: string,
init: RequestInit,
apiProxyUrl?: string
): Promise<Response> {
const proxy = apiProxyUrl?.trim()
if (!proxy) {
return fetch(url, init)
}
const undici = await import('undici')
const dispatcher = new undici.ProxyAgent(proxy)
const response = await undici.fetch(url, {
...init,
dispatcher
} as Parameters<typeof undici.fetch>[1])
return response as unknown as Response
}
async function callTelegramApi<T>(
botToken: string,
method: string,
init: RequestInit,
apiProxyUrl?: string,
attempt = 0
): Promise<T> {
const response = await telegramFetch(apiUrl(botToken, method), init, apiProxyUrl)
const body = await response.json() as TelegramApiResponse<T>
if (!body.ok) {
const retryAfter = body.parameters?.retry_after
if (response.status === 429 && retryAfter && attempt < 2) {
await new Promise(resolve => setTimeout(resolve, retryAfter * 1000))
return callTelegramApi(botToken, method, init, apiProxyUrl, attempt + 1)
}
const description = body.description ?? `HTTP ${response.status}`
if (response.status === 429 || description.toLowerCase().includes('too many')) {
throw new Error('Telegram 请求过于频繁,请稍后重试')
}
const migrateToChatId = body.parameters?.migrate_to_chat_id
throw new TelegramApiCallError(description, migrateToChatId)
}
if (body.result === undefined) {
throw new Error('Telegram API 返回为空')
}
return body.result
}
function filenameFromKey(key: string): string {
const base = key.split('/').pop() ?? 'image'
return base.replace(/[^\w.-]+/g, '_').slice(0, 200) || 'image'
}
/** Node fetch + FormData/Blob 发往 Telegram 时经常丢文件,改用手写 multipart。 */
function buildSendDocumentMultipart(input: {
chatId: string
caption: string
filename: string
bytes: Uint8Array
}): { body: Uint8Array, contentType: string } {
const boundary = `----PicHost${crypto.randomUUID().replace(/-/g, '')}`
const crlf = '\r\n'
const safeFilename = input.filename.replace(/"/g, '\\"')
const preamble = [
`--${boundary}${crlf}`,
`Content-Disposition: form-data; name="chat_id"${crlf}${crlf}`,
`${input.chatId}${crlf}`,
`--${boundary}${crlf}`,
`Content-Disposition: form-data; name="disable_content_type_detection"${crlf}${crlf}`,
`true${crlf}`,
`--${boundary}${crlf}`,
`Content-Disposition: form-data; name="caption"${crlf}${crlf}`,
`${input.caption}${crlf}`,
`--${boundary}${crlf}`,
`Content-Disposition: form-data; name="document"; filename="${safeFilename}"${crlf}`,
// 固定 octet-stream,避免 Telegram 把图片转成 photo 后响应里不带 file_id
`Content-Type: application/octet-stream${crlf}${crlf}`
].join('')
const suffix = `${crlf}--${boundary}--${crlf}`
const body = Buffer.concat([
Buffer.from(preamble, 'utf8'),
Buffer.from(input.bytes),
Buffer.from(suffix, 'utf8')
])
return {
body: new Uint8Array(body),
contentType: `multipart/form-data; boundary=${boundary}`
}
}
export class TelegramStorageBackend implements StorageBackend {
readonly id: string
readonly type = 'telegram' as const
readonly servingMode: ServingMode = 'proxy'
readonly publicUrl = ''
private chatId: string
private readonly botToken: string
private readonly apiProxyUrl?: string
constructor(
id: string,
config: TelegramBackendConfig,
secrets: TelegramBackendSecrets
) {
this.id = id
this.chatId = config.chatId
this.botToken = secrets.botToken
this.apiProxyUrl = config.apiProxyUrl
}
private async persistChatIdMigration(newChatId: string): Promise<void> {
if (newChatId === this.chatId) return
this.chatId = newChatId
const { updateStorageBackend } = await import('../storage-backends')
updateStorageBackend(this.id, { config: { chatId: newChatId } })
}
private async withChatIdMigrationRetry<T>(
fn: (chatId: string) => Promise<T>
): Promise<T> {
try {
return await fn(this.chatId)
} catch (error) {
if (
error instanceof TelegramApiCallError
&& error.migrateToChatId != null
) {
const newId = String(error.migrateToChatId)
await this.persistChatIdMigration(newId)
return await fn(newId)
}
throw error
}
}
async put(key: string, bytes: Uint8Array, _meta: StoredImageMeta): Promise<void> {
if (!validateImageKey(key)) {
throw new Error('Invalid image key')
}
if (bytes.byteLength > TELEGRAM_MAX_FILE_BYTES) {
throw new Error('文件超过 Telegram 存储上限(20MB)')
}
const filename = filenameFromKey(key)
const caption = key.length <= 1024 ? key : key.slice(0, 1021) + '...'
const message = await this.withChatIdMigrationRetry(async (chatId) => {
const { body, contentType: multipartType } = buildSendDocumentMultipart({
chatId,
caption,
filename,
bytes
})
return callTelegramApi<TelegramSentMessage>(
this.botToken,
'sendDocument',
{
method: 'POST',
headers: { 'Content-Type': multipartType },
body: body.buffer.slice(
body.byteOffset,
body.byteOffset + body.byteLength
) as ArrayBuffer
},
this.apiProxyUrl
)
})
const ref = fileRefFromSentMessage(message)
if (!ref) {
if (message.message_id != null) {
await this.deleteChatMessage(this.chatId, message.message_id).catch((error) => {
logException('telegram rollback message failed', error, {
messageId: message.message_id
})
})
}
logException(
'telegram sendDocument: message has no file id',
new Error('Telegram 未返回文件信息'),
{
messageId: message.message_id,
keys: Object.keys(message)
}
)
throw new Error('Telegram 未返回文件信息')
}
setStorageObjectRef(this.id, key, ref)
}
async head(key: string): Promise<StoredImage | null> {
if (!validateImageKey(key)) return null
const indexed = getImageIndexAsStored(key)
if (!indexed || indexed.backendId !== this.id) {
return null
}
const ref = getStorageObjectRef(this.id, key)
if (!ref) return null
return { ...indexed, backendId: this.id }
}
private async deleteChatMessage(chatId: string, messageId: number): Promise<void> {
await callTelegramApi<boolean>(
this.botToken,
'deleteMessage',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
message_id: messageId
})
},
this.apiProxyUrl
)
}
async delete(key: string): Promise<void> {
const ref = getStorageObjectRef(this.id, key)
deleteStorageObjectRef(this.id, key)
if (ref?.messageId == null) return
try {
await this.withChatIdMigrationRetry(chatId =>
this.deleteChatMessage(chatId, ref.messageId as number)
)
} catch (error) {
logException('telegram deleteMessage failed', error, { key, messageId: ref.messageId })
}
}
async createStream(
key: string,
range?: { start: number, end: number }
): Promise<Readable> {
const ref = getStorageObjectRef(this.id, key)
if (!ref?.fileId) {
throw new Error('Telegram 文件引用不存在')
}
const file = await callTelegramApi<TelegramFile>(
this.botToken,
'getFile',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ file_id: ref.fileId })
},
this.apiProxyUrl
)
if (!file.file_path) {
throw new Error('Telegram 文件路径不可用')
}
const downloadUrl = fileDownloadUrl(this.botToken, file.file_path)
const response = await telegramFetch(downloadUrl, { method: 'GET' }, this.apiProxyUrl)
if (!response.ok) {
throw new Error(`Telegram 文件下载失败(${response.status})`)
}
const buffer = Buffer.from(await response.arrayBuffer())
if (range) {
const slice = buffer.subarray(range.start, range.end + 1)
return Readable.from(slice)
}
return Readable.from(buffer)
}
async testConnection(): Promise<{ ok: boolean, message: string }> {
try {
await callTelegramApi<{ id: number, username?: string }>(
this.botToken,
'getMe',
{ method: 'GET' },
this.apiProxyUrl
)
await this.withChatIdMigrationRetry(chatId =>
callTelegramApi<{ id: number, title?: string }>(
this.botToken,
'getChat',
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ chat_id: chatId })
},
this.apiProxyUrl
)
)
return { ok: true, message: '连接成功' }
} catch (error) {
const message = error instanceof Error ? error.message : '连接失败'
return { ok: false, message }
}
}
async getUsageStats(): Promise<{ count: number, bytes: number }> {
return { count: 0, bytes: 0 }
}
}
+17 -2
View File
@@ -28,7 +28,7 @@ export interface FolderStorageStat {
bytes: number
}
export type StorageBackendType = 'local' | 's3'
export type StorageBackendType = 'local' | 's3' | 'telegram'
export type ServingMode = 'proxy' | 'public'
export interface S3BackendConfig {
@@ -44,6 +44,21 @@ export interface S3BackendSecrets {
secretAccessKey: string
}
export interface TelegramBackendConfig {
chatId: string
apiProxyUrl?: string
}
export interface TelegramBackendSecrets {
botToken: string
}
export interface TelegramObjectRef {
fileId: string
fileUniqueId?: string
messageId?: number
}
export interface StorageBackendRow {
id: string
name: string
@@ -62,7 +77,7 @@ export interface StorageBackendInfo {
id: string
name: string
type: StorageBackendType
config: S3BackendConfig | Record<string, never>
config: S3BackendConfig | TelegramBackendConfig | Record<string, never>
servingMode: ServingMode
publicUrl: string
quotaBytes: number | null
+3 -6
View File
@@ -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
View File
@@ -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) {
+24
View File
@@ -3,6 +3,8 @@ import {
type AllowedMimeType
} from './constants'
import { getSetting, setSetting } from './db'
import { getActiveBackendRow } from './storage/resolver'
import { TELEGRAM_MAX_FILE_BYTES } from './storage/telegram'
export const SETTINGS_UPLOAD_MAX_FILE_SIZE_MB = 'upload_max_file_size_mb'
export const SETTINGS_ALLOWED_MIME_TYPES = 'allowed_mime_types'
@@ -180,6 +182,15 @@ export function getMaxFileSizeBytes(): number {
return getUploadMaxFileSizeMb() * 1024 * 1024
}
export function getEffectiveMaxFileSizeBytes(): number {
const configured = getMaxFileSizeBytes()
const row = getActiveBackendRow()
if (row?.type === 'telegram') {
return Math.min(configured, TELEGRAM_MAX_FILE_BYTES)
}
return configured
}
export function getAllowedMimeTypesList(): AllowedMimeType[] {
const dbRaw = getSetting(SETTINGS_ALLOWED_MIME_TYPES)
if (dbRaw !== null) {
@@ -279,6 +290,19 @@ export function formatMaxFileSizeMessage(): string {
return `图片大小不能超过 ${getUploadMaxFileSizeMb()} MB`
}
export function formatEffectiveMaxFileSizeMessage(): string {
const row = getActiveBackendRow()
if (row?.type === 'telegram') {
const mb = TELEGRAM_MAX_FILE_BYTES / (1024 * 1024)
const siteMb = getUploadMaxFileSizeMb()
if (siteMb * 1024 * 1024 <= TELEGRAM_MAX_FILE_BYTES) {
return formatMaxFileSizeMessage()
}
return `图片大小不能超过 ${mb} MB(Telegram 存储上限)`
}
return formatMaxFileSizeMessage()
}
export function getUploadPolicySettingsPayload() {
return {
uploadMaxFileSizeMb: getUploadMaxFileSizeMb(),
+3 -1
View File
@@ -3,6 +3,8 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
include: ['server/**/*.test.ts']
include: ['server/**/*.test.ts'],
pool: 'forks',
setupFiles: ['./server/test/setup.ts']
}
})