5 Commits
Author SHA1 Message Date
O96u b05d572221 release: v1.2.8 — 双域名保存确认与 clear-domains 恢复
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
启用双域名时以确认框提示锁死风险与恢复方式,不再强制校验 Host。
新增 clear-domains 运维 CLI 与相关文档。
2026-09-04 14:46:37 +08:00
O96u 4789d19d06 docs: 补充 v1.2.7 登录验证(滑块 / Turnstile / Cap)文档 2026-09-03 13:57:20 +08:00
O96u 430c4de0f4 release: v1.2.7 — 登录人机验证(滑块 / Turnstile / Cap)
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
2026-09-03 13:53:43 +08:00
O96u 8408d01197 release: v1.2.6 — 新 UI 体验优化与存储标识规则
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
2026-09-01 21:31:02 +08:00
O96u ac65c1eb9d refactor: 重构设置、API、图库与存储页面前端结构。
将操作日志并入设置侧栏,补齐检查更新提示与版本接口刷新;拆分各模块组件并修复图库搜索分页变量。
2026-09-01 17:15:02 +08:00
118 changed files with 6775 additions and 2172 deletions

No files matched your search

+3
View File
@@ -35,3 +35,6 @@
# 仅本地开发:设为 true 可绕过登录验证(跳过 /setup,一般无需开启)
# DEV_BYPASS_ACCESS=false
# 登录人机验证(滑块 / Turnstile / Cap)在后台「设置 → 访问控制」配置,无环境变量。
# 配置错误无法登录时:docker exec pichost slider(或 npm run slider)恢复为本地滑块。
+39
View File
@@ -4,6 +4,45 @@
## [Unreleased]
## [1.2.8] - 2026-09-04
### 改进
- 双域名:保存或初始化时弹出风险确认(说明可能锁死及 `clear-domains` 恢复方式),不再强制校验当前 Host
### 新增
- 运维 CLI `clear-domains`:清除数据库中的网站域 / 图片域配置(`docker exec pichost clear-domains`)
### 文档
- FAQ、双域名、反向代理文档补充锁死原因与恢复步骤
## [1.2.7] - 2026-09-03
### 新增
- 登录/注册人机验证:本地滑块、Cloudflare Turnstile、Cap;管理员在「设置 → 访问控制」中切换
- 运维 CLI `slider`:将登录验证重置为本地滑块(`docker exec pichost slider`)
### 改进
- 登出后登录页验证码可正常重新加载
## [1.2.6] - 2026-09-01
### 新增
- 设置、API、图库、存储页 UI 重构(侧栏导航、统计卡片、在线调试等)
- 图库筛选增加存储后端下拉
- 新建对象存储后端按类型生成存储标识:`r2-*`、`cos-*`、`oss-*`、`s3-*`
### 改进
- 操作日志表格:操作/来源标签同行展示,路径列省略号截断、无横向滚动条
- 存储后端卡片:存储标识与类型同一行左对齐排列
- README 与文档站截图、导航说明同步新界面
## [1.2.5] - 2026-08-31
### 新增
+2
View File
@@ -25,6 +25,8 @@ ENV NODE_ENV=production \
COPY --from=build /app/.output ./.output
COPY server/cli/reset-password.mjs ./server/cli/reset-password.mjs
COPY server/cli/migrate-to-single-images.mjs ./server/cli/migrate-to-single-images.mjs
COPY server/cli/slider.mjs ./server/cli/slider.mjs
COPY server/cli/clear-domains.mjs ./server/cli/clear-domains.mjs
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
+7 -7
View File
@@ -31,20 +31,20 @@
**main** has no public demo. **cloudflare** branch live demo: [pic.roven.cc](https://pic.roven.cc)
| Home | Storage |
| API | Gallery |
| :--: | :-----: |
| ![Home](docs/screenshots/upload.png) | ![Storage](docs/screenshots/storage.png) |
| ![API](docs/screenshots/api.png) | ![Gallery](docs/screenshots/gallery.png) |
| Stats | Settings |
| :---: | :-------: |
| ![Stats](docs/screenshots/stats.png) | ![Settings](docs/screenshots/settings-en.png) |
| Storage | Settings |
| :-----: | :-------: |
| ![Storage](docs/screenshots/storage.png) | ![Settings](docs/screenshots/settings-en.png) |
## Features
- **Drag, click, or Ctrl+V paste** — server-side WebP, Referer hotlink protection
- **Multi-user** — login with slider captcha, optional registration; users see only their images
- **Multi-user** — login with slider, Turnstile, or Cap verification; optional registration; users see only their images
- **Multi-backend storage** — local disk + S3-compatible (R2 / COS / OSS / AWS); hybrid `proxy` / `public` URLs
- **Gallery & stats** — browse, search, batch delete; upload trends and source breakdown
- **Gallery** — browse, search, filter by storage/source, grid/list views, batch delete; stats overview and source breakdown
- **API & Twikoo** — global / per-user tokens; `POST /api/index.php` compatible
- **Zero-config Docker** — first-run web wizard, no secrets upfront
+6 -6
View File
@@ -31,20 +31,20 @@
**main** 分支暂无公网演示;**cloudflare** 分支在线体验:[pic.roven.cc](https://pic.roven.cc)
| 首页 | 存储 |
| API | 图库 |
| :--: | :--: |
| ![首页](docs/screenshots/upload.png) | ![存储](docs/screenshots/storage.png) |
| ![API](docs/screenshots/api.png) | ![图库](docs/screenshots/gallery.png) |
| 统计 | 设置 |
| 存储 | 设置 |
| :--: | :--: |
| ![统计](docs/screenshots/stats.png) | ![设置](docs/screenshots/settings.png) |
| ![存储](docs/screenshots/storage.png) | ![设置](docs/screenshots/settings.png) |
## 特性
- **拖拽 / 点击 / Ctrl+V 粘贴**上传;服务端 WebP 压缩、Referer 防盗链
- **多用户**:账号密码登录(滑动验证)、可选开放注册;普通用户仅见自己的图片
- **多用户**:账号密码登录(滑块 / Turnstile / Cap 人机验证)、可选开放注册;普通用户仅见自己的图片
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public`
- **图库与统计**:浏览、搜索、批量删除;上传趋势与来源分布
- **图库**:浏览、搜索、按存储/来源筛选、网格/列表切换、批量删除;统计概览与来源分布
- **API 与 Twikoo**:全局 / 个人 Token;`POST /api/index.php` 兼容
- **Docker 零配置**:首次访问 Web 引导创建管理员
+18
View File
@@ -106,3 +106,21 @@
.upload-settings-btn:hover .upload-settings-icon {
transform: rotate(90deg);
}
.api-debug-response {
scrollbar-width: thin;
scrollbar-color: rgb(82 82 82) transparent;
}
.api-debug-response::-webkit-scrollbar {
width: 6px;
}
.api-debug-response::-webkit-scrollbar-thumb {
border-radius: 9999px;
background-color: rgb(82 82 82);
}
.api-debug-response::-webkit-scrollbar-track {
background: transparent;
}
+34 -20
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png'
import type { LoginVerificationPayload } from '~/types/auth'
const router = useRouter()
const { login, fetchStatus, authStatus } = useAuth()
@@ -11,45 +12,53 @@ const username = ref('')
const password = ref('')
const secret = ref('')
const loading = ref(false)
const captchaRef = ref<{ reset: () => Promise<void> } | null>(null)
const captchaPayload = ref<{ captchaId: string, captchaPosition: number } | null>(null)
const verificationRef = ref<{ reset: () => Promise<void> } | null>(null)
const verificationPayload = ref<LoginVerificationPayload | null>(null)
const verificationMountKey = ref(0)
const legacyMode = computed(() => authStatus.value?.legacyMode ?? false)
const allowRegistration = computed(() => authStatus.value?.allowRegistration ?? false)
const loginVerification = computed(() =>
authStatus.value?.loginVerification ?? { method: 'slider' as const }
)
const canSubmit = computed(() =>
Boolean(captchaPayload.value)
Boolean(verificationPayload.value)
&& (legacyMode.value ? Boolean(secret.value) : Boolean(username.value && password.value))
)
function onCaptchaVerified(payload: { id: string, positionPercent: number }) {
captchaPayload.value = {
captchaId: payload.id,
captchaPosition: payload.positionPercent
}
function onVerificationVerified(payload: LoginVerificationPayload) {
verificationPayload.value = payload
}
async function resetCaptcha() {
captchaPayload.value = null
await captchaRef.value?.reset()
function onVerificationCleared() {
verificationPayload.value = null
}
async function resetVerification() {
verificationPayload.value = null
await verificationRef.value?.reset()
}
onMounted(async () => {
verificationPayload.value = null
verificationMountKey.value += 1
const status = await fetchStatus()
if (!status.initialized && !status.legacyMode) {
await router.replace('/setup')
return
}
})
async function submit() {
if (!canSubmit.value || loading.value || !captchaPayload.value) return
if (!canSubmit.value || loading.value || !verificationPayload.value) return
loading.value = true
try {
const captcha = captchaPayload.value
const verification = verificationPayload.value
const result = legacyMode.value
? await login({ secret: secret.value }, captcha)
: await login({ username: username.value.trim(), password: password.value }, captcha)
? await login({ secret: secret.value }, verification)
: await login({ username: username.value.trim(), password: password.value }, verification)
if (result.ok) {
if (result.needsMigration) {
@@ -59,10 +68,10 @@ async function submit() {
username.value = ''
password.value = ''
secret.value = ''
await resetCaptcha()
await resetVerification()
toast.add({ title: t('auth.loginSuccess'), color: 'success' })
} else {
await resetCaptcha()
await resetVerification()
toast.add({
title: result.error ?? (legacyMode.value ? t('auth.loginFailedSecret') : t('auth.loginFailedCredentials')),
color: 'error'
@@ -170,9 +179,14 @@ async function submit() {
</div>
</template>
<SliderCaptcha
ref="captchaRef"
@verified="onCaptchaVerified"
<LoginVerification
:key="verificationMountKey"
ref="verificationRef"
:method="loginVerification.method"
:turnstile-site-key="loginVerification.turnstileSiteKey"
:cap-api-endpoint="loginVerification.capApiEndpoint"
@verified="onVerificationVerified"
@cleared="onVerificationCleared"
/>
<UButton
+11 -3
View File
@@ -3,9 +3,11 @@ const props = withDefaults(
defineProps<{
code: string
scrollable?: boolean
lang?: string
}>(),
{
scrollable: true
scrollable: true,
lang: ''
}
)
@@ -34,6 +36,12 @@ async function copyCode() {
<span class="size-3 rounded-full border border-black/15 bg-[#ff5f56]" />
<span class="size-3 rounded-full border border-black/15 bg-[#ffbd2e]" />
<span class="size-3 rounded-full border border-black/15 bg-[#27c93f]" />
<span
v-if="lang"
class="ml-1 text-[10px] font-medium tracking-wide text-neutral-500 uppercase"
>
{{ lang }}
</span>
</div>
<UButton
icon="i-lucide-copy"
@@ -47,7 +55,7 @@ async function copyCode() {
</div>
<pre
class="overflow-auto p-4 text-xs leading-relaxed text-neutral-100"
:class="props.scrollable ? 'max-h-80' : ''"
><code class="font-mono">{{ props.code }}</code></pre>
:class="scrollable ? 'max-h-80' : ''"
><code class="font-mono whitespace-pre">{{ code }}</code></pre>
</div>
</template>
+2 -7
View File
@@ -17,17 +17,12 @@ const navItems = computed(() => {
]
if (isAdmin.value) {
items.push({ label: t('nav.storage'), to: '/storage', icon: 'i-lucide-hard-drive' })
items.push({ label: t('nav.settings'), to: '/settings', icon: 'i-lucide-settings' })
}
items.push({ label: t('nav.settings'), to: '/settings', icon: 'i-lucide-settings' })
return items
})
const accountMenuItems = computed<DropdownMenuItem[]>(() => [
{
label: t('nav.logs'),
icon: 'i-lucide-scroll-text',
to: '/logs'
},
{
label: t('nav.changePassword'),
icon: 'i-lucide-key-round',
@@ -48,7 +43,7 @@ const desktopUserMenuItems = computed<DropdownMenuItem[][]>(() => [
function isNavActive(to: string) {
if (to === '/settings') {
return route.path === '/settings'
return route.path.startsWith('/settings')
}
return route.path.startsWith(to)
}
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
import 'cap-widget'
const props = defineProps<{
apiEndpoint: string
}>()
const emit = defineEmits<{
verified: [payload: { capToken: string }]
cleared: []
}>()
const { t } = useI18n()
const widgetRef = ref<HTMLElement | null>(null)
function onSolve(event: Event) {
const token = (event as CustomEvent<{ token: string }>).detail?.token
if (token) {
emit('verified', { capToken: token })
}
}
function onError() {
emit('cleared')
}
function reset() {
const widget = widgetRef.value as (HTMLElement & { reset?: () => void }) | null
widget?.reset?.()
emit('cleared')
}
defineExpose({ reset })
</script>
<template>
<ClientOnly>
<cap-widget
ref="widgetRef"
:data-cap-api-endpoint="props.apiEndpoint"
:data-cap-i18n-initial-state="t('auth.capInitialState')"
:data-cap-i18n-verifying-label="t('auth.capVerifying')"
:data-cap-i18n-solved-label="t('auth.capSolved')"
:data-cap-i18n-error-label="t('auth.capError')"
@solve="onSolve"
@error="onError"
/>
</ClientOnly>
</template>
+4 -1
View File
@@ -6,6 +6,8 @@ const props = defineProps<{
icon?: string
block?: boolean
successTitle?: string
variant?: 'solid' | 'outline' | 'soft' | 'subtle' | 'ghost' | 'link'
color?: 'primary' | 'secondary' | 'success' | 'info' | 'warning' | 'error' | 'neutral'
}>()
const emit = defineEmits<{
@@ -76,7 +78,8 @@ async function copy() {
<template>
<UButton
size="xs"
variant="soft"
:variant="variant ?? 'soft'"
:color="color"
:loading="copying"
:disabled="!value"
:label="iconOnly ? undefined : label"
+153 -2
View File
@@ -9,20 +9,26 @@ const props = withDefaults(defineProps<{
showKey?: boolean
showStorage?: boolean
compact?: boolean
gallery?: boolean
allowDelete?: boolean
}>(), {
selectable: true,
showKey: true,
showStorage: false,
compact: false
compact: false,
gallery: false,
allowDelete: true
})
const emit = defineEmits<{
'update:selected': [value: boolean]
'preview': []
'delete': []
}>()
const { formatFileSize } = useFileSize()
const { t, locale } = useI18n()
const toast = useToast()
const { copyFormat } = useUploadPreferences()
const imageError = ref(false)
const retryCount = ref(0)
@@ -110,13 +116,158 @@ const storageIcon = computed(() =>
props.image.storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
)
const uploadSourceLabel = computed(() => {
switch (props.image.uploadSource) {
case 'web':
return t('stats.tagWeb')
case 'api':
return t('stats.tagApi')
default:
return null
}
})
function toggleSelected(value: boolean | 'indeterminate') {
emit('update:selected', value === true)
}
const copyingUrl = ref(false)
async function copyGalleryUrl() {
if (copyingUrl.value || !props.image.url) return
copyingUrl.value = true
try {
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(props.image.url)
} else {
const textarea = document.createElement('textarea')
textarea.value = props.image.url
textarea.setAttribute('readonly', '')
textarea.style.position = 'fixed'
textarea.style.left = '-9999px'
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
toast.add({ title: t('copy.copiedUrl'), color: 'success' })
} catch {
toast.add({ title: t('copy.failedManual'), color: 'error' })
} finally {
copyingUrl.value = false
}
}
</script>
<template>
<div class="flex flex-col overflow-hidden rounded-xl border border-default bg-elevated shadow-sm">
<div
v-if="gallery"
class="flex flex-col overflow-hidden rounded-xl border border-default bg-elevated"
>
<div class="relative aspect-[4/3] shrink-0 overflow-hidden bg-muted">
<img
v-if="!imageError"
:key="`${image.key}-${retryCount}`"
:src="previewSrc"
:alt="image.originalName"
loading="lazy"
class="size-full cursor-zoom-in object-cover object-center"
role="button"
tabindex="0"
:aria-label="t('image.openPreview')"
@click="emit('preview')"
@keydown.enter="emit('preview')"
@keydown.space.prevent="emit('preview')"
@error="onPreviewError"
>
<div
v-else
class="flex size-full items-center justify-center text-xs text-muted"
>
{{ t('image.previewFailed') }}
</div>
<div
v-if="selectable"
class="absolute top-2 left-2"
@click.stop
>
<UCheckbox
:model-value="selected"
:ui="{ base: 'shadow-none' }"
@update:model-value="toggleSelected"
/>
</div>
</div>
<div class="flex flex-col gap-1.5 p-3">
<p
class="truncate text-sm font-semibold"
:title="image.originalName"
>
{{ image.originalName }}
</p>
<p class="truncate text-xs text-muted">
{{ uploadedLabel }} · {{ formatFileSize(image.size) }}
</p>
<div
v-if="uploadSourceLabel || (showStorage && image.storage)"
class="flex flex-wrap gap-1.5"
>
<span
v-if="uploadSourceLabel"
class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary"
>
{{ uploadSourceLabel }}
</span>
<span
v-if="showStorage && image.storage"
class="inline-flex max-w-full items-center gap-1 rounded-md border border-default px-2 py-0.5 text-xs text-muted"
:title="image.storage.name"
>
<UIcon
:name="storageIcon"
class="size-3 shrink-0"
/>
<span class="truncate">{{ image.storage.name }}</span>
</span>
</div>
</div>
<div class="flex items-center justify-around border-t border-default px-2 py-2 text-muted">
<UButton
icon="i-lucide-link"
variant="ghost"
color="neutral"
size="sm"
:loading="copyingUrl"
:aria-label="t('common.copy')"
@click="copyGalleryUrl"
/>
<UButton
icon="i-lucide-eye"
variant="ghost"
color="neutral"
size="sm"
:aria-label="t('image.openPreview')"
@click="emit('preview')"
/>
<UButton
v-if="allowDelete"
icon="i-lucide-trash-2"
variant="ghost"
color="neutral"
size="sm"
:aria-label="t('common.delete')"
@click="emit('delete')"
/>
</div>
</div>
<div
v-else
class="flex flex-col overflow-hidden rounded-xl border border-default bg-elevated shadow-sm"
>
<div
class="relative aspect-square shrink-0 overflow-hidden bg-muted"
role="button"
+22 -3
View File
@@ -10,17 +10,33 @@ const props = withDefaults(defineProps<{
emptyText?: string
dense?: boolean
compact?: boolean
/** 图库:5 列 × 2 行,缩略图略扁 */
gallery?: boolean
allowDelete?: boolean
}>(), {
selectable: true,
showKey: true,
showStorage: false,
dense: false,
compact: false
compact: false,
gallery: false,
allowDelete: true
})
const gridClass = computed(() => {
if (props.gallery) {
return 'grid items-start grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5'
}
if (props.dense) {
return 'grid items-start grid-cols-2 gap-3 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
}
return 'grid items-start grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'
})
const emit = defineEmits<{
'update:selectedKeys': [value: Set<string>]
'preview': [image: ImageItem]
'delete': [image: ImageItem]
}>()
const { t } = useI18n()
@@ -38,8 +54,8 @@ function updateSelection(key: string, selected: boolean) {
<template>
<div
v-if="items.length"
class="grid items-start sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
:class="dense ? 'grid-cols-2 gap-3' : 'grid-cols-1 gap-4'"
class="items-start"
:class="gridClass"
>
<ImageCard
v-for="image in items"
@@ -50,8 +66,11 @@ function updateSelection(key: string, selected: boolean) {
:show-key="showKey"
:show-storage="showStorage"
:compact="compact"
:gallery="gallery"
:allow-delete="allowDelete"
@update:selected="updateSelection(image.key, $event)"
@preview="emit('preview', image)"
@delete="emit('delete', image)"
/>
</div>
<div
+274 -104
View File
@@ -1,15 +1,19 @@
<script setup lang="ts">
import type { ImageItem } from '~/types/image'
import type { CopyFormat } from '~/composables/useUploadPreferences'
import { formatImageDimensions, getFileExtension } from '~/utils/image-display'
import { formatImageDimensions } from '~/utils/image-display'
type EmbedFormat = CopyFormat | 'bbcode'
const props = withDefaults(defineProps<{
open: boolean
image: ImageItem | null
showStorage?: boolean
deleting?: boolean
allowDelete?: boolean
}>(), {
showStorage: false
showStorage: false,
allowDelete: true
})
const emit = defineEmits<{
@@ -17,6 +21,7 @@ const emit = defineEmits<{
'delete': []
}>()
const toast = useToast()
const { formatFileSize } = useFileSize()
const { t, locale } = useI18n()
const { copyFormat } = useUploadPreferences()
@@ -24,40 +29,67 @@ const { copyFormat } = useUploadPreferences()
const naturalWidth = ref<number | null>(null)
const naturalHeight = ref<number | null>(null)
const dimensionsLoaded = ref(false)
const copyingUrl = ref(false)
const embedFormat = ref<EmbedFormat>('url')
const copyFormatItems = computed(() => [
const embedFormatItems = computed(() => [
{ label: t('copy.url'), value: 'url' as const },
{ label: t('copy.markdown'), value: 'markdown' as const },
{ label: t('copy.html'), value: 'html' as const }
{ label: t('copy.html'), value: 'html' as const },
{ label: t('copy.bbcode'), value: 'bbcode' as const }
])
const uploadedLabel = computed(() => {
if (!props.image) return '—'
try {
return new Date(props.image.uploadedAt).toLocaleString(locale.value, { hour12: false })
const date = new Date(props.image.uploadedAt)
const y = date.getFullYear()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
const h = String(date.getHours()).padStart(2, '0')
const min = String(date.getMinutes()).padStart(2, '0')
const s = String(date.getSeconds()).padStart(2, '0')
return `${y}/${m}/${d} ${h}:${min}:${s}`
} catch {
return props.image.uploadedAt
}
})
const sizeLabel = computed(() => {
if (!props.image) return '—'
return t('image.previewSizeDetail', {
size: formatFileSize(props.image.size),
bytes: props.image.size.toLocaleString(locale.value)
})
})
const bbcodeValue = computed(() => {
if (!props.image) return ''
return `[img]${props.image.url}[/img]`
})
const previewValue = computed(() => {
if (!props.image) return ''
switch (copyFormat.value) {
switch (embedFormat.value) {
case 'markdown':
return props.image.markdown
case 'html':
return props.image.html
case 'bbcode':
return bbcodeValue.value
default:
return props.image.url
}
})
const copySuccessTitle = computed(() => {
switch (copyFormat.value) {
switch (embedFormat.value) {
case 'markdown':
return t('copy.copiedMarkdown')
case 'html':
return t('copy.copiedHtml')
case 'bbcode':
return t('copy.copiedBbcode')
default:
return t('copy.copiedUrl')
}
@@ -67,11 +99,15 @@ const storageIcon = computed(() =>
props.image?.storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
)
const uploadSourceLabel = computed(() => {
if (!props.image?.uploadSource) return t('image.uploadSourceUnknown')
return props.image.uploadSource === 'api'
? t('stats.sourceApi')
: t('stats.sourceWeb')
const uploadSourceTag = computed(() => {
switch (props.image?.uploadSource) {
case 'web':
return t('stats.tagWeb')
case 'api':
return t('stats.tagApi')
default:
return null
}
})
const dimensionsLabel = computed(() => {
@@ -80,45 +116,69 @@ const dimensionsLabel = computed(() => {
return dimensionsLoaded.value ? '—' : t('image.previewDimensionsUnknown')
})
const detailRows = computed(() => {
if (!props.image) return []
const image = props.image
const rows: Array<{ label: string, value: string, mono?: boolean, storage?: boolean }> = [
{ label: t('image.previewOriginalName'), value: image.originalName },
{ label: t('image.previewExtension'), value: getFileExtension(image.originalName) },
{ label: t('image.previewUploadedAt'), value: uploadedLabel.value },
{ label: t('image.previewSize'), value: formatFileSize(image.size) },
{ label: t('image.previewContentType'), value: image.contentType },
{ label: t('image.previewDimensions'), value: dimensionsLabel.value },
{ label: t('image.previewUploadSource'), value: uploadSourceLabel.value }
]
if (image.owner) {
rows.push({ label: t('image.previewOwner'), value: image.owner.username })
}
if (props.showStorage && image.storage) {
rows.push({ label: t('image.previewStorage'), value: image.storage.name, storage: true })
}
rows.push({ label: t('image.previewKey'), value: image.key, mono: true })
return rows
})
watch(() => props.image?.key, () => {
naturalWidth.value = null
naturalHeight.value = null
dimensionsLoaded.value = false
})
function close() {
emit('update:open', false)
watch(() => props.open, (open) => {
if (open) {
embedFormat.value = copyFormat.value
}
})
function selectEmbedFormat(value: EmbedFormat) {
embedFormat.value = value
if (value !== 'bbcode') {
copyFormat.value = value
}
}
function selectCopyFormat(value: CopyFormat) {
copyFormat.value = value
async function copyText(text: string, successTitle: string) {
if (!text) return false
try {
if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
toast.add({ title: successTitle, color: 'success' })
return true
}
} catch {
// fallback below
}
const textarea = document.createElement('textarea')
textarea.value = text
textarea.setAttribute('readonly', '')
textarea.style.position = 'fixed'
textarea.style.left = '-9999px'
document.body.appendChild(textarea)
textarea.select()
let ok = false
try {
ok = document.execCommand('copy')
} catch {
ok = false
} finally {
document.body.removeChild(textarea)
}
if (ok) {
toast.add({ title: successTitle, color: 'success' })
} else {
toast.add({ title: t('copy.failedManual'), color: 'error' })
}
return ok
}
async function copyLink() {
if (!props.image?.url || copyingUrl.value) return
copyingUrl.value = true
try {
await copyText(props.image.url, t('copy.copiedUrl'))
} finally {
copyingUrl.value = false
}
}
function openInNewTab() {
@@ -126,6 +186,15 @@ function openInNewTab() {
window.open(props.image.url, '_blank', 'noopener,noreferrer')
}
function downloadOriginal() {
if (!props.image?.url) return
const link = document.createElement('a')
link.href = props.image.url
link.download = props.image.originalName || 'image'
link.rel = 'noopener'
link.click()
}
function requestDelete() {
emit('delete')
}
@@ -142,6 +211,7 @@ function onImageLoad(event: Event) {
<UModal
:open="open && !!image"
:title="t('image.previewTitle')"
:description="t('image.previewSubtitle')"
:ui="{ content: 'max-w-5xl' }"
@update:open="emit('update:open', $event)"
>
@@ -149,65 +219,138 @@ function onImageLoad(event: Event) {
v-if="image"
#body
>
<div class="grid gap-5 md:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)] md:items-stretch">
<div class="flex min-h-[14rem] items-center justify-center overflow-hidden rounded-xl border border-default bg-muted/15 p-3 md:min-h-[22rem]">
<div class="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,1.15fr)] lg:items-start">
<div class="preview-checkerboard flex items-center justify-center overflow-hidden rounded-xl border border-default p-4">
<img
:src="image.url"
:alt="image.originalName"
class="max-h-[min(70vh,32rem)] w-full object-contain"
class="max-h-[min(60vh,24rem)] w-full object-contain"
@load="onImageLoad"
>
</div>
<div class="flex min-h-0 flex-col gap-4">
<dl class="grid gap-2.5 sm:grid-cols-2">
<div
v-for="row in detailRows"
:key="row.label"
class="min-w-0 rounded-lg border border-default/60 bg-muted/10 px-3 py-2"
:class="row.mono ? 'sm:col-span-2' : ''"
>
<dt class="text-xs text-muted">
{{ row.label }}
<div class="flex min-w-0 flex-col gap-5">
<dl class="divide-y divide-default text-sm">
<div class="flex gap-4 py-2.5 first:pt-0">
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewOriginalName') }}
</dt>
<dd
class="mt-0.5 break-all text-sm"
:class="row.mono ? 'font-mono text-xs text-dimmed' : 'font-medium'"
>
<span
v-if="row.storage && image.storage"
class="inline-flex items-center gap-1.5"
>
<dd class="min-w-0 flex-1 break-all font-medium">
{{ image.originalName }}
</dd>
</div>
<div class="flex gap-4 py-2.5">
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewUploadedAt') }}
</dt>
<dd class="min-w-0 flex-1">
{{ uploadedLabel }}
</dd>
</div>
<div class="flex gap-4 py-2.5">
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewSize') }}
</dt>
<dd class="min-w-0 flex-1">
{{ sizeLabel }}
</dd>
</div>
<div class="flex gap-4 py-2.5">
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewDimensions') }}
</dt>
<dd class="min-w-0 flex-1">
{{ dimensionsLabel }}
</dd>
</div>
<div class="flex gap-4 py-2.5">
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewContentType') }}
</dt>
<dd class="min-w-0 flex-1">
{{ image.contentType }}
</dd>
</div>
<div
v-if="showStorage && image.storage"
class="flex gap-4 py-2.5"
>
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewStorage') }}
</dt>
<dd class="min-w-0 flex-1">
<span class="inline-flex items-center gap-1.5">
<UIcon
:name="storageIcon"
class="size-3.5 shrink-0"
class="size-3.5 shrink-0 text-muted"
/>
{{ row.value }}
{{ image.storage.name }}
</span>
<template v-else>
{{ row.value }}
</template>
</dd>
</div>
<div
v-if="uploadSourceTag"
class="flex gap-4 py-2.5"
>
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewUploadSource') }}
</dt>
<dd class="min-w-0 flex-1">
<span class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
{{ uploadSourceTag }}
</span>
</dd>
</div>
<div
v-if="image.owner"
class="flex gap-4 py-2.5"
>
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewOwner') }}
</dt>
<dd class="min-w-0 flex-1">
{{ image.owner.username }}
</dd>
</div>
<div class="flex gap-4 py-2.5 last:pb-0">
<dt class="w-20 shrink-0 text-muted">
{{ t('image.previewKey') }}
</dt>
<dd class="flex min-w-0 flex-1 items-start gap-2">
<span class="min-w-0 flex-1 break-all font-mono text-xs text-dimmed">
{{ image.key }}
</span>
<CopyButton
icon="i-lucide-copy"
icon-only
variant="ghost"
color="neutral"
class="shrink-0"
:label="t('common.copy')"
:value="image.key"
:success-title="t('copy.copied')"
/>
</dd>
</div>
</dl>
<div class="mt-auto space-y-2 rounded-xl border border-default/70 bg-muted/10 p-3">
<p class="text-xs font-medium text-muted">
<div class="border-t border-default pt-4">
<p class="mb-2.5 text-sm font-medium">
{{ t('image.previewLinks') }}
</p>
<div class="flex gap-1 rounded-lg border border-default bg-default p-0.5">
<UButton
v-for="item in copyFormatItems"
v-for="item in embedFormatItems"
:key="item.value"
size="xs"
class="flex-1 justify-center"
:variant="copyFormat === item.value ? 'solid' : 'ghost'"
:color="copyFormat === item.value ? 'primary' : 'neutral'"
:variant="embedFormat === item.value ? 'solid' : 'ghost'"
:color="embedFormat === item.value ? 'primary' : 'neutral'"
:label="item.label"
@click="selectCopyFormat(item.value)"
@click="selectEmbedFormat(item.value)"
/>
</div>
<div class="flex items-center gap-1.5">
<div class="mt-2 flex items-center gap-2">
<UInput
:model-value="previewValue"
readonly
@@ -215,42 +358,69 @@ function onImageLoad(event: Event) {
class="min-w-0 flex-1 font-mono text-xs"
/>
<CopyButton
icon="i-lucide-copy"
:label="t('common.copy')"
:value="previewValue"
:success-title="copySuccessTitle"
/>
</div>
</div>
<div class="flex flex-wrap justify-end gap-2 border-t border-default pt-3">
<UButton
:label="t('image.previewOpen')"
icon="i-lucide-external-link"
color="neutral"
variant="outline"
size="sm"
@click="openInNewTab"
/>
<UButton
:label="t('common.delete')"
icon="i-lucide-trash-2"
color="error"
variant="outline"
size="sm"
:loading="deleting"
@click="requestDelete"
/>
<UButton
:label="t('image.previewClose')"
color="neutral"
variant="outline"
size="sm"
@click="close"
/>
</div>
</div>
</div>
</template>
<template
v-if="image"
#footer
>
<div class="flex w-full flex-wrap justify-end gap-1.5">
<UButton
:label="t('image.previewOpen')"
icon="i-lucide-external-link"
color="neutral"
variant="outline"
size="sm"
@click="openInNewTab"
/>
<UButton
:label="t('image.previewDownload')"
icon="i-lucide-download"
color="neutral"
variant="outline"
size="sm"
@click="downloadOriginal"
/>
<UButton
:label="t('image.previewCopyLink')"
icon="i-lucide-link"
color="primary"
size="sm"
:loading="copyingUrl"
@click="copyLink"
/>
<UButton
v-if="allowDelete"
:label="t('common.delete')"
icon="i-lucide-trash-2"
color="error"
variant="outline"
size="sm"
:loading="deleting"
@click="requestDelete"
/>
</div>
</template>
</UModal>
</template>
<style scoped>
.preview-checkerboard {
background-color: var(--ui-bg-muted);
background-image:
linear-gradient(45deg, color-mix(in oklab, var(--ui-border) 28%, transparent) 25%, transparent 25%),
linear-gradient(-45deg, color-mix(in oklab, var(--ui-border) 28%, transparent) 25%, transparent 25%),
linear-gradient(45deg, transparent 75%, color-mix(in oklab, var(--ui-border) 28%, transparent) 75%),
linear-gradient(-45deg, transparent 75%, color-mix(in oklab, var(--ui-border) 28%, transparent) 75%);
background-size: 14px 14px;
background-position: 0 0, 0 7px, 7px -7px, -7px 0;
}
</style>
+90
View File
@@ -0,0 +1,90 @@
<script setup lang="ts">
import type {
LoginVerificationMethod,
LoginVerificationPayload
} from '~/types/auth'
const props = defineProps<{
method: LoginVerificationMethod
turnstileSiteKey?: string
capApiEndpoint?: string
}>()
const emit = defineEmits<{
verified: [payload: LoginVerificationPayload]
cleared: []
}>()
const sliderRef = ref<{ reset: () => Promise<void> } | null>(null)
const turnstileRef = ref<{ reset: () => void } | null>(null)
const capRef = ref<{ reset: () => void } | null>(null)
function onSliderVerified(payload: { id: string, positionPercent: number }) {
emit('verified', {
method: 'slider',
captchaId: payload.id,
captchaPosition: payload.positionPercent
})
}
function onTurnstileVerified(payload: { turnstileToken: string }) {
emit('verified', {
method: 'turnstile',
turnstileToken: payload.turnstileToken
})
}
function onCapVerified(payload: { capToken: string }) {
emit('verified', {
method: 'cap',
capToken: payload.capToken
})
}
function onCleared() {
emit('cleared')
}
async function reset() {
emit('cleared')
if (props.method === 'slider') {
await sliderRef.value?.reset()
return
}
if (props.method === 'turnstile') {
turnstileRef.value?.reset()
return
}
capRef.value?.reset()
}
defineExpose({ reset })
</script>
<template>
<SliderCaptcha
v-if="method === 'slider'"
ref="sliderRef"
@verified="onSliderVerified"
/>
<TurnstileCaptcha
v-else-if="method === 'turnstile' && turnstileSiteKey"
ref="turnstileRef"
:site-key="turnstileSiteKey"
@verified="onTurnstileVerified"
@cleared="onCleared"
/>
<CapCaptcha
v-else-if="method === 'cap' && capApiEndpoint"
ref="capRef"
:api-endpoint="capApiEndpoint"
@verified="onCapVerified"
@cleared="onCleared"
/>
<p
v-else
class="rounded-lg border border-warning/25 bg-warning/5 px-3 py-2 text-xs text-warning"
>
{{ $t('auth.verificationMisconfigured') }}
</p>
</template>
-18
View File
@@ -136,24 +136,6 @@ function toggleOpen() {
{{ t('nav.account') }}
</h3>
<div class="space-y-2">
<NuxtLink
to="/logs"
class="flex items-center justify-between rounded-lg border border-default px-3.5 py-2.5 text-sm text-highlighted transition-colors hover:bg-elevated"
@click="open = false"
>
<span class="flex items-center gap-2.5">
<UIcon
name="i-lucide-scroll-text"
class="size-4 opacity-70"
/>
{{ t('nav.logs') }}
</span>
<UIcon
name="i-lucide-chevron-right"
class="size-4 text-muted"
/>
</NuxtLink>
<NuxtLink
to="/account/password"
class="flex items-center justify-between rounded-lg border border-default px-3.5 py-2.5 text-sm text-highlighted transition-colors hover:bg-elevated"
+217 -91
View File
@@ -1,124 +1,250 @@
<script setup lang="ts">
const props = defineProps<{
type PageItem = number | 'ellipsis'
const props = withDefaults(defineProps<{
page: number
totalPages: number
total: number
unit?: string
loading?: boolean
}>()
pageSize?: number
pageSizeOptions?: number[]
}>(), {
loading: false,
pageSizeOptions: () => [10, 20, 30, 50]
})
const emit = defineEmits<{
'update:page': [page: number]
'update:pageSize': [pageSize: number]
}>()
const { t } = useI18n()
const unitLabel = computed(() => props.unit ?? t('common.itemsUnit'))
const jumpInput = ref('')
const jumpPageInput = ref('')
const showMobilePageNumbers = computed(() => props.totalPages <= 5)
const visiblePages = computed<PageItem[]>(() => {
const total = Math.max(1, props.totalPages)
const current = Math.min(Math.max(1, props.page), total)
if (total <= 7) {
return Array.from({ length: total }, (_, index) => index + 1)
}
const pages = new Set<number>([1, total])
for (let page = current - 1; page <= current + 1; page++) {
if (page >= 1 && page <= total) pages.add(page)
}
const sorted = [...pages].sort((a, b) => a - b)
const items: PageItem[] = []
for (let index = 0; index < sorted.length; index++) {
const page = sorted[index]!
const prev = sorted[index - 1]
if (prev !== undefined && page - prev > 1) {
items.push('ellipsis')
}
items.push(page)
}
return items
})
const pageSizeItems = computed(() =>
props.pageSizeOptions.map(size => ({
label: t('pagination.perPage', { size }),
value: size
}))
)
watch(
() => props.page,
(page) => {
jumpPageInput.value = String(page)
},
{ immediate: true }
)
function goTo(target: number) {
if (target < 1 || target > props.totalPages || props.loading) {
return
}
if (target === props.page) {
jumpInput.value = ''
return
}
if (target < 1 || target > props.totalPages || props.loading) return
if (target === props.page) return
emit('update:page', target)
}
function submitJump() {
const raw = String(jumpInput.value ?? '').trim()
if (!raw) return
const parsed = Number.parseInt(raw, 10)
if (!Number.isFinite(parsed)) return
goTo(parsed)
function onPageSizeChange(value: unknown) {
const size = Number(value)
if (!Number.isFinite(size) || size <= 0 || size === props.pageSize) return
emit('update:pageSize', size)
}
watch(() => props.page, () => {
jumpInput.value = ''
})
function jumpToPage() {
const target = Number.parseInt(jumpPageInput.value, 10)
if (!Number.isFinite(target)) return
goTo(target)
}
function pageButtonClass(target: number) {
return target === props.page
? 'border-primary bg-primary/10 text-primary font-medium'
: 'border-default bg-elevated text-default hover:bg-muted'
}
const navButtonClass = 'inline-flex items-center justify-center rounded-md border border-default bg-elevated text-default transition-colors hover:bg-muted disabled:pointer-events-none disabled:opacity-40'
</script>
<template>
<div
v-if="total > 0"
class="flex flex-col items-center gap-2 border-t border-default pt-4 sm:flex-row sm:justify-between"
class="border-t border-default pt-4"
>
<p
v-if="totalPages > 1"
class="text-sm text-muted"
>
{{ t('pagination.pageOf', { page, totalPages, total, unit: unitLabel }) }}
</p>
<p
v-else
class="text-sm text-muted"
>
{{ t('pagination.totalOnly', { total, unit: unitLabel }) }}
</p>
<div
v-if="totalPages > 1"
class="flex flex-wrap items-center justify-center gap-1"
>
<UButton
icon="i-lucide-chevrons-left"
variant="outline"
size="sm"
:aria-label="t('pagination.first')"
:disabled="page <= 1 || loading"
@click="goTo(1)"
/>
<UButton
icon="i-lucide-chevron-left"
variant="outline"
size="sm"
:aria-label="t('pagination.prev')"
:disabled="page <= 1 || loading"
@click="goTo(page - 1)"
/>
<UButton
icon="i-lucide-chevron-right"
variant="outline"
size="sm"
:aria-label="t('pagination.next')"
:disabled="page >= totalPages || loading"
@click="goTo(page + 1)"
/>
<UButton
icon="i-lucide-chevrons-right"
variant="outline"
size="sm"
:aria-label="t('pagination.last')"
:disabled="page >= totalPages || loading"
@click="goTo(totalPages)"
/>
<form
class="ml-1 flex items-center gap-1"
@submit.prevent="submitJump"
>
<UInput
v-model="jumpInput"
type="number"
:min="1"
:max="totalPages"
<div class="flex flex-col gap-3">
<div class="flex items-center justify-between gap-2 sm:hidden">
<p class="text-sm text-muted">
{{ t('pagination.totalCount', { total, unit: unitLabel }) }}
</p>
<USelect
v-if="pageSize !== undefined"
:model-value="pageSize"
:items="pageSizeItems"
value-key="value"
size="sm"
class="w-16"
:placeholder="t('pagination.pagePlaceholder')"
class="w-[6.5rem] shrink-0"
:aria-label="t('pagination.pageSize')"
:disabled="loading"
:aria-label="t('pagination.pagePlaceholder')"
@keyup.enter="submitJump"
@update:model-value="onPageSizeChange"
/>
<UButton
type="button"
size="sm"
variant="outline"
:label="t('pagination.goTo')"
:disabled="loading || !String(jumpInput ?? '').trim()"
@click="submitJump"
/>
</form>
</div>
<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<p class="hidden text-sm text-muted sm:block">
{{ t('pagination.totalCount', { total, unit: unitLabel }) }}
</p>
<div class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-end sm:gap-3">
<USelect
v-if="pageSize !== undefined"
:model-value="pageSize"
:items="pageSizeItems"
value-key="value"
size="sm"
class="hidden w-[7.5rem] shrink-0 sm:block"
:aria-label="t('pagination.pageSize')"
:disabled="loading"
@update:model-value="onPageSizeChange"
/>
<div class="flex items-center justify-center gap-1 sm:justify-end">
<button
type="button"
:class="[navButtonClass, 'hidden size-8 sm:inline-flex']"
:aria-label="t('pagination.first')"
:disabled="page <= 1 || loading"
@click="goTo(1)"
>
<UIcon
name="i-lucide-chevrons-left"
class="size-4"
/>
</button>
<button
type="button"
:class="[navButtonClass, 'size-9 sm:size-8']"
:aria-label="t('pagination.prev')"
:disabled="page <= 1 || loading"
@click="goTo(page - 1)"
>
<UIcon
name="i-lucide-chevron-left"
class="size-4"
/>
</button>
<p
v-if="!showMobilePageNumbers"
class="min-w-[5.5rem] px-1 text-center text-sm text-muted sm:hidden"
>
{{ t('pagination.pageStatus', { page, totalPages }) }}
</p>
<template
v-for="(target, index) in visiblePages"
:key="`${target}-${index}`"
>
<span
v-if="target === 'ellipsis'"
class="inline-flex size-9 items-center justify-center text-sm text-muted sm:size-8"
:class="showMobilePageNumbers ? '' : 'hidden sm:inline-flex'"
aria-hidden="true"
>
…
</span>
<button
v-else
type="button"
class="inline-flex items-center justify-center rounded-md border text-sm transition-colors disabled:pointer-events-none disabled:opacity-40"
:class="[
pageButtonClass(target),
showMobilePageNumbers ? 'size-9 sm:size-8' : 'hidden size-8 sm:inline-flex'
]"
:aria-label="t('pagination.pageNumber', { page: target })"
:aria-current="target === page ? 'page' : undefined"
:disabled="loading"
@click="goTo(target)"
>
{{ target }}
</button>
</template>
<button
type="button"
:class="[navButtonClass, 'size-9 sm:size-8']"
:aria-label="t('pagination.next')"
:disabled="page >= totalPages || loading"
@click="goTo(page + 1)"
>
<UIcon
name="i-lucide-chevron-right"
class="size-4"
/>
</button>
<button
type="button"
:class="[navButtonClass, 'hidden size-8 sm:inline-flex']"
:aria-label="t('pagination.last')"
:disabled="page >= totalPages || loading"
@click="goTo(totalPages)"
>
<UIcon
name="i-lucide-chevrons-right"
class="size-4"
/>
</button>
</div>
<form
class="hidden items-center gap-1.5 text-sm text-muted sm:flex"
@submit.prevent="jumpToPage"
>
<span>{{ t('pagination.goToPrefix') }}</span>
<UInput
v-model="jumpPageInput"
type="number"
min="1"
:max="totalPages"
size="sm"
class="w-14"
:aria-label="t('pagination.pagePlaceholder')"
:disabled="loading"
@blur="jumpToPage"
/>
<span v-if="t('pagination.goToSuffix')">{{ t('pagination.goToSuffix') }}</span>
</form>
</div>
</div>
</div>
</div>
</template>
+120
View File
@@ -0,0 +1,120 @@
<script setup lang="ts">
const props = defineProps<{
siteKey: string
}>()
const emit = defineEmits<{
verified: [payload: { turnstileToken: string }]
cleared: []
}>()
interface TurnstileRenderOptions {
'sitekey': string
'action'?: string
'callback'?: (token: string) => void
'expired-callback'?: () => void
'error-callback'?: () => void
}
interface TurnstileApi {
render: (container: HTMLElement, options: TurnstileRenderOptions) => string
reset: (widgetId?: string) => void
remove: (widgetId: string) => void
}
declare global {
interface Window {
turnstile?: TurnstileApi
onTurnstileLoad?: () => void
}
}
const containerRef = ref<HTMLElement | null>(null)
const widgetId = ref<string | null>(null)
const scriptLoaded = ref(false)
function onVerified(token: string) {
if (token) {
emit('verified', { turnstileToken: token })
}
}
function onCleared() {
emit('cleared')
}
function renderWidget() {
if (!containerRef.value || !window.turnstile || !props.siteKey) return
if (widgetId.value) {
window.turnstile.remove(widgetId.value)
widgetId.value = null
}
widgetId.value = window.turnstile.render(containerRef.value, {
'sitekey': props.siteKey,
'action': 'login',
'callback': onVerified,
'expired-callback': onCleared,
'error-callback': onCleared
})
}
function tryRenderWidget() {
if (scriptLoaded.value) {
renderWidget()
}
}
function loadScript() {
if (window.turnstile) {
scriptLoaded.value = true
tryRenderWidget()
return
}
window.onTurnstileLoad = () => {
scriptLoaded.value = true
tryRenderWidget()
}
const existing = document.querySelector('script[data-turnstile]')
if (existing) {
if (window.turnstile) {
scriptLoaded.value = true
tryRenderWidget()
}
return
}
const script = document.createElement('script')
script.src = 'https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit&onload=onTurnstileLoad'
script.async = true
script.defer = true
script.dataset.turnstile = 'true'
document.head.appendChild(script)
}
function reset() {
if (window.turnstile && widgetId.value) {
window.turnstile.reset(widgetId.value)
}
onCleared()
}
onMounted(async () => {
loadScript()
await nextTick()
tryRenderWidget()
})
watch([containerRef, () => props.siteKey, scriptLoaded], () => {
tryRenderWidget()
}, { flush: 'post' })
defineExpose({ reset })
</script>
<template>
<ClientOnly>
<div
ref="containerRef"
class="flex min-h-16 items-center justify-center"
/>
</ClientOnly>
</template>
+6 -36
View File
@@ -1,13 +1,4 @@
<script setup lang="ts">
withDefaults(
defineProps<{
embedded?: boolean
}>(),
{
embedded: false
}
)
const emit = defineEmits<{
back: []
}>()
@@ -57,17 +48,8 @@ onMounted(() => {
</script>
<template>
<div
class="flex flex-col overflow-hidden max-sm:overflow-visible"
:class="
embedded
? ''
: 'upload-card-surface upload-card-surface--panel max-sm:min-h-0 sm:h-full'
"
>
<div
class="flex items-start justify-between gap-3 border-b border-default px-5 py-4 sm:px-6"
>
<div class="upload-card-surface upload-card-surface--panel flex max-sm:min-h-0 flex-col overflow-hidden max-sm:overflow-visible sm:h-full">
<div class="flex items-start justify-between gap-3 border-b border-default px-5 py-4 sm:px-6">
<div class="flex min-w-0 items-start gap-2">
<UIcon
name="i-lucide-settings-2"
@@ -83,7 +65,6 @@ onMounted(() => {
</div>
</div>
<UButton
v-if="!embedded"
:label="t('common.back')"
icon="i-lucide-arrow-left"
variant="ghost"
@@ -95,10 +76,7 @@ onMounted(() => {
/>
</div>
<div
class="p-5 sm:p-6"
:class="embedded ? '' : 'flex flex-1 flex-col justify-center'"
>
<div class="flex flex-1 flex-col justify-center p-5 sm:p-6">
<div class="grid gap-5 sm:grid-cols-3 sm:gap-6">
<div class="space-y-4">
<h3 class="text-sm font-semibold">
@@ -128,9 +106,7 @@ onMounted(() => {
class="mt-0.5"
/>
<span class="min-w-0 flex-1">
<span
class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm"
>
<span class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm">
<span>{{ t('preferences.autoDeletePrefix') }}</span>
<UInput
v-model.number="userAutoDeleteDaysDraft"
@@ -139,11 +115,7 @@ onMounted(() => {
max="3650"
size="xs"
class="w-14 tabular-nums"
:class="
userAutoDeleteEnabled
? ''
: 'pointer-events-none opacity-40'
"
:class="userAutoDeleteEnabled ? '' : 'pointer-events-none opacity-40'"
/>
<span>{{ t('preferences.autoDeleteSuffix') }}</span>
</span>
@@ -171,9 +143,7 @@ onMounted(() => {
<p class="text-xs leading-relaxed text-muted">
{{ t('preferences.webpQualityHint') }}
</p>
<div
class="flex items-center justify-between gap-2 text-sm text-muted"
>
<div class="flex items-center justify-between gap-2 text-sm text-muted">
<span>{{ t('preferences.current', { n: clientWebpQuality }) }}</span>
<span>{{ clientQualityLevel }}</span>
</div>
+379
View File
@@ -0,0 +1,379 @@
<script setup lang="ts">
import type { ApiDocEndpoint, ApiDocParam } from '~/composables/useApiDocs'
const props = defineProps<{
endpoint: ApiDocEndpoint
token: string
}>()
const { t } = useI18n()
const toast = useToast()
const authToken = ref('')
const paramValues = ref<Record<string, string>>({})
const fileValues = ref<Record<string, File | null>>({})
const fileInputRefs = ref<Record<string, HTMLInputElement | null>>({})
const sending = ref(false)
const responseStatus = ref<number | null>(null)
const responseBody = ref('')
const responseError = ref(false)
function isDebugParam(param: ApiDocParam) {
if (param.name === 'token' && props.endpoint.requiresAuth) {
return false
}
return true
}
const debugQueryParams = computed(() =>
props.endpoint.params.filter(p => p.location === 'query' && isDebugParam(p))
)
const debugBodyParams = computed(() =>
props.endpoint.params.filter(p =>
(p.location === 'form-data' || p.location === 'body') && isDebugParam(p)
)
)
const showAuthHeader = computed(() => props.endpoint.requiresAuth)
watch(
() => props.endpoint.id,
() => {
resetForm()
},
{ immediate: true }
)
watch(
() => props.token,
(value) => {
if (value) {
authToken.value = value
if (!props.endpoint.requiresAuth && 'token' in paramValues.value) {
paramValues.value.token = value
}
}
},
{ immediate: true }
)
function resetForm() {
const values: Record<string, string> = {}
const files: Record<string, File | null> = {}
for (const param of props.endpoint.params) {
if (!isDebugParam(param)) continue
if (param.type === 'file') {
files[param.name] = null
} else if (param.name === 'keys') {
values[param.name] = '["images/2026/08/example.webp"]'
} else if (param.name === 'token' && props.token) {
values[param.name] = props.token
} else {
values[param.name] = ''
}
}
paramValues.value = values
fileValues.value = files
responseStatus.value = null
responseBody.value = ''
responseError.value = false
}
function fileLabel(name: string) {
return fileValues.value[name]?.name ?? t('api.debug.noFileSelected')
}
function triggerFilePick(name: string) {
fileInputRefs.value[name]?.click()
}
function onFileChange(name: string, event: Event) {
const input = event.target as HTMLInputElement
fileValues.value[name] = input.files?.[0] ?? null
}
function isParamFilled(param: ApiDocParam) {
if (param.type === 'file') {
return fileValues.value[param.name] != null
}
const value = paramValues.value[param.name]?.trim() ?? ''
if (!value) return false
if (param.location === 'body' && param.name === 'keys') {
try {
const parsed = JSON.parse(value) as { keys?: unknown }
return Array.isArray(parsed.keys) && parsed.keys.length > 0
} catch {
return false
}
}
return true
}
const canSendRequest = computed(() => {
if (sending.value) return false
if (showAuthHeader.value && !authToken.value.trim()) return false
const params = [...debugQueryParams.value, ...debugBodyParams.value]
return params.every(param => !param.required || isParamFilled(param))
})
function buildUrl() {
const url = new URL(props.endpoint.path, window.location.origin)
for (const param of debugQueryParams.value) {
const value = paramValues.value[param.name]?.trim()
if (value) {
url.searchParams.set(param.name, value)
}
}
return url.toString()
}
async function sendRequest() {
if (!canSendRequest.value) return
sending.value = true
responseStatus.value = null
responseBody.value = ''
responseError.value = false
try {
const headers: Record<string, string> = {}
if (showAuthHeader.value && authToken.value.trim()) {
headers['Auth-Token'] = authToken.value.trim()
}
let body: BodyInit | undefined
if (debugBodyParams.value.some(p => p.location === 'form-data')) {
const formData = new FormData()
for (const param of debugBodyParams.value) {
if (param.location !== 'form-data') continue
if (param.type === 'file') {
const file = fileValues.value[param.name]
if (file) formData.append(param.name, file)
} else {
const value = paramValues.value[param.name]?.trim()
if (value) formData.append(param.name, value)
}
}
body = formData
} else if (debugBodyParams.value.some(p => p.location === 'body')) {
headers['Content-Type'] = 'application/json'
try {
body = JSON.stringify(JSON.parse(paramValues.value.keys || '{}'))
} catch {
toast.add({ title: t('api.debug.invalidJson'), color: 'error' })
sending.value = false
return
}
}
const response = await fetch(buildUrl(), {
method: props.endpoint.method,
headers,
body,
credentials: 'include'
})
responseStatus.value = response.status
const text = await response.text()
try {
responseBody.value = JSON.stringify(JSON.parse(text), null, 2)
} catch {
responseBody.value = text
}
responseError.value = !response.ok
} catch {
responseError.value = true
responseBody.value = t('api.debug.networkError')
toast.add({ title: t('api.debug.sendFailed'), color: 'error' })
} finally {
sending.value = false
}
}
const responseScrollable = computed(() => responseBody.value.split('\n').length > 14)
</script>
<template>
<aside class="flex w-full shrink-0 flex-col border-t border-default bg-default lg:w-72 lg:border-t-0 lg:border-l xl:w-80">
<div class="flex items-start gap-2 border-b border-default px-5 py-4 sm:px-6">
<UIcon
name="i-lucide-flask-conical"
class="mt-0.5 size-5 shrink-0 text-primary"
/>
<div class="min-w-0">
<h3 class="text-base font-semibold">
{{ t('api.debug.title') }}
</h3>
<div class="mt-1.5 flex flex-wrap items-center gap-2">
<ApiMethodBadge
:method="endpoint.method"
size="sm"
/>
<code class="truncate font-mono text-xs text-muted">
{{ endpoint.path }}
</code>
</div>
</div>
</div>
<div class="flex flex-1 flex-col">
<div class="space-y-3 p-5 sm:p-6">
<section
v-if="showAuthHeader"
class="rounded-xl border border-default p-3 sm:p-4"
>
<h4 class="mb-3 text-xs font-semibold text-highlighted">
{{ t('api.debug.headers') }}
</h4>
<div class="space-y-1.5">
<label class="text-xs text-muted">
Auth-Token
<span class="text-error">*</span>
</label>
<UInput
v-model="authToken"
size="sm"
class="font-mono text-xs"
:placeholder="t('api.debug.tokenPlaceholder')"
/>
</div>
</section>
<section
v-if="debugQueryParams.length"
class="rounded-xl border border-default p-3 sm:p-4"
>
<h4 class="mb-3 text-xs font-semibold text-highlighted">
{{ t('api.debug.query') }}
</h4>
<div class="space-y-3">
<div
v-for="param in debugQueryParams"
:key="param.name"
class="space-y-1.5"
>
<label class="text-xs text-muted">
{{ param.name }}
<span
v-if="param.required"
class="text-error"
>*</span>
</label>
<UInput
v-model="paramValues[param.name]"
size="sm"
class="font-mono text-xs"
/>
</div>
</div>
</section>
<section
v-if="debugBodyParams.length"
class="rounded-xl border border-default p-3 sm:p-4"
>
<h4 class="mb-3 text-xs font-semibold text-highlighted">
{{ t('api.debug.body') }}
</h4>
<div class="space-y-3">
<div
v-for="param in debugBodyParams"
:key="param.name"
class="space-y-1.5"
>
<label class="text-xs text-muted">
{{ param.name }}
<span
v-if="param.required"
class="text-error"
>*</span>
</label>
<div
v-if="param.type === 'file'"
class="flex items-center gap-2"
>
<input
:ref="(el) => { fileInputRefs[param.name] = el as HTMLInputElement }"
type="file"
accept="image/*"
class="hidden"
@change="onFileChange(param.name, $event)"
>
<UButton
size="xs"
variant="outline"
color="neutral"
:label="t('api.debug.selectFile')"
@click="triggerFilePick(param.name)"
/>
<span class="min-w-0 truncate text-xs text-muted">
{{ fileLabel(param.name) }}
</span>
</div>
<UTextarea
v-else-if="param.location === 'body'"
v-model="paramValues[param.name]"
:rows="3"
size="sm"
class="font-mono text-xs"
/>
<UInput
v-else
v-model="paramValues[param.name]"
size="sm"
class="font-mono text-xs"
/>
</div>
</div>
</section>
<UButton
icon="i-lucide-send"
:label="t('api.debug.send')"
color="primary"
block
:loading="sending"
:disabled="!canSendRequest"
@click="sendRequest"
/>
<section
v-if="responseStatus !== null || responseBody"
class="overflow-hidden rounded-xl border border-default"
>
<div class="flex items-center justify-between border-b border-default px-3 py-2">
<span class="text-xs font-semibold text-highlighted">
{{ t('api.debug.response') }}
</span>
<UBadge
v-if="responseStatus !== null"
:color="responseError ? 'error' : 'success'"
variant="subtle"
size="xs"
>
{{ responseStatus }}
</UBadge>
</div>
<pre
class="api-debug-response bg-neutral-950 p-3 text-xs leading-relaxed text-neutral-100"
:class="responseScrollable ? 'max-h-64 overflow-y-auto' : ''"
><code class="font-mono whitespace-pre">{{ responseBody }}</code></pre>
</section>
</div>
<div class="mt-auto border-t border-default p-5 sm:p-6">
<h4 class="mb-2 text-xs font-semibold">
{{ t('api.debug.notesTitle') }}
</h4>
<ul class="space-y-1 text-xs leading-relaxed text-muted">
<li>{{ t('api.debug.noteSuccess') }}</li>
<li>{{ t('api.debug.noteError') }}</li>
<li>{{ t('api.debug.noteLimit') }}</li>
</ul>
</div>
</div>
</aside>
</template>
+121
View File
@@ -0,0 +1,121 @@
<script setup lang="ts">
import type { ApiDocEndpoint } from '~/composables/useApiDocs'
defineProps<{
endpoint: ApiDocEndpoint
}>()
const { t } = useI18n()
</script>
<template>
<section class="p-5 sm:p-6">
<h2 class="text-base font-semibold">
{{ t(endpoint.titleKey) }}
</h2>
<div class="mt-2 flex flex-wrap items-center gap-2">
<ApiMethodBadge
:method="endpoint.method"
size="sm"
/>
<code class="rounded-md border border-primary/20 bg-primary/10 px-2 py-0.5 font-mono text-sm font-medium text-primary">
{{ endpoint.path }}
</code>
</div>
<p class="mt-3 text-sm leading-relaxed text-muted">
{{ t(endpoint.descKey) }}
</p>
<div
v-if="endpoint.params.length"
class="mt-5 overflow-hidden rounded-xl border border-default"
>
<div class="border-b border-default bg-muted/20 px-4 py-2.5">
<h3 class="text-sm font-medium">
{{ t('api.requestParams') }}
</h3>
</div>
<div class="overflow-x-auto">
<table class="w-full min-w-[32rem] text-left text-sm">
<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">
{{ t('api.paramType') }}
</th>
<th class="px-4 py-2.5 font-medium">
{{ t('api.paramLocation') }}
</th>
<th class="px-4 py-2.5 font-medium">
{{ t('api.paramRequired') }}
</th>
<th class="px-4 py-2.5 font-medium">
{{ t('api.paramDescription') }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="param in endpoint.params"
:key="param.name"
class="border-b border-default last:border-b-0"
>
<td class="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">
{{ param.type }}
</td>
<td class="px-4 py-2.5 text-muted">
{{ param.location }}
</td>
<td class="px-4 py-2.5">
<UBadge
:color="param.required ? 'primary' : 'neutral'"
variant="subtle"
size="xs"
>
{{ param.required ? t('api.required') : t('api.optional') }}
</UBadge>
</td>
<td class="px-4 py-2.5 text-muted">
{{ t(param.descriptionKey) }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="mt-5 space-y-4">
<div>
<p class="mb-2 text-xs font-medium text-muted">
{{ t('api.requestExample') }}
</p>
<ApiCurlBlock
:code="endpoint.curl"
lang="cURL"
/>
</div>
<div>
<p class="mb-2 text-xs font-medium text-muted">
{{ t('api.responseExample') }}
<span class="font-normal">200 OK</span>
</p>
<ApiCurlBlock
:code="endpoint.responseExample"
lang="JSON"
:scrollable="false"
/>
</div>
</div>
</section>
</template>
+34
View File
@@ -0,0 +1,34 @@
<script setup lang="ts">
import type { ApiDocMethod } from '~/composables/useApiDocs'
const props = defineProps<{
method: ApiDocMethod
size?: 'xs' | 'sm'
}>()
const colorClass = computed(() => {
switch (props.method) {
case 'GET':
return 'bg-sky-500/15 text-sky-700 dark:text-sky-300'
case 'POST':
return 'bg-primary/15 text-primary'
case 'DELETE':
return 'bg-red-500/15 text-red-700 dark:text-red-300'
default:
return 'bg-muted text-muted'
}
})
const sizeClass = computed(() =>
props.size === 'sm' ? 'px-2 py-0.5 text-xs' : 'px-1.5 py-0.5 text-[10px]'
)
</script>
<template>
<span
class="inline-flex shrink-0 rounded font-mono font-semibold leading-none"
:class="[colorClass, sizeClass]"
>
{{ method }}
</span>
</template>
+148
View File
@@ -0,0 +1,148 @@
<script setup lang="ts">
import type { ApiDocCategory, ApiDocEndpoint } from '~/composables/useApiDocs'
const props = defineProps<{
endpoints: ApiDocEndpoint[]
activeId: string
}>()
const emit = defineEmits<{
select: [id: string]
}>()
const { t, locale } = useI18n()
const search = ref('')
const docsUrl = computed(() =>
locale.value === 'en'
? 'https://o96u.github.io/PicHost/en/guide/api.html'
: 'https://o96u.github.io/PicHost/guide/api.html'
)
const categories: { key: ApiDocCategory, labelKey: string }[] = [
{ key: 'image', labelKey: 'api.categories.image' },
{ key: 'extension', labelKey: 'api.categories.extension' },
{ key: 'system', labelKey: 'api.categories.system' }
]
const filteredEndpoints = computed(() => {
const q = search.value.trim().toLowerCase()
if (!q) return props.endpoints
return props.endpoints.filter((endpoint) => {
const title = t(endpoint.titleKey).toLowerCase()
const path = endpoint.path.toLowerCase()
return title.includes(q) || path.includes(q) || endpoint.method.toLowerCase().includes(q)
})
})
function endpointsForCategory(category: ApiDocCategory) {
return filteredEndpoints.value.filter(endpoint => endpoint.category === category)
}
function onSelect(id: string) {
emit('select', id)
}
function onSearchKeydown(event: KeyboardEvent) {
if (event.key === 'Escape') {
search.value = ''
event.preventDefault()
}
}
onMounted(() => {
const onGlobalKeydown = (event: KeyboardEvent) => {
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === 'k') {
event.preventDefault()
document.getElementById('api-endpoint-search')?.focus()
}
}
window.addEventListener('keydown', onGlobalKeydown)
onUnmounted(() => window.removeEventListener('keydown', onGlobalKeydown))
})
</script>
<template>
<aside class="flex w-full shrink-0 flex-col border-b border-default bg-default lg:w-52 lg:border-b-0 lg:border-r lg:bg-neutral-50 dark:lg:bg-neutral-900/30 xl:w-56">
<div class="border-b border-default p-3 sm:p-4">
<UInput
id="api-endpoint-search"
v-model="search"
:placeholder="t('api.searchPlaceholder')"
icon="i-lucide-search"
size="sm"
@keydown="onSearchKeydown"
>
<template #trailing>
<UKbd
size="sm"
class="hidden sm:inline-flex"
>
⌘K
</UKbd>
</template>
</UInput>
</div>
<nav class="flex-1 overflow-y-auto p-2 sm:p-3">
<div
v-for="category in categories"
:key="category.key"
class="mb-4"
>
<p
v-if="endpointsForCategory(category.key).length"
class="mb-1.5 px-2 text-xs font-medium text-muted"
>
{{ t(category.labelKey) }}
</p>
<ul class="space-y-0.5">
<li
v-for="endpoint in endpointsForCategory(category.key)"
:key="endpoint.id"
>
<button
type="button"
class="flex w-full items-center gap-2 rounded-lg px-2 py-2 text-left text-sm transition-colors"
:class="activeId === endpoint.id
? 'bg-primary/10 font-medium text-primary'
: 'text-muted hover:bg-muted/40 hover:text-highlighted'"
@click="onSelect(endpoint.id)"
>
<ApiMethodBadge :method="endpoint.method" />
<span class="min-w-0 truncate">{{ t(endpoint.titleKey) }}</span>
</button>
</li>
</ul>
</div>
</nav>
<div class="hidden border-t border-default p-3 sm:p-4 lg:block">
<div class="rounded-xl border border-primary/15 bg-primary/5 p-3">
<div class="flex items-start gap-2.5">
<UIcon
name="i-lucide-book-open"
class="mt-0.5 size-4 shrink-0 text-primary"
/>
<div class="min-w-0 space-y-2">
<p class="text-xs font-medium text-highlighted">
{{ t('api.helpTitle') }}
</p>
<p class="text-xs leading-relaxed text-muted">
{{ t('api.helpSubtitle') }}
</p>
<UButton
:label="t('api.viewDocs')"
icon="i-lucide-external-link"
size="xs"
variant="outline"
color="neutral"
:to="docsUrl"
target="_blank"
rel="noopener noreferrer"
/>
</div>
</div>
</div>
</div>
</aside>
</template>
+146
View File
@@ -0,0 +1,146 @@
<script setup lang="ts">
const props = defineProps<{
token: string
loading: boolean
regenerating: boolean
canRegenerate: boolean
tokenSource?: 'env' | 'db' | 'none'
envTokenOverride?: boolean
isAdmin?: boolean
}>()
const emit = defineEmits<{
regenerate: []
}>()
const { t } = useI18n()
const toast = useToast()
const tokenVisible = ref(false)
const copying = ref(false)
function toggleTokenVisible() {
tokenVisible.value = !tokenVisible.value
}
const displayValue = computed(() => {
if (!props.token) return t('common.notConfigured')
if (tokenVisible.value) return props.token
return '•'.repeat(Math.min(props.token.length, 40))
})
function tokenSourceLabel(source: 'env' | 'db' | 'none' | undefined) {
switch (source) {
case 'env':
return t('api.tokenSourceEnv')
case 'db':
return t('api.tokenSourceDb')
default:
return t('api.tokenSourceNone')
}
}
async function copyToken() {
if (!props.token || copying.value) return
copying.value = true
try {
await navigator.clipboard.writeText(props.token)
toast.add({ title: t('copy.copied'), color: 'success' })
} catch {
toast.add({ title: t('copy.failed'), color: 'error' })
} finally {
copying.value = false
}
}
</script>
<template>
<section class="border-b border-default">
<div class="flex items-center gap-2 border-b border-default px-5 py-4 sm:px-6">
<UIcon
name="i-lucide-key-round"
class="size-5 shrink-0 text-primary"
/>
<h2 class="text-base font-semibold">
{{ t('api.tokenTitle') }}
</h2>
</div>
<div class="space-y-4 p-5 sm:p-6">
<UAlert
v-if="envTokenOverride"
color="warning"
variant="subtle"
icon="i-lucide-triangle-alert"
:title="t('api.envOverrideTitle')"
: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"
variant="subtle"
icon="i-lucide-info"
:title="t('api.notConfiguredTitle')"
:description="t('api.notConfiguredDesc')"
/>
<div class="flex flex-col gap-2 sm:flex-row sm:items-stretch">
<UInput
:model-value="displayValue"
readonly
class="min-w-0 flex-1 font-mono text-xs sm:text-sm"
:loading="loading"
/>
<div class="flex gap-2">
<UButton
size="sm"
variant="outline"
color="neutral"
:label="tokenVisible ? t('api.hideToken') : t('api.showToken')"
@click="toggleTokenVisible"
/>
<UButton
size="sm"
variant="outline"
color="neutral"
:label="t('common.copy')"
:loading="copying"
:disabled="!token"
@click="copyToken"
/>
<UButton
icon="i-lucide-refresh-cw"
:label="t('api.regenerate')"
color="primary"
variant="soft"
size="sm"
:loading="regenerating"
:disabled="!canRegenerate"
@click="emit('regenerate')"
/>
</div>
</div>
<p
v-if="tokenSource"
class="text-xs text-muted"
>
{{ tokenSourceLabel(tokenSource) }}
· {{ t('api.tokenHeader') }}
<code class="font-mono">Auth-Token: &lt;token&gt;</code>
<template v-if="token && !envTokenOverride">
· {{ t('api.tokenInvalidate') }}
</template>
</p>
</div>
</section>
</template>
+152
View File
@@ -0,0 +1,152 @@
<script setup lang="ts">
const props = withDefaults(defineProps<{
searchQuery: string
storageBackend: string
storageBackendItems: Array<{ label: string, value: string }>
uploadSource: string
uploadSourceItems: Array<{ label: string, value: string }>
viewMode: 'grid' | 'list'
selectedCount?: number
loading?: boolean
showBatchDelete?: boolean
}>(), {
selectedCount: 0,
loading: false,
showBatchDelete: true
})
const emit = defineEmits<{
'update:searchQuery': [value: string]
'update:storageBackend': [value: string]
'update:uploadSource': [value: string]
'update:viewMode': [mode: 'grid' | 'list']
'search': []
'reset': []
'batch-delete': []
}>()
const { t } = useI18n()
function setViewMode(mode: 'grid' | 'list') {
if (mode === props.viewMode || props.loading) return
emit('update:viewMode', mode)
}
function viewButtonClass(active: boolean) {
return active
? 'border-primary bg-primary/10 text-primary'
: 'border-transparent bg-elevated text-muted hover:bg-muted hover:text-default'
}
</script>
<template>
<form
class="flex flex-nowrap items-center gap-2 overflow-x-auto pb-1"
@submit.prevent="emit('search')"
>
<UInput
:model-value="searchQuery"
icon="i-lucide-search"
:placeholder="t('stats.searchPlaceholder')"
class="w-40 shrink-0 sm:w-48"
size="sm"
:disabled="loading"
@update:model-value="emit('update:searchQuery', $event)"
/>
<USelect
:model-value="storageBackend"
:items="storageBackendItems"
class="w-28 shrink-0"
size="sm"
:aria-label="t('stats.storage')"
:disabled="loading"
@update:model-value="emit('update:storageBackend', $event)"
/>
<USelect
:model-value="uploadSource"
:items="uploadSourceItems"
class="w-28 shrink-0"
size="sm"
:aria-label="t('stats.filterSource')"
:disabled="loading"
@update:model-value="emit('update:uploadSource', $event)"
/>
<UButton
type="submit"
icon="i-lucide-search"
size="sm"
color="primary"
class="shrink-0"
:aria-label="t('common.search')"
:loading="loading"
>
{{ t('common.search') }}
</UButton>
<UButton
type="button"
icon="i-lucide-rotate-ccw"
size="sm"
variant="outline"
color="neutral"
class="shrink-0"
:aria-label="t('stats.resetFilters')"
:disabled="loading"
@click="emit('reset')"
>
{{ t('stats.resetFilters') }}
</UButton>
<UButton
v-if="showBatchDelete"
type="button"
icon="i-lucide-trash-2"
size="sm"
variant="outline"
color="error"
class="shrink-0"
:disabled="!selectedCount || loading"
@click="emit('batch-delete')"
>
{{ t('stats.batchDelete') }}
</UButton>
<div
class="inline-flex shrink-0 overflow-hidden rounded-md border border-default"
role="group"
:aria-label="t('stats.viewMode')"
>
<button
type="button"
class="inline-flex size-8 items-center justify-center border-r border-default transition-colors disabled:pointer-events-none disabled:opacity-40"
:class="viewButtonClass(viewMode === 'grid')"
:aria-label="t('stats.viewGrid')"
:aria-pressed="viewMode === 'grid'"
:disabled="loading"
@click="setViewMode('grid')"
>
<UIcon
name="i-lucide-layout-grid"
class="size-4"
/>
</button>
<button
type="button"
class="inline-flex size-8 items-center justify-center transition-colors disabled:pointer-events-none disabled:opacity-40"
:class="viewButtonClass(viewMode === 'list')"
:aria-label="t('stats.viewList')"
:aria-pressed="viewMode === 'list'"
:disabled="loading"
@click="setViewMode('list')"
>
<UIcon
name="i-lucide-list"
class="size-4"
/>
</button>
</div>
</form>
</template>
+224
View File
@@ -0,0 +1,224 @@
<script setup lang="ts">
import type { ImageItem } from '~/types/image'
const props = withDefaults(defineProps<{
items: ImageItem[]
selectedKeys: Set<string>
selectable?: boolean
showStorage?: boolean
emptyText?: string
showDelete?: boolean
}>(), {
selectable: false,
showStorage: false,
showDelete: true
})
const emit = defineEmits<{
'update:selectedKeys': [value: Set<string>]
'preview': [image: ImageItem]
'delete': [image: ImageItem]
}>()
const { t } = useI18n()
const { formatFileSize } = useFileSize()
const displayEmptyText = computed(() => props.emptyText ?? t('image.empty'))
const allSelected = computed(() =>
props.items.length > 0 && props.items.every(item => props.selectedKeys.has(item.key))
)
const someSelected = computed(() =>
props.items.some(item => props.selectedKeys.has(item.key))
)
const headerIndeterminate = computed(() => someSelected.value && !allSelected.value)
function updateSelection(key: string, selected: boolean) {
const next = new Set(props.selectedKeys)
if (selected) next.add(key)
else next.delete(key)
emit('update:selectedKeys', next)
}
function toggleAll(value: boolean | 'indeterminate') {
if (value === true) {
emit('update:selectedKeys', new Set(props.items.map(item => item.key)))
return
}
emit('update:selectedKeys', new Set())
}
function formatUploadedAt(value: string) {
try {
const date = new Date(value)
const y = date.getFullYear()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
const h = String(date.getHours()).padStart(2, '0')
const min = String(date.getMinutes()).padStart(2, '0')
const s = String(date.getSeconds()).padStart(2, '0')
return `${y}/${m}/${d} ${h}:${min}:${s}`
} catch {
return value
}
}
function sourceLabel(image: ImageItem) {
switch (image.uploadSource) {
case 'web':
return t('stats.tagWeb')
case 'api':
return t('stats.tagApi')
default:
return null
}
}
function typeLabel(image: ImageItem) {
if (props.showStorage && image.storage) return image.storage.name
return '—'
}
</script>
<template>
<div
v-if="items.length"
class="overflow-hidden rounded-xl border border-default bg-default"
>
<div class="overflow-x-auto">
<table class="min-w-full text-sm">
<thead class="border-b border-default text-xs text-muted">
<tr>
<th
v-if="selectable"
class="w-10 px-4 py-3 text-left font-medium"
>
<UCheckbox
:model-value="allSelected ? true : headerIndeterminate ? 'indeterminate' : false"
:aria-label="t('stats.selectAll')"
@update:model-value="toggleAll"
/>
</th>
<th class="min-w-[16rem] px-4 py-3 text-left font-medium">
{{ t('stats.colFilename') }}
</th>
<th class="hidden w-28 px-4 py-3 text-left font-medium sm:table-cell">
{{ t('stats.colSource') }}
</th>
<th class="w-24 px-4 py-3 text-left font-medium">
{{ t('stats.colSize') }}
</th>
<th class="hidden w-32 px-4 py-3 text-left font-medium md:table-cell">
{{ t('stats.colType') }}
</th>
<th class="hidden w-44 px-4 py-3 text-left font-medium lg:table-cell">
{{ t('stats.colUploadedAt') }}
</th>
<th class="w-28 px-4 py-3 text-right font-medium">
{{ t('stats.colActions') }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-default">
<tr
v-for="image in items"
:key="image.key"
class="transition-colors hover:bg-muted/20"
>
<td
v-if="selectable"
class="px-4 py-3"
>
<UCheckbox
:model-value="selectedKeys.has(image.key)"
@update:model-value="updateSelection(image.key, $event === true)"
/>
</td>
<td class="px-4 py-3">
<div class="flex min-w-0 items-center gap-3">
<button
type="button"
class="relative size-10 shrink-0 overflow-hidden rounded-md border border-default bg-muted"
:aria-label="t('image.openPreview')"
@click="emit('preview', image)"
>
<img
:src="image.url"
:alt="image.originalName"
loading="lazy"
class="size-full object-cover"
>
</button>
<p
class="min-w-0 flex-1 truncate font-medium"
:title="image.originalName"
>
{{ image.originalName }}
</p>
</div>
</td>
<td class="hidden px-4 py-3 sm:table-cell">
<span
v-if="sourceLabel(image)"
class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary"
>
{{ sourceLabel(image) }}
</span>
<span
v-else
class="text-muted"
>—</span>
</td>
<td class="px-4 py-3 text-muted">
{{ formatFileSize(image.size) }}
</td>
<td class="hidden px-4 py-3 text-muted md:table-cell">
<span class="truncate">{{ typeLabel(image) }}</span>
</td>
<td class="hidden px-4 py-3 text-muted lg:table-cell">
{{ formatUploadedAt(image.uploadedAt) }}
</td>
<td class="px-4 py-3">
<div class="flex items-center justify-end gap-0.5 text-muted">
<CopyButton
icon="i-lucide-link"
icon-only
variant="ghost"
color="neutral"
:label="t('common.copy')"
:value="image.url"
:success-title="t('copy.copiedUrl')"
/>
<UButton
icon="i-lucide-eye"
variant="ghost"
color="neutral"
size="xs"
:aria-label="t('image.openPreview')"
@click="emit('preview', image)"
/>
<UButton
v-if="showDelete"
icon="i-lucide-trash-2"
variant="ghost"
color="neutral"
size="xs"
:aria-label="t('common.delete')"
@click="emit('delete', image)"
/>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div
v-else
class="rounded-xl border border-dashed border-default py-16 text-center text-sm text-muted"
>
{{ displayEmptyText }}
</div>
</template>
@@ -0,0 +1,55 @@
<script setup lang="ts">
import type { ImageItem } from '~/types/image'
const props = defineProps<{
items: ImageItem[]
selectedKeys: Set<string>
}>()
const emit = defineEmits<{
'update:selectedKeys': [value: Set<string>]
'clear': []
}>()
const { t } = useI18n()
const allSelected = computed(() =>
props.items.length > 0 && props.items.every(item => props.selectedKeys.has(item.key))
)
const someSelected = computed(() =>
props.items.some(item => props.selectedKeys.has(item.key))
)
const indeterminate = computed(() => someSelected.value && !allSelected.value)
function toggleAll(value: boolean | 'indeterminate') {
if (value === true) {
emit('update:selectedKeys', new Set(props.items.map(item => item.key)))
return
}
emit('update:selectedKeys', new Set())
}
</script>
<template>
<div class="flex min-w-0 items-center gap-3">
<UCheckbox
:model-value="allSelected ? true : indeterminate ? 'indeterminate' : false"
:disabled="!items.length"
:aria-label="t('stats.selectAll')"
@update:model-value="toggleAll"
/>
<p class="text-sm text-muted">
{{ t('stats.selectedItems', { n: selectedKeys.size }) }}
</p>
<button
type="button"
class="text-sm text-primary hover:underline disabled:pointer-events-none disabled:opacity-40"
:disabled="selectedKeys.size === 0"
@click="emit('clear')"
>
{{ t('stats.clear') }}
</button>
</div>
</template>
@@ -0,0 +1,238 @@
<script setup lang="ts">
export interface GalleryStatsData {
uploadToday: number
uploadYesterday: number
uploadMonth: number
uploadLastMonth: number
uploadTotal: number
storedCount: number
uploadBytesTotal: number
bySource: {
web: number
api: number
}
storageUsage: {
usedBytes: number
totalBytes: number | null
percent: number | null
}
}
const props = defineProps<{
stats: GalleryStatsData | null
loading?: boolean
}>()
const { t } = useI18n()
const { formatFileSize } = useFileSize()
const SOURCE_COLORS = ['var(--ui-primary)', '#10b981'] as const
const sourceItems = computed(() => {
const bySource = props.stats?.bySource
if (!bySource) return []
return [
{ key: 'web', label: t('stats.sourceWeb'), count: bySource.web, color: SOURCE_COLORS[0] },
{ key: 'api', label: t('stats.sourceApi'), count: bySource.api, color: SOURCE_COLORS[1] }
]
})
const sourceTotal = computed(() =>
sourceItems.value.reduce((sum, item) => sum + item.count, 0)
)
function sourcePercent(count: number) {
if (!sourceTotal.value) return 0
return Math.round((count / sourceTotal.value) * 100)
}
function formatTrend(current: number, previous: number) {
if (previous === 0) {
if (current === 0) {
return { text: t('stats.trendFlat'), tone: 'muted' as const }
}
return { text: t('stats.trendUp', { p: 100 }), tone: 'up' as const }
}
const change = Math.round(((current - previous) / previous) * 100)
if (change > 0) {
return { text: t('stats.trendUp', { p: change }), tone: 'up' as const }
}
if (change < 0) {
return { text: t('stats.trendDown', { p: Math.abs(change) }), tone: 'down' as const }
}
return { text: t('stats.trendFlat'), tone: 'muted' as const }
}
const todayTrend = computed(() =>
formatTrend(props.stats?.uploadToday ?? 0, props.stats?.uploadYesterday ?? 0)
)
const monthTrend = computed(() =>
formatTrend(props.stats?.uploadMonth ?? 0, props.stats?.uploadLastMonth ?? 0)
)
const usageLabel = computed(() => {
const usage = props.stats?.storageUsage
if (!usage) return '—'
const used = formatFileSize(usage.usedBytes)
if (usage.totalBytes) {
return `${used} / ${formatFileSize(usage.totalBytes)}`
}
return used
})
const usagePercent = computed(() => {
const percent = props.stats?.storageUsage.percent
if (percent == null) return null
return Math.min(percent, 100)
})
const usageBarWidth = computed(() => {
const usage = props.stats?.storageUsage
if (!usage?.totalBytes || usagePercent.value == null) return 0
return Math.max(usagePercent.value, usage.usedBytes > 0 ? 4 : 0)
})
function displayValue(value: number | undefined) {
if (props.loading) return '—'
return value ?? '—'
}
</script>
<template>
<section class="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-6">
<div class="rounded-xl border border-default bg-elevated p-4">
<p class="text-xs text-muted">
{{ t('stats.uploadToday') }}
</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-highlighted">
{{ displayValue(stats?.uploadToday) }}
</p>
<p
class="mt-2 text-xs"
:class="{
'text-primary': todayTrend.tone === 'up',
'text-muted': todayTrend.tone === 'muted',
'text-orange-600 dark:text-orange-400': todayTrend.tone === 'down'
}"
>
{{ t('stats.vsYesterday') }} {{ todayTrend.text }}
</p>
</div>
<div class="rounded-xl border border-default bg-elevated p-4">
<p class="text-xs text-muted">
{{ t('stats.uploadMonth') }}
</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-highlighted">
{{ displayValue(stats?.uploadMonth) }}
</p>
<p
class="mt-2 text-xs"
:class="{
'text-primary': monthTrend.tone === 'up',
'text-muted': monthTrend.tone === 'muted',
'text-orange-600 dark:text-orange-400': monthTrend.tone === 'down'
}"
>
{{ t('stats.vsLastMonth') }} {{ monthTrend.text }}
</p>
</div>
<div class="rounded-xl border border-default bg-elevated p-4">
<p class="text-xs text-muted">
{{ t('stats.uploadTotal') }}
</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-highlighted">
{{ displayValue(stats?.uploadTotal) }}
</p>
<p class="mt-2 text-xs text-muted">
{{ t('stats.totalFiles') }}
</p>
</div>
<div class="rounded-xl border border-default bg-elevated p-4">
<p class="text-xs text-muted">
{{ t('stats.storedCount') }}
</p>
<p class="mt-2 text-2xl font-semibold tabular-nums text-highlighted">
{{ displayValue(stats?.storedCount) }}
</p>
<p class="mt-2 text-xs text-muted">
{{ stats ? t('stats.totalOccupied', { size: formatFileSize(stats.uploadBytesTotal) }) : '—' }}
</p>
</div>
<div class="rounded-xl border border-default bg-elevated p-4">
<p class="text-xs text-muted">
{{ t('stats.storageUsage') }}
</p>
<p class="mt-2 text-sm font-semibold tabular-nums text-highlighted sm:text-base">
{{ usageLabel }}
</p>
<div
v-if="stats?.storageUsage.totalBytes"
class="mt-3 space-y-1"
>
<div class="h-1.5 overflow-hidden rounded-full bg-muted/50">
<div
class="h-full rounded-full bg-primary transition-all"
:style="{ width: `${usageBarWidth}%` }"
/>
</div>
<p class="text-right text-xs tabular-nums text-muted">
{{ usagePercent }}%
</p>
</div>
<p
v-else
class="mt-2 text-xs text-muted"
>
{{ t('stats.noQuota') }}
</p>
</div>
<div class="col-span-2 rounded-xl border border-default bg-elevated p-4 sm:col-span-1">
<p class="text-xs text-muted">
{{ t('stats.sourceDistribution') }}
</p>
<div
v-if="!sourceTotal"
class="mt-4 text-xs text-muted"
>
{{ t('stats.noData') }}
</div>
<ul
v-else
class="mt-3 space-y-3"
>
<li
v-for="item in sourceItems"
:key="item.key"
>
<div class="flex items-center justify-between gap-2 text-xs">
<span class="flex min-w-0 items-center gap-1.5">
<span
class="size-2 shrink-0 rounded-full"
:style="{ background: item.color }"
/>
<span class="truncate">{{ item.label }}</span>
</span>
<span class="shrink-0 tabular-nums text-muted">
{{ item.count }} ({{ sourcePercent(item.count) }}%)
</span>
</div>
<div class="mt-1.5 h-1.5 overflow-hidden rounded-full bg-muted/40">
<div
class="h-full rounded-full transition-[width]"
:style="{
width: `${sourcePercent(item.count)}%`,
backgroundColor: item.color
}"
/>
</div>
</li>
</ul>
</div>
</section>
</template>
@@ -0,0 +1,5 @@
<template>
<div class="divide-y divide-default overflow-hidden rounded-lg border border-default">
<slot />
</div>
</template>
@@ -0,0 +1,554 @@
<script setup lang="ts">
import type { ActivityLogListResponse, ActivityLogStorage, LogAction, LogSource } from '~/types/logs'
const { isAuthenticated, handleAuthError, isAdmin } = useAuth()
const toast = useToast()
const { t, locale } = useI18n()
const { formatFileSize } = useFileSize()
const loading = ref(true)
const page = ref(1)
const actionFilter = ref<'all' | LogAction>('all')
const sourceFilter = ref<'all' | LogSource>('all')
const userFilter = ref<'all' | number>('all')
const searchQuery = ref('')
const activeSearch = ref('')
const listData = ref<ActivityLogListResponse | null>(null)
const imageLinkBase = ref('')
const hideFolderInUrl = ref(false)
const pageSize = 10
const summaryLabel = computed(() => {
const summary = listData.value?.summary
if (!summary) return ''
return t('logs.summaryAll', {
total: summary.total,
upload: summary.upload,
delete: summary.delete
})
})
const actionItems = computed(() => [
{ label: t('logs.filterActionAll'), value: 'all' as const },
{ label: t('logs.actionUpload'), value: 'upload' as const },
{ label: t('logs.actionDelete'), value: 'delete' as const }
])
const sourceItems = computed(() => [
{ label: t('logs.filterSourceAll'), value: 'all' as const },
{ label: t('logs.sourceWeb'), value: 'web' as const },
{ label: t('logs.sourceApi'), value: 'api' as const }
])
const userItems = computed(() => {
const items: Array<{ label: string, value: 'all' | number }> = [
{ label: t('logs.filterUserAll'), value: 'all' }
]
for (const user of listData.value?.users ?? []) {
items.push({ label: user.username, value: user.id })
}
return items
})
function formatTime(value: string) {
try {
return new Date(value).toLocaleString(locale.value, { hour12: false })
} catch {
return value
}
}
function formatTimeShort(value: string) {
try {
return new Date(value).toLocaleString(locale.value, {
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false
})
} catch {
return value
}
}
function actionBadgeClass(action: LogAction) {
const base = 'inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-xs font-medium whitespace-nowrap'
return action === 'upload'
? `${base} bg-success/10 text-success`
: `${base} bg-error/10 text-error`
}
function actionIcon(action: LogAction) {
return action === 'upload' ? 'i-lucide-upload' : 'i-lucide-trash-2'
}
function sourceLabel(source: LogSource) {
switch (source) {
case 'web':
return t('logs.sourceWeb')
case 'api':
return t('logs.sourceApi')
}
}
function storageIcon(storage: ActivityLogStorage | null) {
return storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
}
function publicPathFromKey(key: string) {
if (hideFolderInUrl.value) {
const slash = key.lastIndexOf('/')
return slash >= 0 ? key.slice(slash + 1) : key
}
const prefix = 'images/'
return key.startsWith(prefix) ? key.slice(prefix.length) : key
}
function imageUrl(key: string) {
const base = imageLinkBase.value.replace(/\/$/, '')
const path = publicPathFromKey(key)
if (!base) return `/${path}`
return `${base}/${path}`
}
async function loadImageLinkBase() {
try {
if (isAdmin.value) {
const data = await $fetch<{ effectiveImageBaseUrl: string, hideFolderInUrl: boolean }>('/api/settings', {
credentials: 'include'
})
imageLinkBase.value = data.effectiveImageBaseUrl
hideFolderInUrl.value = data.hideFolderInUrl
return
}
const data = await $fetch<{ env: { imageBaseUrl: string, hideFolderInUrl: boolean } }>('/api/user/api-token', {
credentials: 'include'
})
imageLinkBase.value = data.env.imageBaseUrl
hideFolderInUrl.value = data.env.hideFolderInUrl
} catch {
if (import.meta.client) {
imageLinkBase.value = window.location.origin
}
}
}
async function loadLogs() {
loading.value = true
try {
const query: Record<string, string | number> = {
page: page.value,
limit: pageSize
}
if (actionFilter.value !== 'all') {
query.action = actionFilter.value
}
if (sourceFilter.value !== 'all') {
query.source = sourceFilter.value
}
if (isAdmin.value && userFilter.value !== 'all') {
query.userId = userFilter.value
}
if (activeSearch.value) {
query.q = activeSearch.value
}
listData.value = await $fetch<ActivityLogListResponse>('/api/logs', {
credentials: 'include',
query
})
page.value = listData.value.page
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: t('logs.loadFailed'), color: 'error' })
}
} finally {
loading.value = false
}
}
function applyFilters() {
page.value = 1
void loadLogs()
}
function submitSearch() {
activeSearch.value = searchQuery.value.trim()
applyFilters()
}
function clearSearch() {
searchQuery.value = ''
activeSearch.value = ''
applyFilters()
}
function handlePageChange(target: number) {
page.value = target
void loadLogs()
}
onMounted(async () => {
await loadImageLinkBase()
await loadLogs()
})
</script>
<template>
<div class="min-w-0">
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default px-5 py-4 sm:px-6">
<div>
<h2 class="text-sm font-semibold">
{{ t('logs.pageTitle') }}
</h2>
<p class="mt-0.5 text-xs text-muted">
{{ isAdmin ? t('logs.pageSubtitleAdmin') : t('logs.pageSubtitle') }}
</p>
</div>
<UButton
icon="i-lucide-refresh-cw"
variant="outline"
color="neutral"
size="sm"
:label="t('common.refresh')"
:loading="loading"
@click="loadLogs"
/>
</div>
<form
class="border-b border-default px-5 py-3 sm:px-6"
@submit.prevent="submitSearch"
>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<p
v-if="summaryLabel"
class="text-xs text-muted"
>
{{ summaryLabel }}
</p>
<p
v-else
class="text-xs text-muted"
>
{{ t('stats.counting') }}
</p>
<div class="flex min-w-0 flex-wrap items-center gap-2 sm:justify-end">
<USelect
v-if="isAdmin"
v-model="userFilter"
:items="userItems"
value-key="value"
class="min-w-0 w-full sm:w-36"
size="sm"
@update:model-value="applyFilters"
/>
<USelect
v-model="actionFilter"
:items="actionItems"
value-key="value"
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-32"
size="sm"
@update:model-value="applyFilters"
/>
<USelect
v-model="sourceFilter"
:items="sourceItems"
value-key="value"
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-36"
size="sm"
@update:model-value="applyFilters"
/>
<div class="flex min-w-0 w-full items-center gap-2 sm:w-auto">
<UInput
v-model="searchQuery"
icon="i-lucide-search"
:placeholder="t('logs.searchPlaceholder')"
class="min-w-0 flex-1 sm:w-40 sm:flex-none"
size="sm"
:disabled="loading"
/>
<UButton
type="submit"
icon="i-lucide-search"
size="sm"
class="shrink-0"
:aria-label="t('common.search')"
:loading="loading"
>
<span class="hidden sm:inline">{{ t('common.search') }}</span>
</UButton>
<UButton
v-if="activeSearch"
type="button"
icon="i-lucide-x"
size="sm"
variant="ghost"
color="neutral"
class="shrink-0"
:aria-label="t('stats.clear')"
@click="clearSearch"
>
<span class="hidden sm:inline">{{ t('stats.clear') }}</span>
</UButton>
</div>
</div>
</div>
</form>
<div
v-if="loading"
class="p-4 sm:p-6"
>
<div class="space-y-3 sm:hidden">
<USkeleton
v-for="n in 6"
:key="`mobile-${n}`"
class="h-24 rounded-lg"
/>
</div>
<div class="hidden space-y-2 sm:block">
<USkeleton
v-for="n in 8"
:key="`desktop-${n}`"
class="h-12 rounded-lg"
/>
</div>
</div>
<template v-else-if="listData && listData.items.length">
<div class="min-w-0 sm:hidden">
<div class="divide-y divide-default">
<article
v-for="row in listData.items"
:key="row.id"
class="min-w-0 px-4 py-3.5"
>
<div class="flex items-start justify-between gap-3">
<time class="text-xs text-muted">
{{ formatTimeShort(row.createdAt) }}
</time>
<span class="shrink-0 text-xs tabular-nums text-muted">
{{ formatFileSize(row.size) }}
</span>
</div>
<div class="mt-2 flex min-w-0 max-w-full flex-wrap items-center gap-1.5">
<span :class="actionBadgeClass(row.action)">
<UIcon
:name="actionIcon(row.action)"
class="size-3 shrink-0"
/>
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }}
</span>
<span class="inline-flex items-center rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary whitespace-nowrap">
{{ sourceLabel(row.source) }}
</span>
<span
v-if="isAdmin"
class="text-xs text-muted"
>
{{ row.username ?? '—' }}
</span>
<UBadge
v-if="row.storage"
color="neutral"
variant="subtle"
size="xs"
class="max-w-full truncate"
>
<UIcon
:name="storageIcon(row.storage)"
class="mr-1 size-3"
/>
{{ row.storage.name }}
</UBadge>
</div>
<p
class="mt-2 truncate text-sm"
:title="row.originalName"
>
{{ row.originalName }}
</p>
<div class="mt-2 flex min-w-0 items-center gap-1">
<a
v-if="row.action === 'upload'"
:href="imageUrl(row.key)"
target="_blank"
rel="noopener noreferrer"
class="min-w-0 flex-1 truncate font-mono text-xs text-primary hover:underline"
:title="row.key"
>
{{ row.key }}
</a>
<span
v-else
class="min-w-0 flex-1 truncate font-mono text-xs text-dimmed"
:title="row.key"
>
{{ row.key }}
</span>
<CopyButton
icon="i-lucide-copy"
icon-only
class="shrink-0"
:label="t('common.copy')"
:value="row.key"
:success-title="t('copy.copiedUrl')"
/>
</div>
</article>
</div>
</div>
<div class="hidden min-w-0 sm:block">
<table class="w-full table-fixed text-left text-sm">
<thead class="border-b border-default bg-muted/30 text-xs text-muted">
<tr>
<th class="w-36 px-4 py-3 font-medium sm:px-6">
{{ t('logs.colTime') }}
</th>
<th
v-if="isAdmin"
class="w-20 px-4 py-3 font-medium"
>
{{ t('logs.colUser') }}
</th>
<th class="w-20 whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colAction') }}
</th>
<th class="w-16 whitespace-nowrap px-4 py-3 font-medium">
{{ t('logs.colSource') }}
</th>
<th class="w-24 px-4 py-3 font-medium">
{{ t('logs.colStorage') }}
</th>
<th class="hidden px-4 py-3 font-medium md:table-cell">
{{ t('logs.colFile') }}
</th>
<th class="w-20 px-4 py-3 font-medium">
{{ t('logs.colSize') }}
</th>
<th class="hidden px-4 py-3 font-medium xl:table-cell">
{{ t('logs.colKey') }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-default">
<tr
v-for="row in listData.items"
:key="row.id"
class="hover:bg-muted/20"
>
<td class="px-4 py-3 text-xs text-muted sm:px-6">
<span class="block truncate">{{ formatTime(row.createdAt) }}</span>
</td>
<td
v-if="isAdmin"
class="px-4 py-3 text-xs"
>
<span class="block truncate">{{ row.username ?? '—' }}</span>
</td>
<td class="whitespace-nowrap px-4 py-3">
<span :class="actionBadgeClass(row.action)">
<UIcon
:name="actionIcon(row.action)"
class="size-3 shrink-0"
/>
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }}
</span>
</td>
<td class="whitespace-nowrap px-4 py-3">
<span class="inline-flex items-center rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary">
{{ sourceLabel(row.source) }}
</span>
</td>
<td class="px-4 py-3 text-xs">
<span
v-if="row.storage"
class="flex min-w-0 items-center gap-1"
:title="row.storage.name"
>
<UIcon
:name="storageIcon(row.storage)"
class="size-3.5 shrink-0 opacity-70"
/>
<span class="truncate">{{ row.storage.name }}</span>
</span>
<span
v-else
class="text-muted"
>—</span>
</td>
<td
class="hidden max-w-0 truncate px-4 py-3 md:table-cell"
:title="row.originalName"
>
{{ row.originalName }}
</td>
<td class="whitespace-nowrap px-4 py-3 tabular-nums text-muted">
{{ formatFileSize(row.size) }}
</td>
<td class="hidden max-w-0 px-4 py-3 xl:table-cell">
<div class="flex min-w-0 items-center gap-1">
<a
v-if="row.action === 'upload'"
:href="imageUrl(row.key)"
target="_blank"
rel="noopener noreferrer"
class="min-w-0 truncate font-mono text-xs text-primary hover:underline"
:title="row.key"
>
{{ row.key }}
</a>
<span
v-else
class="min-w-0 truncate font-mono text-xs text-dimmed"
:title="row.key"
>
{{ row.key }}
</span>
<CopyButton
icon="i-lucide-copy"
icon-only
class="shrink-0"
:label="t('common.copy')"
:value="row.key"
:success-title="t('copy.copiedUrl')"
/>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<div
v-else
class="px-4 py-16 text-center text-sm text-muted sm:px-6"
>
{{ t('logs.empty') }}
</div>
<div
v-if="listData && listData.total > 0"
class="border-t border-default px-4 py-4 sm:px-6"
>
<PaginationBar
:page="listData.page"
:total-pages="listData.totalPages"
:total="listData.total"
:unit="t('logs.entriesUnit')"
:loading="loading"
@update:page="handlePageChange"
/>
</div>
</div>
</template>
@@ -0,0 +1,7 @@
<template>
<div class="overflow-hidden rounded-xl border border-default bg-default p-5 sm:p-6">
<div class="space-y-8">
<slot />
</div>
</div>
</template>
@@ -0,0 +1,37 @@
<script setup lang="ts">
defineProps<{
title: string
hint?: string
}>()
</script>
<template>
<section class="space-y-4">
<div class="flex items-start justify-between gap-4">
<div class="min-w-0">
<div class="flex items-center gap-2">
<span
class="h-4 w-1 shrink-0 rounded-full bg-primary"
aria-hidden="true"
/>
<h2 class="text-sm font-semibold text-highlighted">
{{ title }}
</h2>
</div>
<p
v-if="hint"
class="mt-1.5 pl-3 text-xs leading-relaxed text-muted"
>
{{ hint }}
</p>
</div>
<div
v-if="$slots.action"
class="shrink-0"
>
<slot name="action" />
</div>
</div>
<slot />
</section>
</template>
@@ -0,0 +1,33 @@
<script setup lang="ts">
defineProps<{
hasChanges: boolean
saving: boolean
}>()
const emit = defineEmits<{
save: []
}>()
const { t } = useI18n()
</script>
<template>
<div class="border-t border-default bg-default px-4 py-4 sm:px-6">
<div class="flex items-center justify-end gap-3">
<p
v-if="hasChanges"
class="mr-auto text-xs text-warning"
>
{{ t('settings.unsavedChanges') }}
</p>
<UButton
:label="t('settings.saveSettings')"
icon="i-lucide-save"
color="primary"
:loading="saving"
:disabled="!hasChanges"
@click="emit('save')"
/>
</div>
</div>
</template>
@@ -0,0 +1,47 @@
<script setup lang="ts">
import type { SettingsTab } from '~/types/settings'
defineProps<{
modelValue: SettingsTab
items: Array<{ id: SettingsTab, label: string, icon: string }>
title: string
subtitle: string
}>()
const emit = defineEmits<{
'update:modelValue': [SettingsTab]
}>()
</script>
<template>
<aside class="flex w-full shrink-0 flex-col border-b border-default bg-neutral-50 dark:bg-neutral-900/30 lg:w-56 lg:border-b-0 lg:border-r xl:w-60">
<div class="border-b border-default px-4 py-5 sm:px-5">
<h1 class="text-lg font-semibold tracking-tight text-highlighted">
{{ title }}
</h1>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ subtitle }}
</p>
</div>
<nav class="flex-1 space-y-0.5 p-3">
<button
v-for="item in items"
:key="item.id"
type="button"
class="flex w-full items-center gap-2.5 rounded-lg px-3 py-2.5 text-left text-sm transition-colors"
:class="modelValue === item.id
? 'bg-primary/10 font-medium text-primary'
: 'text-muted hover:bg-muted/50 hover:text-highlighted'"
@click="emit('update:modelValue', item.id)"
>
<UIcon
:name="item.icon"
class="size-4 shrink-0"
:class="modelValue === item.id ? 'text-primary' : 'opacity-70'"
/>
<span>{{ item.label }}</span>
</button>
</nav>
</aside>
</template>
@@ -0,0 +1,36 @@
<script setup lang="ts">
defineProps<{
appVersion: string
updateAvailable: boolean
latestVersion: string | null
releaseUrl: string | null
}>()
const { t } = useI18n()
</script>
<template>
<div class="pl-3">
<div class="flex flex-wrap items-center gap-2">
<span class="text-sm font-medium text-highlighted">
{{ t('settings.systemVersion') }}
</span>
<UBadge
color="neutral"
variant="subtle"
size="sm"
>
v{{ appVersion }}
</UBadge>
<a
v-if="updateAvailable && latestVersion"
:href="releaseUrl || 'https://github.com/O96u/PicHost/releases'"
target="_blank"
rel="noopener noreferrer"
class="text-xs text-warning hover:underline"
>
{{ t('settings.updateAvailable', { version: `v${latestVersion}` }) }}
</a>
</div>
</div>
</template>
@@ -0,0 +1,34 @@
<script setup lang="ts">
defineProps<{
title?: string
hint?: string
disabled?: boolean
}>()
const model = defineModel<boolean>({ required: true })
</script>
<template>
<div class="flex items-start justify-between gap-4 px-4 py-4 sm:px-5">
<div class="min-w-0 flex-1 pr-2">
<p class="text-sm font-medium text-highlighted">
<slot name="title">
{{ title }}
</slot>
</p>
<p
v-if="hint || $slots.hint"
class="mt-1 text-xs leading-relaxed text-muted"
>
<slot name="hint">
{{ hint }}
</slot>
</p>
</div>
<USwitch
v-model="model"
:disabled="disabled"
class="mt-0.5 shrink-0"
/>
</div>
</template>
@@ -0,0 +1,148 @@
<script setup lang="ts">
const {
compressEnabled,
autoCopyMarkdown,
copyFormat,
clientWebpQuality,
loadPreferences
} = useUploadPreferences()
const { t } = useI18n()
const {
userSettings,
enabled: userAutoDeleteEnabled,
daysDraft: userAutoDeleteDaysDraft,
load: loadUserSettings
} = useUserAutoDeleteSettings()
const copyFormatItems = computed(() => [
{ label: t('copy.url'), value: 'url' as const },
{ label: t('copy.markdown'), value: 'markdown' as const },
{ label: t('copy.html'), value: 'html' as const }
])
const clientQualityLevel = computed(() => {
if (clientWebpQuality.value >= 85) return t('preferences.qualityHigh')
if (clientWebpQuality.value >= 60) return t('preferences.qualityMedium')
return t('preferences.qualityLow')
})
function setCopyFormat(value: 'url' | 'markdown' | 'html') {
copyFormat.value = value
}
function onClientQualityInput(event: Event) {
const value = Number((event.target as HTMLInputElement).value)
clientWebpQuality.value = Number.isFinite(value) ? value : 80
}
onMounted(() => {
loadPreferences()
void loadUserSettings()
})
</script>
<template>
<SettingsSection :title="t('preferences.processing')">
<SettingsGroup>
<SettingsToggleRow
v-model="compressEnabled"
:title="t('preferences.clientCompress')"
:hint="t('preferences.clientCompressHint')"
/>
<div
v-if="userSettings"
class="flex items-start justify-between gap-4 px-4 py-4 sm:px-5"
>
<div class="min-w-0 flex-1 pr-2">
<p class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm font-medium text-highlighted">
<span>{{ t('preferences.autoDeletePrefix') }}</span>
<UInput
v-model.number="userAutoDeleteDaysDraft"
type="number"
min="1"
max="3650"
size="xs"
class="w-14 tabular-nums"
:class="userAutoDeleteEnabled ? '' : 'pointer-events-none opacity-40'"
/>
<span>{{ t('preferences.autoDeleteSuffix') }}</span>
</p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('preferences.autoDeleteHint') }}
</p>
</div>
<USwitch
v-model="userAutoDeleteEnabled"
class="mt-0.5 shrink-0"
/>
</div>
<div
v-else
class="flex justify-center py-4"
>
<UIcon
name="i-lucide-loader-circle"
class="size-5 animate-spin text-muted"
/>
</div>
<div class="px-4 py-4 sm:px-5">
<div class="flex items-start justify-between gap-4">
<div class="min-w-0 flex-1">
<p class="text-sm font-medium text-highlighted">
{{ t('preferences.webpQuality') }}
</p>
<p class="mt-1 text-xs leading-relaxed text-muted">
{{ t('preferences.webpQualityHint') }}
</p>
</div>
<div class="shrink-0 text-right text-xs text-muted">
<p>{{ t('preferences.current', { n: clientWebpQuality }) }}</p>
<p class="mt-0.5">
{{ clientQualityLevel }}
</p>
</div>
</div>
<input
type="range"
min="1"
max="100"
:value="clientWebpQuality"
class="mt-3 h-1.5 w-full cursor-pointer appearance-none rounded-full bg-muted accent-primary"
@input="onClientQualityInput"
>
</div>
</SettingsGroup>
</SettingsSection>
<SettingsSection :title="t('settings.uploadConvenience')">
<SettingsGroup>
<SettingsToggleRow
v-model="autoCopyMarkdown"
:title="t('preferences.autoCopy')"
:hint="t('preferences.autoCopyHint')"
/>
<div class="flex flex-col gap-3 px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5">
<p class="text-sm font-medium text-highlighted">
{{ t('settings.defaultCopyFormat') }}
</p>
<div
class="flex w-full max-w-xs gap-1 rounded-lg border border-default p-0.5 sm:w-auto"
:class="autoCopyMarkdown ? '' : 'pointer-events-none opacity-40'"
>
<UButton
v-for="item in copyFormatItems"
:key="item.value"
size="xs"
class="flex-1 justify-center sm:min-w-[4.5rem]"
:variant="copyFormat === item.value ? 'solid' : 'ghost'"
:color="copyFormat === item.value ? 'primary' : 'neutral'"
:label="item.label"
@click="setCopyFormat(item.value)"
/>
</div>
</div>
</SettingsGroup>
</SettingsSection>
</template>
+119 -160
View File
@@ -1,16 +1,6 @@
<script setup lang="ts">
import type { StorageBackendItem } from '~/types/storage'
type CardAction = {
key: string
icon: string
label: string
shortLabel: string
danger?: boolean
disabled?: boolean
onClick: () => void
}
const props = defineProps<{
backend: StorageBackendItem
envOverride?: boolean
@@ -35,181 +25,150 @@ const typeLabel = computed(() =>
props.backend.type === 'local' ? t('storage.backendLocal') : t('storage.backendCloud')
)
const servingLabel = computed(() =>
props.backend.servingMode === 'public'
? t('storage.servingPublic')
: t('storage.servingProxy')
)
const bucketLine = computed(() => {
if (props.backend.type !== 's3') return null
return props.backend.config.bucket || t('storage.notConfigured')
})
const actionsDisabled = computed(() => props.envOverride || props.busy)
const actions = computed<CardAction[]>(() => {
const isLocal = props.backend.type === 'local'
const items: CardAction[] = []
const isLocal = computed(() => props.backend.type === 'local')
if (!props.backend.isDefault && props.backend.enabled) {
items.push({
key: 'default',
icon: 'i-lucide-star',
label: t('storage.setDefault'),
shortLabel: isLocal ? t('storage.setDefault') : t('storage.actionSetDefault'),
onClick: () => emit('setDefault')
})
}
function canSetDefault() {
return !props.backend.isDefault && props.backend.enabled
}
if (props.backend.type === 's3') {
items.push({
key: 'edit',
icon: 'i-lucide-pencil',
label: t('common.edit'),
shortLabel: t('common.edit'),
onClick: () => emit('edit')
})
}
function canEdit() {
return props.backend.type === 's3'
}
items.push({
key: 'test',
icon: 'i-lucide-plug-zap',
label: t('storage.testConnection'),
shortLabel: isLocal ? t('storage.testConnection') : t('storage.actionTest'),
onClick: () => emit('test')
})
function canToggle() {
return props.backend.type !== 'local'
}
if (props.backend.type !== 'local') {
items.push({
key: 'toggle',
icon: props.backend.enabled ? 'i-lucide-pause' : 'i-lucide-play',
label: props.backend.enabled ? t('storage.disable') : t('storage.enable'),
shortLabel: props.backend.enabled ? t('storage.disable') : t('storage.enable'),
disabled: props.backend.isDefault && props.backend.enabled,
onClick: () => emit('toggleEnabled')
})
}
if (props.backend.type !== 'local' && !props.backend.isDefault) {
items.push({
key: 'delete',
icon: 'i-lucide-trash-2',
label: t('common.delete'),
shortLabel: t('common.delete'),
danger: true,
onClick: () => emit('delete')
})
}
return items
})
const actionGridClass = computed(() => {
switch (actions.value.length) {
case 1: return 'grid-cols-1'
case 2: return 'grid-cols-2'
case 3: return 'grid-cols-3'
case 4: return 'grid-cols-4'
default: return 'grid-cols-5'
}
})
function canDelete() {
return props.backend.type !== 'local' && !props.backend.isDefault
}
</script>
<template>
<article
class="flex h-full flex-col rounded-2xl border border-default bg-elevated p-4 shadow-sm"
:class="{
'ring-2 ring-primary/30': backend.isDefault,
'opacity-75': !backend.enabled
}"
class="flex h-full flex-col rounded-xl border border-default bg-elevated p-4 sm:p-5"
:class="{ 'opacity-75': !backend.enabled }"
>
<div class="mb-3 flex items-start justify-between gap-2">
<div class="flex min-w-0 items-start gap-2.5">
<div
class="flex size-9 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary"
>
<div class="flex items-start justify-between gap-3">
<div class="flex min-w-0 items-center gap-3">
<div class="flex size-10 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary">
<UIcon
:name="typeIcon"
class="size-4.5"
class="size-5"
/>
</div>
<div class="min-w-0">
<h3 class="truncate text-sm font-semibold">
{{ backend.name }}
</h3>
<p class="mt-0.5 text-xs text-muted">
{{ typeLabel }}
<template v-if="bucketLine">
· {{ bucketLine }}
</template>
</p>
</div>
<h3 class="truncate text-base font-semibold">
{{ backend.name }}
</h3>
</div>
<div class="flex shrink-0 flex-wrap justify-end gap-1">
<UBadge
v-if="backend.enabled"
color="success"
variant="subtle"
size="xs"
<div class="flex shrink-0 flex-wrap justify-end gap-1.5">
<span
v-if="backend.isDefault"
class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary"
>
{{ t('storage.badgeDefaultStorage') }}
</span>
<span
v-if="isLocal"
class="inline-flex rounded-md border border-default bg-default px-2 py-0.5 text-xs font-medium text-muted"
>
{{ t('storage.badgeLocal') }}
</span>
<span
v-else-if="backend.enabled"
class="inline-flex rounded-md border border-default bg-default px-2 py-0.5 text-xs font-medium text-muted"
>
{{ t('storage.badgeEnabled') }}
</UBadge>
<UBadge
v-if="backend.isDefault"
color="primary"
variant="subtle"
size="xs"
>
{{ t('storage.badgeDefault') }}
</UBadge>
<UBadge
v-if="!backend.enabled"
color="warning"
variant="subtle"
size="xs"
</span>
<span
v-else
class="inline-flex rounded-md bg-muted px-2 py-0.5 text-xs font-medium text-muted"
>
{{ t('storage.badgeDisabled') }}
</UBadge>
</span>
</div>
</div>
<StorageUsageBar
:capacity="backend.capacity"
:index-bytes="backend.usage.bytes"
/>
<div class="mt-4">
<StorageUsageBar
:capacity="backend.capacity"
:index-bytes="backend.usage.bytes"
/>
</div>
<p class="mt-3 text-xs text-muted">
{{ t('storage.servingMode') }}: {{ servingLabel }}
</p>
<div class="mt-4 border-t border-default pt-4">
<div
class="grid gap-1.5"
:class="actionGridClass"
>
<button
v-for="action in actions"
:key="action.key"
type="button"
class="flex flex-col items-center justify-center gap-1 rounded-lg border px-1 py-2 transition disabled:cursor-not-allowed disabled:opacity-40"
:class="action.danger
? 'border-error/30 text-error hover:bg-error/5'
: 'border-default text-muted hover:bg-muted/40 hover:text-highlighted'"
:title="action.label"
:aria-label="action.label"
:disabled="actionsDisabled || action.disabled"
@click="action.onClick"
>
<UIcon
:name="action.icon"
class="size-4 shrink-0"
/>
<span class="w-full truncate text-center text-[11px] leading-none">
{{ action.shortLabel }}
</span>
</button>
<div class="mt-4 flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted">
<div class="flex min-w-0 items-center gap-2">
<span class="shrink-0">{{ t('storage.storageId') }}:</span>
<code class="min-w-0 truncate font-mono text-dimmed">{{ backend.id }}</code>
<CopyButton
icon="i-lucide-copy"
icon-only
variant="ghost"
color="primary"
class="shrink-0"
:label="t('common.copy')"
:value="backend.id"
:success-title="t('copy.copied')"
/>
</div>
<span>
{{ t('storage.storageType') }}: {{ typeLabel }}
</span>
</div>
<div class="mt-4 flex flex-wrap gap-2 border-t border-default pt-4">
<UButton
v-if="canSetDefault()"
:label="t('storage.setDefault')"
icon="i-lucide-star"
size="sm"
variant="outline"
color="neutral"
:disabled="actionsDisabled"
@click="emit('setDefault')"
/>
<UButton
v-if="canEdit()"
:label="t('common.edit')"
icon="i-lucide-pencil"
size="sm"
variant="outline"
color="neutral"
:disabled="actionsDisabled"
@click="emit('edit')"
/>
<UButton
:label="t('storage.testConnection')"
:icon="isLocal ? 'i-lucide-wand-sparkles' : 'i-lucide-activity'"
size="sm"
variant="outline"
color="neutral"
:loading="busy"
:disabled="actionsDisabled"
@click="emit('test')"
/>
<UButton
v-if="canToggle()"
:label="backend.enabled ? t('storage.disable') : t('storage.enable')"
:icon="backend.enabled ? 'i-lucide-pause' : 'i-lucide-play'"
size="sm"
variant="outline"
color="neutral"
:disabled="actionsDisabled || (backend.isDefault && backend.enabled)"
@click="emit('toggleEnabled')"
/>
<UButton
v-if="canDelete()"
:label="t('common.delete')"
icon="i-lucide-trash-2"
size="sm"
variant="outline"
color="error"
:disabled="actionsDisabled"
@click="emit('delete')"
/>
</div>
</article>
</template>
@@ -6,6 +6,7 @@ type StorageProvider = 'r2' | 'cos' | 'oss' | 'aws' | 'custom'
export interface StorageFormPayload {
name: string
provider: StorageProvider
config: {
endpoint: string
region: string
@@ -158,6 +159,7 @@ watch(provider, (value) => {
function handleSubmit() {
emit('submit', {
name: name.value.trim() || providerLabel(provider.value),
provider: provider.value,
config: {
endpoint: endpoint.value.trim(),
region: region.value.trim() || 'auto',
+184
View File
@@ -0,0 +1,184 @@
<script setup lang="ts">
import type { StorageBackendItem } from '~/types/storage'
const props = defineProps<{
backends: StorageBackendItem[]
loading?: boolean
}>()
const { t } = useI18n()
const { formatFileSize } = useFileSize()
const CHART_COLORS = [
'var(--ui-primary)',
'#3b82f6',
'#6366f1',
'#f59e0b',
'#ec4899',
'#8b5cf6'
] as const
function backendUsedBytes(backend: StorageBackendItem) {
return backend.capacity.source === 'disk'
? backend.capacity.usedBytes
: backend.usage.bytes
}
const totalCapacityBytes = computed(() => {
let total = 0
let hasTotal = false
for (const backend of props.backends) {
if (backend.capacity.totalBytes != null && backend.capacity.totalBytes > 0) {
total += backend.capacity.totalBytes
hasTotal = true
}
}
return hasTotal ? total : null
})
const totalUsedBytes = computed(() =>
props.backends.reduce((sum, backend) => sum + backendUsedBytes(backend), 0)
)
const totalFreeBytes = computed(() => {
if (!totalCapacityBytes.value) return null
return Math.max(0, totalCapacityBytes.value - totalUsedBytes.value)
})
const usagePercent = computed(() => {
if (!totalCapacityBytes.value) return null
return Math.min(Math.round((totalUsedBytes.value / totalCapacityBytes.value) * 1000) / 10, 100)
})
const usageBarWidth = computed(() => {
if (usagePercent.value == null) return 0
return Math.max(usagePercent.value, totalUsedBytes.value > 0 ? 4 : 0)
})
const distributionItems = computed(() => {
if (!totalCapacityBytes.value) return []
return props.backends
.filter(backend => backend.capacity.totalBytes != null && backend.capacity.totalBytes > 0)
.map((backend, index) => ({
id: backend.id,
name: backend.name,
color: CHART_COLORS[index % CHART_COLORS.length]!,
percent: Math.round((backend.capacity.totalBytes! / totalCapacityBytes.value!) * 1000) / 10
}))
})
const donutStyle = computed(() => {
const items = distributionItems.value
if (!items.length) return { background: 'var(--ui-bg-muted)' }
let cursor = 0
const segments = items.map((item) => {
const start = cursor
cursor += item.percent
return `${item.color} ${start}% ${cursor}%`
})
return { background: `conic-gradient(${segments.join(', ')})` }
})
function displaySize(bytes: number | null) {
if (props.loading) return '—'
if (bytes == null) return '—'
return formatFileSize(bytes)
}
</script>
<template>
<section class="rounded-xl border border-default bg-elevated p-4 sm:p-5">
<h2 class="text-sm font-semibold">
{{ t('storage.overviewTitle') }}
</h2>
<p class="mt-0.5 text-xs text-muted">
{{ t('storage.overviewSubtitle') }}
</p>
<div class="mt-4 grid gap-5 lg:grid-cols-[minmax(0,1fr)_auto] lg:items-center">
<div>
<div class="grid grid-cols-2 gap-4 sm:grid-cols-4">
<div>
<p class="text-xs text-muted">
{{ t('storage.overviewTotal') }}
</p>
<p class="mt-1 text-lg font-semibold tabular-nums">
{{ displaySize(totalCapacityBytes) }}
</p>
<div
v-if="totalCapacityBytes"
class="mt-2 h-1 overflow-hidden rounded-full bg-muted/50"
>
<div
class="h-full rounded-full bg-primary transition-all"
:style="{ width: `${usageBarWidth}%` }"
/>
</div>
</div>
<div>
<p class="text-xs text-muted">
{{ t('storage.overviewUsed') }}
</p>
<p class="mt-1 text-lg font-semibold tabular-nums">
{{ displaySize(totalUsedBytes) }}
</p>
</div>
<div>
<p class="text-xs text-muted">
{{ t('storage.overviewFree') }}
</p>
<p class="mt-1 text-lg font-semibold tabular-nums">
{{ displaySize(totalFreeBytes) }}
</p>
</div>
<div>
<p class="text-xs text-muted">
{{ t('storage.overviewUsageRate') }}
</p>
<p class="mt-1 text-lg font-semibold tabular-nums">
{{ usagePercent != null ? `${usagePercent}%` : '—' }}
</p>
</div>
</div>
</div>
<div class="flex items-center gap-4">
<div
class="relative size-24 shrink-0 rounded-full p-2"
:style="donutStyle"
>
<div class="flex size-full items-center justify-center rounded-full bg-elevated px-2 text-center">
<p class="text-[10px] leading-tight text-muted">
{{ t('storage.capacityDistribution') }}
</p>
</div>
</div>
<ul
v-if="distributionItems.length"
class="min-w-[8rem] space-y-2"
>
<li
v-for="item in distributionItems"
:key="item.id"
class="flex items-center justify-between gap-3 text-xs"
>
<span class="flex min-w-0 items-center gap-1.5">
<span
class="size-2 shrink-0 rounded-full"
:style="{ background: item.color }"
/>
<span class="truncate">{{ item.name }}</span>
</span>
<span class="shrink-0 tabular-nums text-muted">
{{ item.percent }}%
</span>
</li>
</ul>
</div>
</div>
</section>
</template>
@@ -0,0 +1,62 @@
<script setup lang="ts">
const { t } = useI18n()
const items = computed(() => [
{
icon: 'i-lucide-hard-drive',
iconClass: 'text-primary',
boxClass: 'border-primary/20 bg-primary/5',
title: t('storage.backendLocal'),
desc: t('storage.supportedLocalDesc')
},
{
icon: 'i-lucide-cloud',
iconClass: 'text-orange-500',
boxClass: 'border-orange-500/20 bg-orange-500/5',
title: 'Cloudflare R2',
desc: t('storage.supportedR2Desc')
},
{
icon: 'i-lucide-server',
iconClass: 'text-blue-500',
boxClass: 'border-blue-500/20 bg-blue-500/5',
title: t('storage.supportedS3Title'),
desc: t('storage.supportedS3Desc')
}
])
</script>
<template>
<section class="rounded-xl border border-default bg-elevated p-4 sm:p-5">
<h2 class="text-sm font-semibold">
{{ t('storage.supportedTitle') }}
</h2>
<div class="mt-4 grid grid-cols-1 gap-3 lg:grid-cols-3">
<div
v-for="item in items"
:key="item.title"
class="flex items-start gap-3 rounded-lg border border-default bg-muted/30 px-4 py-3"
>
<div
class="flex size-10 shrink-0 items-center justify-center rounded-lg border"
:class="item.boxClass"
>
<UIcon
:name="item.icon"
class="size-5"
:class="item.iconClass"
/>
</div>
<div class="min-w-0 pt-0.5">
<p class="text-sm font-semibold">
{{ item.title }}
</p>
<p class="mt-0.5 text-xs leading-relaxed text-muted">
{{ item.desc }}
</p>
</div>
</div>
</div>
</section>
</template>
+30 -33
View File
@@ -36,56 +36,53 @@ function formatOptional(bytes: number | null): string {
<template>
<div class="space-y-3">
<div class="grid grid-cols-3 gap-2 text-center text-xs">
<div class="rounded-lg bg-muted/30 px-2 py-2">
<p class="text-muted">
{{ $t('storage.statTotal') }}
</p>
<p class="mt-1 font-medium tabular-nums text-highlighted">
{{ formatOptional(capacity.totalBytes) }}
</p>
</div>
<div class="rounded-lg bg-muted/30 px-2 py-2">
<p class="text-muted">
<div class="grid grid-cols-2 gap-3 sm:grid-cols-4">
<div>
<p class="text-xs text-muted">
{{ $t('storage.statUsed') }}
</p>
<p class="mt-1 font-medium tabular-nums text-highlighted">
<p class="mt-1 text-sm font-semibold tabular-nums">
{{ formatFileSize(displayUsedBytes) }}
</p>
</div>
<div class="rounded-lg bg-muted/30 px-2 py-2">
<p class="text-muted">
<div>
<p class="text-xs text-muted">
{{ $t('storage.statTotal') }}
</p>
<p class="mt-1 text-sm font-semibold tabular-nums">
{{ formatOptional(capacity.totalBytes) }}
</p>
</div>
<div>
<p class="text-xs text-muted">
{{ $t('storage.statFree') }}
</p>
<p
class="mt-1 font-medium tabular-nums"
:class="overQuota ? 'text-error' : 'text-highlighted'"
class="mt-1 text-sm font-semibold tabular-nums"
:class="overQuota ? 'text-error' : ''"
>
{{ formatOptional(capacity.freeBytes) }}
</p>
</div>
<div>
<p class="text-xs text-muted">
{{ $t('storage.usageRate') }}
</p>
<p class="mt-1 text-sm font-semibold tabular-nums">
{{ hasBar ? `${displayPercent}%` : '—' }}
</p>
</div>
</div>
<div
v-if="hasBar"
class="space-y-1"
class="h-1 overflow-hidden rounded-full bg-muted/50"
>
<div class="flex items-center justify-between text-xs">
<span class="text-muted">{{ $t('storage.usageRate') }}</span>
<span
class="tabular-nums font-medium"
:class="overQuota ? 'text-error' : ''"
>
{{ displayPercent }}%
</span>
</div>
<div class="h-1.5 overflow-hidden rounded-full bg-muted/50">
<div
class="h-full rounded-full transition-all"
:class="overQuota ? 'bg-error/80' : 'bg-primary/70'"
:style="{ width: `${barWidth}%` }"
/>
</div>
<div
class="h-full rounded-full transition-all"
:class="overQuota ? 'bg-error/80' : 'bg-primary'"
:style="{ width: `${barWidth}%` }"
/>
</div>
</div>
</template>
+323
View File
@@ -0,0 +1,323 @@
export type ApiDocMethod = 'GET' | 'POST' | 'DELETE'
export type ApiDocCategory = 'image' | 'extension' | 'system'
export type ApiParamLocation = 'form-data' | 'query' | 'header' | 'body'
export interface ApiDocParam {
name: string
type: string
location: ApiParamLocation
required: boolean
descriptionKey: string
}
export interface ApiDocEndpoint {
id: string
category: ApiDocCategory
method: ApiDocMethod
path: string
titleKey: string
descKey: string
params: ApiDocParam[]
requiresAuth: boolean
curl: string
responseExample: string
}
interface ApiDocsContext {
baseUrl: string
authHeader: string
}
function authFlag(authHeader: string) {
return `-H 'Auth-Token: ${authHeader}'`
}
export function buildApiDocs(ctx: ApiDocsContext): ApiDocEndpoint[] {
const { baseUrl, authHeader } = ctx
const auth = authFlag(authHeader)
return [
{
id: 'upload',
category: 'image',
method: 'POST',
path: '/api/images/upload',
titleKey: 'api.docs.upload.title',
descKey: 'api.docs.upload.desc',
requiresAuth: true,
params: [
{
name: 'image',
type: 'file',
location: 'form-data',
required: true,
descriptionKey: 'api.params.upload.image'
},
{
name: 'file',
type: 'file',
location: 'form-data',
required: false,
descriptionKey: 'api.params.upload.file'
},
{
name: 'files',
type: 'file',
location: 'form-data',
required: false,
descriptionKey: 'api.params.upload.files'
},
{
name: 'token',
type: 'string',
location: 'form-data',
required: false,
descriptionKey: 'api.params.upload.token'
}
],
curl: `curl -X POST "${baseUrl}/api/images/upload" \\
${auth} \\
-F "image=@./demo.png"`,
responseExample: `{
"success": true,
"items": [
{
"key": "images/2026/08/abc123.webp",
"url": "https://pic.example.com/abc123.webp",
"originalName": "demo.png",
"contentType": "image/webp",
"size": 12345,
"uploadedAt": "2026-08-01T12:00:00.000Z",
"markdown": "![demo.png](https://pic.example.com/abc123.webp)",
"html": "<img src=\\"https://pic.example.com/abc123.webp\\" alt=\\"demo.png\\">"
}
],
"errors": []
}`
},
{
id: 'list',
category: 'image',
method: 'GET',
path: '/api/images',
titleKey: 'api.docs.list.title',
descKey: 'api.docs.list.desc',
requiresAuth: true,
params: [
{
name: 'limit',
type: 'number',
location: 'query',
required: false,
descriptionKey: 'api.params.list.limit'
},
{
name: 'page',
type: 'number',
location: 'query',
required: false,
descriptionKey: 'api.params.list.page'
},
{
name: 'backendId',
type: 'string',
location: 'query',
required: false,
descriptionKey: 'api.params.backendId'
}
],
curl: `curl "${baseUrl}/api/images?limit=20&page=1" \\
${auth}`,
responseExample: `{
"items": [
{
"key": "images/2026/08/abc123.webp",
"url": "https://pic.example.com/abc123.webp",
"originalName": "demo.png",
"contentType": "image/webp",
"size": 12345,
"uploadedAt": "2026-08-01T12:00:00.000Z",
"markdown": "![demo.png](https://pic.example.com/abc123.webp)",
"html": "<img src=\\"https://pic.example.com/abc123.webp\\" alt=\\"demo.png\\">"
}
],
"total": 1,
"page": 1,
"pageSize": 20,
"totalPages": 1
}`
},
{
id: 'search',
category: 'image',
method: 'GET',
path: '/api/images/search',
titleKey: 'api.docs.search.title',
descKey: 'api.docs.search.desc',
requiresAuth: true,
params: [
{
name: 'q',
type: 'string',
location: 'query',
required: true,
descriptionKey: 'api.params.search.q'
},
{
name: 'limit',
type: 'number',
location: 'query',
required: false,
descriptionKey: 'api.params.list.limit'
},
{
name: 'page',
type: 'number',
location: 'query',
required: false,
descriptionKey: 'api.params.list.page'
},
{
name: 'backendId',
type: 'string',
location: 'query',
required: false,
descriptionKey: 'api.params.backendId'
}
],
curl: `curl "${baseUrl}/api/images/search?q=demo&limit=20&page=1" \\
${auth}`,
responseExample: `{
"items": [],
"total": 0,
"page": 1,
"pageSize": 20,
"totalPages": 0
}`
},
{
id: 'delete',
category: 'image',
method: 'DELETE',
path: '/api/images',
titleKey: 'api.docs.delete.title',
descKey: 'api.docs.delete.desc',
requiresAuth: true,
params: [
{
name: 'key',
type: 'string',
location: 'query',
required: true,
descriptionKey: 'api.params.delete.key'
}
],
curl: `curl -X DELETE "${baseUrl}/api/images?key=images/2026/08/xxxx.webp" \\
${auth}`,
responseExample: `{
"success": true
}`
},
{
id: 'batchDelete',
category: 'image',
method: 'POST',
path: '/api/images/batch-delete',
titleKey: 'api.docs.batchDelete.title',
descKey: 'api.docs.batchDelete.desc',
requiresAuth: true,
params: [
{
name: 'keys',
type: 'string[]',
location: 'body',
required: true,
descriptionKey: 'api.params.batchDelete.keys'
}
],
curl: `curl -X POST "${baseUrl}/api/images/batch-delete" \\
${auth} \\
-H "Content-Type: application/json" \\
-d '{"keys":["images/2026/08/a.webp","images/2026/08/b.webp"]}'`,
responseExample: `{
"success": true,
"deleted": ["images/2026/08/a.webp"],
"failed": []
}`
},
{
id: 'twikoo',
category: 'extension',
method: 'POST',
path: '/api/index.php',
titleKey: 'api.docs.twikoo.title',
descKey: 'api.docs.twikoo.desc',
requiresAuth: false,
params: [
{
name: 'image',
type: 'file',
location: 'form-data',
required: true,
descriptionKey: 'api.params.twikoo.image'
},
{
name: 'token',
type: 'string',
location: 'form-data',
required: true,
descriptionKey: 'api.params.twikoo.token'
}
],
curl: `curl -X POST "${baseUrl}/api/index.php" \\
-F "token=${authHeader}" \\
-F "image=@./demo.png"`,
responseExample: `{
"result": "success",
"code": 200,
"url": "https://pic.example.com/abc123.webp"
}`
},
{
id: 'config',
category: 'system',
method: 'GET',
path: '/api/auth/config',
titleKey: 'api.docs.config.title',
descKey: 'api.docs.config.desc',
requiresAuth: false,
params: [],
curl: `curl "${baseUrl}/api/auth/config"`,
responseExample: `{
"initialized": true,
"allowRegistration": false,
"legacyMode": false,
"adminSecretConfigured": false,
"apiUploadTokenConfigured": true
}`
},
{
id: 'count',
category: 'system',
method: 'GET',
path: '/api/images/count',
titleKey: 'api.docs.count.title',
descKey: 'api.docs.count.desc',
requiresAuth: true,
params: [
{
name: 'backendId',
type: 'string',
location: 'query',
required: false,
descriptionKey: 'api.params.backendId'
}
],
curl: `curl "${baseUrl}/api/images/count" \\
${auth}`,
responseExample: `{
"total": 42
}`
}
]
}
+37 -10
View File
@@ -1,3 +1,5 @@
import type { LoginVerificationPayload } from '~/types/auth'
export type AuthStatus = 'checking' | 'authenticated' | 'unauthenticated'
export type UserRole = 'admin' | 'user'
@@ -8,11 +10,18 @@ export interface AuthUser {
role: UserRole
}
export interface LoginVerificationPublicConfig {
method: 'slider' | 'turnstile' | 'cap'
turnstileSiteKey?: string
capApiEndpoint?: string
}
export interface AuthStatusResponse {
initialized: boolean
allowRegistration: boolean
legacyMode: boolean
needsMigration: boolean
loginVerification: LoginVerificationPublicConfig
user: AuthUser | null
}
@@ -66,9 +75,19 @@ export function getFetchErrorMessage(error: unknown, fallback: string): string {
export type AuthActionResult = { ok: true } | { ok: false, error: string }
export interface LoginCaptchaPayload {
captchaId: string
captchaPosition: number
export type { LoginVerificationPayload }
function buildVerificationBody(verification: LoginVerificationPayload): Record<string, unknown> {
if (verification.method === 'slider') {
return {
captchaId: verification.captchaId,
captchaPosition: verification.captchaPosition
}
}
if (verification.method === 'turnstile') {
return { turnstileToken: verification.turnstileToken }
}
return { capToken: verification.capToken }
}
export function useAuth() {
@@ -123,7 +142,7 @@ export function useAuth() {
async function login(
credentials: { username: string, password: string }
| { secret: string },
captcha: LoginCaptchaPayload
verification: LoginVerificationPayload
): Promise<{ ok: boolean, needsMigration?: boolean, error?: string }> {
try {
const result = await $fetch<{
@@ -135,8 +154,7 @@ export function useAuth() {
credentials: 'include',
body: {
...credentials,
captchaId: captcha.captchaId,
captchaPosition: captcha.captchaPosition
...buildVerificationBody(verification)
}
})
if (result.needsMigration) {
@@ -159,7 +177,8 @@ export function useAuth() {
async function register(
username: string,
password: string
password: string,
verification: LoginVerificationPayload
): Promise<AuthActionResult> {
const validationError = validateAuthInput(username, password)
if (validationError) {
@@ -172,7 +191,11 @@ export function useAuth() {
{
method: 'POST',
credentials: 'include',
body: { username: username.trim(), password }
body: {
username: username.trim(),
password,
...buildVerificationBody(verification)
}
}
)
user.value = result.user
@@ -291,15 +314,19 @@ export function useAuth() {
async function logout() {
try {
await $fetch('/api/auth/logout', { method: 'POST' })
await $fetch('/api/auth/logout', { method: 'POST', credentials: 'include' })
} catch {
// 忽略登出失败
} finally {
status.value = 'unauthenticated'
user.value = null
authStatus.value = null
hasValidatedOnce.value = true
}
try {
await fetchStatus()
} catch {
// 保留既有公开配置(loginVerification 等)
}
}
function handleAuthError(error: unknown) {
+72 -4
View File
@@ -3,12 +3,13 @@ import type {
ImageListResponse
} from '~/types/image'
const PAGE_SIZE = 12
const PAGE_SIZE_DEFAULT = 10
export function useImageList() {
const { t } = useI18n()
const items = ref<ImageItem[]>([])
const page = ref(1)
const pageSize = ref(PAGE_SIZE_DEFAULT)
const totalPages = ref(1)
const total = ref(0)
const loading = ref(false)
@@ -17,6 +18,8 @@ export function useImageList() {
const searchQuery = ref('')
const activeSearch = ref('')
const activeStorageBackend = ref('all')
const activeContentType = ref('all')
const activeUploadSource = ref('all')
const storageBackendOptions = ref<Array<{ id: string, name: string }>>([])
function storageQueryParams(): Record<string, string> {
@@ -25,8 +28,21 @@ export function useImageList() {
return { backendId }
}
function filterQueryParams(): Record<string, string> {
const params: Record<string, string> = { ...storageQueryParams() }
const contentType = activeContentType.value.trim()
if (contentType && contentType !== 'all') {
params.contentType = contentType
}
const uploadSource = activeUploadSource.value.trim()
if (uploadSource && uploadSource !== 'all') {
params.uploadSource = uploadSource
}
return params
}
function listQueryParams(): Record<string, string> {
return storageQueryParams()
return filterQueryParams()
}
function matchesActiveStorage(item: ImageItem) {
@@ -72,7 +88,7 @@ export function useImageList() {
const response = await $fetch<ImageListResponse>('/api/images', {
credentials: 'include',
query: {
limit: PAGE_SIZE,
limit: pageSize.value,
page: targetPage,
...listQueryParams()
}
@@ -100,7 +116,7 @@ export function useImageList() {
credentials: 'include',
query: {
q,
limit: PAGE_SIZE,
limit: pageSize.value,
page: targetPage,
...listQueryParams()
}
@@ -141,6 +157,40 @@ export function useImageList() {
}
}
async function setActiveContentType(contentType: string) {
const next = contentType.trim() || 'all'
if (next === activeContentType.value) return
activeContentType.value = next
page.value = 1
if (activeSearch.value) {
await Promise.all([fetchSearch(1), fetchTotal()])
} else {
await Promise.all([fetchList(1), fetchTotal()])
}
}
async function setActiveUploadSource(uploadSource: string) {
const next = uploadSource.trim() || 'all'
if (next === activeUploadSource.value) return
activeUploadSource.value = next
page.value = 1
if (activeSearch.value) {
await Promise.all([fetchSearch(1), fetchTotal()])
} else {
await Promise.all([fetchList(1), fetchTotal()])
}
}
async function resetFilters() {
searchQuery.value = ''
activeSearch.value = ''
activeStorageBackend.value = 'all'
activeContentType.value = 'all'
activeUploadSource.value = 'all'
page.value = 1
await Promise.all([fetchList(1), fetchTotal()])
}
async function submitSearch() {
const q = searchQuery.value.trim()
activeSearch.value = q
@@ -161,6 +211,17 @@ export function useImageList() {
}
}
async function setPageSize(size: number) {
if (!Number.isFinite(size) || size <= 0 || size === pageSize.value) return
pageSize.value = size
page.value = 1
if (activeSearch.value) {
await Promise.all([fetchSearch(1), fetchTotal()])
} else {
await Promise.all([fetchList(1), fetchTotal()])
}
}
function prependItems(newItems: ImageItem[]) {
const matched = newItems.filter(item => matchesActiveStorage(item))
if (!matched.length || page.value !== 1) return
@@ -220,10 +281,13 @@ export function useImageList() {
return {
items,
page,
pageSize,
totalPages,
total,
loading,
activeStorageBackend,
activeContentType,
activeUploadSource,
storageBackendOptions,
searchQuery,
activeSearch,
@@ -234,9 +298,13 @@ export function useImageList() {
refreshList,
initializeList,
setActiveStorageBackend,
setActiveContentType,
setActiveUploadSource,
resetFilters,
loadStorageBackendOptions,
submitSearch,
goToPage,
setPageSize,
prependItems,
removeItems
}
+36 -265
View File
@@ -12,15 +12,6 @@ interface SettingsResponse {
}
}
interface ApiDocItem {
index: number
method: 'GET' | 'POST' | 'DELETE'
path: string
title: string
description: string
curl: string
}
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const toast = useToast()
const { t } = useI18n()
@@ -31,6 +22,7 @@ const regenerating = ref(false)
const confirmRegenerateOpen = ref(false)
const regenerateResultOpen = ref(false)
const newToken = ref('')
const activeEndpointId = ref('upload')
const baseUrl = computed(() => {
const configured = settings.value?.env.siteBaseUrl
@@ -43,106 +35,24 @@ const baseUrl = computed(() => {
const tokenDisplay = computed(() => settings.value?.apiUploadToken ?? '')
const hasToken = computed(() => tokenDisplay.value.length > 0)
const canRegenerate = computed(() => !settings.value?.envTokenOverride && !loading.value)
const canRegenerate = computed(() =>
!settings.value?.envTokenOverride && !loading.value
)
const authHeader = computed(() =>
hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN'
)
const authHeaderFlag = computed(() => `-H 'Auth-Token: ${authHeader.value}'`)
const apiDocs = computed(() =>
buildApiDocs({
baseUrl: baseUrl.value,
authHeader: authHeader.value
})
)
const apiDocs = computed<ApiDocItem[]>(() => {
const uploadDescription = t('api.docs.upload.desc')
const uploadCurl = `curl -X POST "${baseUrl.value}/api/images/upload" \\
${authHeaderFlag.value} \\
-F "image=@./demo.png"`
const listDescription = t('api.docs.list.desc')
const listCurl = `curl "${baseUrl.value}/api/images?limit=20&page=1" \\
${authHeaderFlag.value}`
return [
{
index: 1,
method: 'POST',
path: '/api/images/upload',
title: t('api.docs.upload.title'),
description: uploadDescription,
curl: uploadCurl
},
{
index: 2,
method: 'GET',
path: '/api/images',
title: t('api.docs.list.title'),
description: listDescription,
curl: listCurl
},
{
index: 3,
method: 'GET',
path: '/api/images/search',
title: t('api.docs.search.title'),
description: t('api.docs.search.desc'),
curl: `curl "${baseUrl.value}/api/images/search?q=demo&limit=20&page=1" \\
${authHeaderFlag.value}`
},
{
index: 4,
method: 'DELETE',
path: '/api/images',
title: t('api.docs.delete.title'),
description: t('api.docs.delete.desc'),
curl: `curl -X DELETE "${baseUrl.value}/api/images?key=images/2026/08/xxxx.webp" \\
${authHeaderFlag.value}`
},
{
index: 5,
method: 'POST',
path: '/api/images/batch-delete',
title: t('api.docs.batchDelete.title'),
description: t('api.docs.batchDelete.desc'),
curl: `curl -X POST "${baseUrl.value}/api/images/batch-delete" \\
${authHeaderFlag.value} \\
-H "Content-Type: application/json" \\
-d '{"keys":["images/2026/08/a.webp","images/2026/08/b.webp"]}'`
}
]
})
const twikooDoc = computed(() => ({
method: 'POST' as const,
path: '/api/index.php',
title: t('api.docs.twikoo.title'),
description: t('api.docs.twikoo.desc'),
curl: `curl -X POST "${baseUrl.value}/api/index.php" \\
-F "token=${authHeader.value}" \\
-F "image=@./demo.png"`
}))
function tokenSourceLabel(source: SettingsResponse['tokenSource']) {
switch (source) {
case 'env':
return t('api.tokenSourceEnv')
case 'db':
return t('api.tokenSourceDb')
default:
return t('api.tokenSourceNone')
}
}
function methodBadgeColor(method: ApiDocItem['method']) {
switch (method) {
case 'GET':
return 'info' as const
case 'POST':
return 'warning' as const
case 'DELETE':
return 'error' as const
default:
return 'neutral' as const
}
}
const activeEndpoint = computed(() =>
apiDocs.value.find(endpoint => endpoint.id === activeEndpointId.value) ?? apiDocs.value[0]
)
async function loadSettings() {
loading.value = true
@@ -251,175 +161,36 @@ watch(isAuthenticated, async (authed, prev) => {
<AppShell v-else>
<section class="overflow-hidden rounded-2xl border border-default bg-elevated shadow-sm">
<div class="flex items-center gap-2 border-b border-default px-5 py-4 sm:px-6">
<UIcon
name="i-lucide-key-round"
class="size-5 text-primary"
/>
<h2 class="text-base font-semibold">
{{ t('api.tokenTitle') }}
</h2>
</div>
<div class="space-y-4 p-5 sm:p-6">
<UAlert
v-if="settings?.envTokenOverride"
color="warning"
variant="subtle"
icon="i-lucide-triangle-alert"
:title="t('api.envOverrideTitle')"
:description="t('api.envOverrideDesc')"
<div class="flex flex-col lg:flex-row lg:items-stretch">
<ApiSidebar
:endpoints="apiDocs"
:active-id="activeEndpointId"
@select="activeEndpointId = $event"
/>
<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="settings && !hasToken"
color="info"
variant="subtle"
icon="i-lucide-info"
:title="t('api.notConfiguredTitle')"
:description="t('api.notConfiguredDesc')"
/>
<div class="flex flex-col gap-2 sm:flex-row sm:items-stretch">
<UInput
:model-value="hasToken ? tokenDisplay : t('common.notConfigured')"
readonly
class="min-w-0 flex-1 font-mono text-xs sm:text-sm"
<div class="flex min-w-0 flex-1 flex-col bg-default lg:border-r lg:border-default">
<ApiTokenCard
:token="tokenDisplay"
:loading="loading"
:regenerating="regenerating"
:can-regenerate="canRegenerate"
:token-source="settings?.tokenSource"
:env-token-override="settings?.envTokenOverride"
:is-admin="isAdmin"
@regenerate="requestRegenerate"
/>
<ApiDocView
v-if="activeEndpoint"
:endpoint="activeEndpoint"
/>
<div class="flex gap-2">
<CopyButton
:label="t('common.copy')"
:value="tokenDisplay"
/>
<UButton
icon="i-lucide-refresh-cw"
:label="t('api.regenerate')"
color="warning"
variant="soft"
:loading="regenerating"
:disabled="!canRegenerate"
@click="requestRegenerate"
/>
</div>
</div>
<p
v-if="settings"
class="text-xs text-muted"
>
{{ tokenSourceLabel(settings.tokenSource) }}
· {{ t('api.tokenHeader') }}
<code class="font-mono">Auth-Token: &lt;token&gt;</code>
<template v-if="hasToken && !settings.envTokenOverride">
· {{ t('api.tokenInvalidate') }}
</template>
</p>
</div>
</section>
<section class="overflow-hidden rounded-2xl border border-default bg-elevated shadow-sm">
<div class="flex items-center gap-2 border-b border-default px-5 py-4 sm:px-6">
<UIcon
name="i-lucide-book-open"
class="size-5 text-primary"
<ApiDebugger
v-if="activeEndpoint"
:endpoint="activeEndpoint"
:token="tokenDisplay"
/>
<h2 class="text-base font-semibold">
{{ t('api.docsTitle') }}
</h2>
</div>
<div class="divide-y divide-default">
<article
v-for="doc in apiDocs"
:key="doc.index"
class="space-y-4 p-5 sm:p-6"
>
<div class="flex gap-3">
<span
class="flex size-7 shrink-0 items-center justify-center rounded-full bg-primary/10 text-sm font-semibold text-primary"
>
{{ doc.index }}
</span>
<div class="min-w-0 space-y-2">
<div class="flex flex-wrap items-center gap-2">
<UBadge
:color="methodBadgeColor(doc.method)"
variant="subtle"
size="sm"
>
{{ doc.method }}
</UBadge>
<code class="rounded-md border border-primary/20 bg-primary/10 px-2 py-0.5 font-mono text-sm font-medium text-primary">
{{ doc.path }}
</code>
<span class="text-sm font-medium">
{{ doc.title }}
</span>
</div>
<p class="text-sm leading-relaxed text-muted">
{{ doc.description }}
</p>
</div>
</div>
<div>
<p class="mb-2 text-xs font-medium text-muted">
{{ t('api.curlExample') }}
</p>
<ApiCurlBlock :code="doc.curl" />
</div>
</article>
</div>
</section>
<section class="overflow-hidden rounded-2xl border border-dashed border-default bg-muted/20">
<div class="space-y-4 p-5 sm:p-6">
<div class="flex gap-3">
<UIcon
name="i-lucide-message-square"
class="mt-0.5 size-5 shrink-0 text-muted"
/>
<div class="min-w-0 space-y-2">
<div class="flex flex-wrap items-center gap-2">
<UBadge
:color="methodBadgeColor(twikooDoc.method)"
variant="subtle"
size="sm"
>
{{ twikooDoc.method }}
</UBadge>
<code class="rounded-md border border-primary/20 bg-primary/10 px-2 py-0.5 font-mono text-sm font-medium text-primary">
{{ twikooDoc.path }}
</code>
<span class="text-sm font-medium">
{{ twikooDoc.title }}
</span>
</div>
<p class="text-sm leading-relaxed text-muted">
{{ twikooDoc.description }}
</p>
</div>
</div>
<div>
<p class="mb-2 text-xs font-medium text-muted">
{{ t('api.curlExample') }}
</p>
<ApiCurlBlock
:code="twikooDoc.curl"
:scrollable="false"
/>
</div>
</div>
</section>
</AppShell>
+122 -263
View File
@@ -3,7 +3,9 @@ import type { ImageItem } from '~/types/image'
interface StatsResponse {
uploadToday: number
uploadYesterday: number
uploadMonth: number
uploadLastMonth: number
deleteToday: number
deleteMonth: number
uploadTotal: number
@@ -15,32 +17,39 @@ interface StatsResponse {
web: number
api: number
}
storageUsage: {
usedBytes: number
totalBytes: number | null
percent: number | null
}
}
const {
items,
page: galleryPage,
pageSize: galleryPageSize,
totalPages: galleryTotalPages,
total: galleryTotal,
loading: galleryLoading,
searchQuery,
activeSearch,
listSummary,
refreshList,
fetchList,
fetchSearch,
fetchTotal,
submitSearch,
goToPage,
setPageSize,
removeItems,
activeStorageBackend,
storageBackendOptions,
setActiveStorageBackend,
storageBackendOptions,
activeUploadSource,
setActiveUploadSource,
resetFilters,
loadStorageBackendOptions
} = useImageList()
const { formatFileSize } = useFileSize()
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth()
const toast = useToast()
const { t } = useI18n()
@@ -54,11 +63,20 @@ const deleteModalOpen = ref(false)
const deleteTargetKeys = ref<string[]>([])
const batchDeleting = ref(false)
const showScrollTop = ref(false)
const currentStorage = ref('all')
const previewOpen = ref(false)
const previewImage = ref<ImageItem | null>(null)
const viewMode = ref<'grid' | 'list'>('grid')
const storageSelectItems = computed(() => [
const currentUploadSource = ref('all')
const currentStorageBackend = ref('all')
const uploadSourceItems = computed(() => [
{ label: t('stats.filterSourceAll'), value: 'all' },
{ label: t('stats.sourceWeb'), value: 'web' },
{ label: t('stats.sourceApi'), value: 'api' }
])
const storageBackendItems = computed(() => [
{ label: t('stats.filterStorageAll'), value: 'all' },
...storageBackendOptions.value.map(backend => ({
label: backend.name,
@@ -68,47 +86,6 @@ const storageSelectItems = computed(() => [
const selectedCount = computed(() => selectedKeys.value.size)
const SOURCE_CHART_COLORS = [
'var(--ui-primary)',
'#10b981'
]
const sourceUploadItems = computed(() => {
const bySource = stats.value?.bySource
if (!bySource) return []
return [
{ key: 'web', label: t('stats.sourceWeb'), count: bySource.web, color: SOURCE_CHART_COLORS[0]! },
{ key: 'api', label: t('stats.sourceApi'), count: bySource.api, color: SOURCE_CHART_COLORS[1]! }
]
})
const sourceUploadTotal = computed(() =>
sourceUploadItems.value.reduce((sum, item) => sum + item.count, 0)
)
function sourcePercent(count: number) {
const total = sourceUploadTotal.value
if (!total) return 0
return Math.round((count / total) * 100)
}
const statCards = computed(() => {
const s = stats.value
const base = [
{ label: t('stats.uploadToday'), value: s?.uploadToday ?? '—' },
{ label: t('stats.uploadMonth'), value: s?.uploadMonth ?? '—' },
{ label: t('stats.uploadTotal'), value: s?.uploadTotal ?? '—' },
{ label: t('stats.storedCount'), value: s?.storedCount ?? '—' },
{ label: t('stats.deleteToday'), value: s?.deleteToday ?? '—' },
{ label: t('stats.deleteMonth'), value: s?.deleteMonth ?? '—' },
isAdmin.value
? { label: t('stats.userCount'), value: s?.userCount ?? '—' }
: { label: t('stats.deleteTotal'), value: s?.deleteTotal ?? '—' },
{ label: t('stats.uploadBytes'), value: s ? formatFileSize(s.uploadBytesTotal) : '—' }
]
return base
})
function onWindowScroll() {
showScrollTop.value = window.scrollY > 400
}
@@ -137,17 +114,6 @@ async function refreshStats() {
}
}
async function refreshGallery() {
if (!isAuthenticated.value) return
selectedKeys.value = new Set()
try {
await Promise.all([refreshList(), loadStorageBackendOptions()])
currentStorage.value = activeStorageBackend.value
} catch (error: unknown) {
handleAuthError(error)
}
}
async function reloadGallery() {
if (activeSearch.value) {
await fetchSearch(galleryPage.value)
@@ -167,7 +133,8 @@ async function refreshAll() {
reloadGallery(),
loadStorageBackendOptions()
])
currentStorage.value = activeStorageBackend.value
currentUploadSource.value = activeUploadSource.value
currentStorageBackend.value = activeStorageBackend.value
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
@@ -178,9 +145,9 @@ async function refreshAll() {
}
}
async function handleStorageChange(backendId: string) {
async function handleStorageBackendChange(backendId: string) {
if (!isAuthenticated.value) return
currentStorage.value = backendId
currentStorageBackend.value = backendId
selectedKeys.value = new Set()
try {
await setActiveStorageBackend(backendId)
@@ -189,6 +156,33 @@ async function handleStorageChange(backendId: string) {
}
}
async function handleUploadSourceChange(uploadSource: string) {
if (!isAuthenticated.value) return
currentUploadSource.value = uploadSource
selectedKeys.value = new Set()
try {
await setActiveUploadSource(uploadSource)
} catch (error: unknown) {
handleAuthError(error)
}
}
async function handleResetFilters() {
if (!isAuthenticated.value) return
selectedKeys.value = new Set()
currentUploadSource.value = 'all'
currentStorageBackend.value = 'all'
try {
await resetFilters()
} catch (error: unknown) {
handleAuthError(error)
}
}
function updateSelectedKeys(keys: Set<string>) {
selectedKeys.value = keys
}
async function handleSearch() {
if (!isAuthenticated.value) return
selectedKeys.value = new Set()
@@ -199,12 +193,6 @@ async function handleSearch() {
}
}
async function clearSearch() {
searchQuery.value = ''
if (!activeSearch.value) return
await refreshGallery()
}
function requestDelete(key: string) {
if (!isAuthenticated.value) return
previewOpen.value = false
@@ -223,19 +211,6 @@ function requestBatchDelete() {
deleteModalOpen.value = true
}
function selectAllOnPage() {
selectedKeys.value = new Set(items.value.map(item => item.key))
}
function invertSelectionOnPage() {
const next = new Set(selectedKeys.value)
for (const item of items.value) {
if (next.has(item.key)) next.delete(item.key)
else next.add(item.key)
}
selectedKeys.value = next
}
function clearSelection() {
selectedKeys.value = new Set()
}
@@ -311,6 +286,17 @@ async function handleGalleryPageChange(targetPage: number) {
}
}
async function handleGalleryPageSizeChange(size: number) {
selectedKeys.value = new Set()
previewOpen.value = false
previewImage.value = null
try {
await setPageSize(size)
} catch (error: unknown) {
handleAuthError(error)
}
}
function openPreview(image: ImageItem) {
previewImage.value = image
previewOpen.value = true
@@ -392,206 +378,76 @@ watch(isAuthenticated, async (authed, prev) => {
/>
</div>
<section class="grid gap-3 lg:grid-cols-3 lg:items-stretch">
<div class="grid grid-cols-2 gap-3 lg:col-span-2 lg:grid-cols-4">
<div
v-for="item in statCards"
:key="item.label"
class="rounded-xl border border-default bg-elevated p-4"
>
<p class="text-xs text-muted">
{{ item.label }}
</p>
<p class="mt-1 text-2xl font-semibold tabular-nums">
{{ item.value }}
</p>
</div>
</div>
<GalleryStatsOverview
:stats="stats"
:loading="statsLoading"
/>
<div class="flex h-full min-h-0 flex-col rounded-xl border border-default bg-elevated p-4 lg:col-span-1">
<h2 class="shrink-0 text-sm font-medium text-muted">
{{ t('stats.sourceDistribution') }}
</h2>
<div
v-if="!sourceUploadTotal"
class="flex flex-1 items-center justify-center text-center text-xs text-muted"
>
{{ t('stats.noData') }}
</div>
<ul
v-else
class="mt-4 flex min-h-0 flex-1 flex-col"
>
<li
v-for="item in sourceUploadItems"
:key="item.key"
class="flex flex-1 flex-col justify-center gap-2 py-1"
>
<div class="flex items-center justify-between gap-2 text-xs">
<span class="flex min-w-0 items-center gap-1.5">
<span
class="size-2 shrink-0 rounded-full"
:style="{ background: item.color }"
/>
<span class="truncate">{{ item.label }}</span>
</span>
<span class="shrink-0 tabular-nums text-muted">
{{ item.count }} ({{ sourcePercent(item.count) }}%)
</span>
</div>
<div class="h-2 rounded-full bg-muted/40">
<div
class="h-full rounded-full transition-[width]"
:style="{
width: `${sourcePercent(item.count)}%`,
backgroundColor: item.color
}"
/>
</div>
</li>
</ul>
</div>
</section>
<section class="space-y-3">
<div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
<GallerySelectionBar
:items="items"
:selected-keys="selectedKeys"
@update:selected-keys="updateSelectedKeys"
@clear="clearSelection"
/>
<section class="space-y-4">
<div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
<div class="min-w-0">
<h2 class="text-lg font-medium">
{{ t('stats.imagesSection') }}
</h2>
<p
v-if="!galleryLoading"
class="mt-0.5 text-sm text-muted"
>
{{ listSummary }}
</p>
</div>
<form
class="flex flex-wrap items-center justify-end gap-2"
@submit.prevent="handleSearch"
>
<UBadge
v-if="selectedCount"
color="primary"
variant="subtle"
class="shrink-0"
>
{{ t('stats.selected', { n: selectedCount }) }}
</UBadge>
<USelect
v-model="currentStorage"
:items="storageSelectItems"
class="w-[6.5rem] shrink-0 sm:w-36"
size="sm"
:aria-label="t('stats.storage')"
@update:model-value="handleStorageChange"
/>
<UInput
v-model="searchQuery"
icon="i-lucide-search"
:placeholder="t('stats.searchPlaceholder')"
class="w-36 shrink-0 sm:w-44"
size="sm"
:disabled="galleryLoading"
/>
<UButton
type="submit"
icon="i-lucide-search"
size="sm"
class="shrink-0"
:aria-label="t('common.search')"
:loading="galleryLoading"
>
<span class="hidden sm:inline">{{ t('common.search') }}</span>
</UButton>
<UButton
v-if="activeSearch"
type="button"
icon="i-lucide-x"
size="sm"
variant="ghost"
color="neutral"
class="shrink-0"
:aria-label="t('stats.clear')"
@click="clearSearch"
>
<span class="hidden sm:inline">{{ t('stats.clear') }}</span>
</UButton>
<UButton
type="button"
icon="i-lucide-check-check"
size="sm"
variant="outline"
color="neutral"
class="shrink-0"
:disabled="!items.length || galleryLoading"
:aria-label="t('stats.selectAll')"
@click="selectAllOnPage"
>
<span class="hidden sm:inline">{{ t('stats.selectAll') }}</span>
</UButton>
<UButton
type="button"
icon="i-lucide-shuffle"
size="sm"
variant="outline"
color="neutral"
class="shrink-0"
:disabled="!items.length || galleryLoading"
:aria-label="t('stats.invertSelection')"
@click="invertSelectionOnPage"
>
<span class="hidden sm:inline">{{ t('stats.invertSelection') }}</span>
</UButton>
<UButton
v-if="selectedCount"
type="button"
icon="i-lucide-x-circle"
size="sm"
variant="ghost"
color="neutral"
class="shrink-0"
:aria-label="t('stats.clearSelection')"
@click="clearSelection"
>
<span class="hidden sm:inline">{{ t('stats.clearSelection') }}</span>
</UButton>
<UButton
type="button"
icon="i-lucide-trash-2"
color="error"
variant="soft"
size="sm"
class="shrink-0"
:aria-label="t('stats.batchDelete')"
:disabled="!selectedCount"
@click="requestBatchDelete"
>
<span class="hidden sm:inline">{{ t('stats.batchDelete') }}</span>
</UButton>
</form>
<GalleryFilterBar
v-model:search-query="searchQuery"
:storage-backend="currentStorageBackend"
:storage-backend-items="storageBackendItems"
:upload-source="currentUploadSource"
:upload-source-items="uploadSourceItems"
:view-mode="viewMode"
:selected-count="selectedCount"
:loading="galleryLoading"
:show-batch-delete="true"
@update:storage-backend="handleStorageBackendChange"
@update:upload-source="handleUploadSourceChange"
@update:view-mode="viewMode = $event"
@search="handleSearch"
@reset="handleResetFilters"
@batch-delete="requestBatchDelete"
/>
</div>
<div
v-if="galleryLoading"
class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
:class="viewMode === 'grid'
? 'grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5'
: 'space-y-2'"
>
<USkeleton
v-for="n in 12"
v-for="n in 10"
:key="n"
class="aspect-square rounded-lg"
:class="viewMode === 'grid' ? 'aspect-[4/3] rounded-lg' : 'h-16 rounded-lg'"
/>
</div>
<ImageGrid
v-else
v-else-if="viewMode === 'grid'"
gallery
:show-key="false"
show-storage
:items="items"
:selected-keys="selectedKeys"
@update:selected-keys="selectedKeys = $event"
:selectable="true"
:allow-delete="true"
@update:selected-keys="updateSelectedKeys"
@preview="openPreview"
@delete="(image) => requestDelete(image.key)"
/>
<GalleryImageList
v-else
show-storage
:items="items"
:selected-keys="selectedKeys"
:selectable="true"
:show-delete="true"
@update:selected-keys="updateSelectedKeys"
@preview="openPreview"
@delete="(image) => requestDelete(image.key)"
/>
<ImagePreviewModal
@@ -599,6 +455,7 @@ watch(isAuthenticated, async (authed, prev) => {
:image="previewImage"
show-storage
:deleting="previewImage ? deletingKeys.has(previewImage.key) : false"
:allow-delete="true"
@delete="requestPreviewDelete"
/>
@@ -607,9 +464,11 @@ watch(isAuthenticated, async (authed, prev) => {
:page="galleryPage"
:total-pages="galleryTotalPages"
:total="galleryTotal"
:page-size="galleryPageSize"
:unit="t('common.imagesUnit')"
:loading="galleryLoading"
@update:page="handleGalleryPageChange"
@update:page-size="handleGalleryPageSizeChange"
/>
</section>
+1
View File
@@ -206,6 +206,7 @@ function requestPreviewDelete() {
v-model:open="previewOpen"
:image="previewImage"
:deleting="previewImage ? deletingKeys.has(previewImage.key) : false"
:allow-delete="true"
@delete="requestPreviewDelete"
/>
</AppShell>
+2 -616
View File
@@ -1,621 +1,7 @@
<script setup lang="ts">
import type { ActivityLogListResponse, ActivityLogStorage, LogAction, LogSource } from '~/types/logs'
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const toast = useToast()
const { t, locale } = useI18n()
const { formatFileSize } = useFileSize()
const loading = ref(true)
const page = ref(1)
const actionFilter = ref<'all' | LogAction>('all')
const sourceFilter = ref<'all' | LogSource>('all')
const userFilter = ref<'all' | number>('all')
const searchQuery = ref('')
const activeSearch = ref('')
const listData = ref<ActivityLogListResponse | null>(null)
const imageLinkBase = ref('')
const hideFolderInUrl = ref(false)
const pageSize = 10
const summaryLabel = computed(() => {
const summary = listData.value?.summary
if (!summary) return ''
return t('logs.summaryAll', {
total: summary.total,
upload: summary.upload,
delete: summary.delete
})
})
const actionItems = computed(() => [
{ label: t('logs.filterActionAll'), value: 'all' as const },
{ label: t('logs.actionUpload'), value: 'upload' as const },
{ label: t('logs.actionDelete'), value: 'delete' as const }
])
const sourceItems = computed(() => [
{ label: t('logs.filterSourceAll'), value: 'all' as const },
{ label: t('logs.sourceWeb'), value: 'web' as const },
{ label: t('logs.sourceApi'), value: 'api' as const }
])
const userItems = computed(() => {
const items: Array<{ label: string, value: 'all' | number }> = [
{ label: t('logs.filterUserAll'), value: 'all' }
]
for (const user of listData.value?.users ?? []) {
items.push({ label: user.username, value: user.id })
}
return items
})
function formatTime(value: string) {
try {
return new Date(value).toLocaleString(locale.value, { hour12: false })
} catch {
return value
}
}
function formatTimeShort(value: string) {
try {
return new Date(value).toLocaleString(locale.value, {
month: 'numeric',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
hour12: false
})
} catch {
return value
}
}
function folderFromKey(key: string) {
const slash = key.indexOf('/')
return slash > 0 ? key.slice(0, slash) : '(root)'
}
function actionColor(action: LogAction) {
return action === 'upload' ? 'success' : 'error'
}
function actionIcon(action: LogAction) {
return action === 'upload' ? 'i-lucide-upload' : 'i-lucide-trash-2'
}
function sourceLabel(source: LogSource) {
switch (source) {
case 'web':
return t('logs.sourceWeb')
case 'api':
return t('logs.sourceApi')
}
}
function storageIcon(storage: ActivityLogStorage | null) {
return storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
}
function publicPathFromKey(key: string) {
if (hideFolderInUrl.value) {
const slash = key.lastIndexOf('/')
return slash >= 0 ? key.slice(slash + 1) : key
}
const prefix = 'images/'
return key.startsWith(prefix) ? key.slice(prefix.length) : key
}
function imageUrl(key: string) {
const base = imageLinkBase.value.replace(/\/$/, '')
const path = publicPathFromKey(key)
if (!base) return `/${path}`
return `${base}/${path}`
}
async function loadImageLinkBase() {
try {
if (isAdmin.value) {
const data = await $fetch<{ effectiveImageBaseUrl: string, hideFolderInUrl: boolean }>('/api/settings', {
credentials: 'include'
})
imageLinkBase.value = data.effectiveImageBaseUrl
hideFolderInUrl.value = data.hideFolderInUrl
return
}
const data = await $fetch<{ env: { imageBaseUrl: string, hideFolderInUrl: boolean } }>('/api/user/api-token', {
credentials: 'include'
})
imageLinkBase.value = data.env.imageBaseUrl
hideFolderInUrl.value = data.env.hideFolderInUrl
} catch {
if (import.meta.client) {
imageLinkBase.value = window.location.origin
}
}
}
async function loadLogs() {
loading.value = true
try {
const query: Record<string, string | number> = {
page: page.value,
limit: pageSize
}
if (actionFilter.value !== 'all') {
query.action = actionFilter.value
}
if (sourceFilter.value !== 'all') {
query.source = sourceFilter.value
}
if (isAdmin.value && userFilter.value !== 'all') {
query.userId = userFilter.value
}
if (activeSearch.value) {
query.q = activeSearch.value
}
listData.value = await $fetch<ActivityLogListResponse>('/api/logs', {
credentials: 'include',
query
})
page.value = listData.value.page
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: t('logs.loadFailed'), color: 'error' })
}
} finally {
loading.value = false
}
}
function applyFilters() {
page.value = 1
void loadLogs()
}
function submitSearch() {
activeSearch.value = searchQuery.value.trim()
applyFilters()
}
function clearSearch() {
searchQuery.value = ''
activeSearch.value = ''
applyFilters()
}
function handlePageChange(target: number) {
page.value = target
void loadLogs()
}
onMounted(async () => {
const status = await fetchStatus()
if (!status.initialized && !status.legacyMode) {
await navigateTo('/setup')
return
}
await checkSession()
if (!isAuthenticated.value) {
await navigateTo('/')
return
}
await loadImageLinkBase()
await loadLogs()
})
watch(isAuthenticated, async (authed, prev) => {
if (authed && prev === false) {
await loadImageLinkBase()
await loadLogs()
}
})
await navigateTo({ path: '/settings', query: { tab: 'logs' } }, { replace: true })
</script>
<template>
<div class="min-h-screen">
<div
v-if="isChecking"
class="flex min-h-screen items-center justify-center"
>
<div class="flex flex-col items-center gap-3 text-muted">
<UIcon
name="i-lucide-loader-circle"
class="size-8 animate-spin"
/>
<p class="text-sm">
{{ t('common.loadingSession') }}
</p>
</div>
</div>
<AdminLoginGate v-else-if="!isAuthenticated" />
<AppShell v-else>
<section class="min-w-0 overflow-x-hidden rounded-2xl border border-default bg-elevated shadow-sm">
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default px-4 py-4 sm:px-6">
<div class="flex items-start gap-2">
<UIcon
name="i-lucide-scroll-text"
class="mt-0.5 size-5 shrink-0 text-primary"
/>
<div>
<h1 class="text-base font-semibold">
{{ t('logs.pageTitle') }}
</h1>
<p class="mt-0.5 text-xs text-muted">
{{ isAdmin ? t('logs.pageSubtitleAdmin') : t('logs.pageSubtitle') }}
</p>
</div>
</div>
<UButton
icon="i-lucide-refresh-cw"
variant="ghost"
color="neutral"
size="sm"
:aria-label="t('common.refresh')"
:loading="loading"
@click="loadLogs"
/>
</div>
<form
class="border-b border-default px-4 py-3 sm:px-6"
@submit.prevent="submitSearch"
>
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<p
v-if="summaryLabel"
class="text-xs text-muted"
>
{{ summaryLabel }}
</p>
<p
v-else
class="text-xs text-muted"
>
{{ t('stats.counting') }}
</p>
<div class="flex min-w-0 flex-wrap items-center gap-2 sm:justify-end">
<USelect
v-if="isAdmin"
v-model="userFilter"
:items="userItems"
value-key="value"
class="min-w-0 w-full sm:w-36"
size="sm"
@update:model-value="applyFilters"
/>
<USelect
v-model="actionFilter"
:items="actionItems"
value-key="value"
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-32"
size="sm"
@update:model-value="applyFilters"
/>
<USelect
v-model="sourceFilter"
:items="sourceItems"
value-key="value"
class="min-w-0 w-[calc(50%-0.25rem)] sm:w-36"
size="sm"
@update:model-value="applyFilters"
/>
<div class="flex min-w-0 w-full items-center gap-2 sm:w-auto">
<UInput
v-model="searchQuery"
icon="i-lucide-search"
:placeholder="t('logs.searchPlaceholder')"
class="min-w-0 flex-1 sm:w-40 sm:flex-none"
size="sm"
:disabled="loading"
/>
<UButton
type="submit"
icon="i-lucide-search"
size="sm"
class="shrink-0"
:aria-label="t('common.search')"
:loading="loading"
>
<span class="hidden sm:inline">{{ t('common.search') }}</span>
</UButton>
<UButton
v-if="activeSearch"
type="button"
icon="i-lucide-x"
size="sm"
variant="ghost"
color="neutral"
class="shrink-0"
:aria-label="t('stats.clear')"
@click="clearSearch"
>
<span class="hidden sm:inline">{{ t('stats.clear') }}</span>
</UButton>
</div>
</div>
</div>
</form>
<div
v-if="loading"
class="p-4 sm:p-6"
>
<div class="space-y-3 sm:hidden">
<USkeleton
v-for="n in 6"
:key="`mobile-${n}`"
class="h-24 rounded-lg"
/>
</div>
<div class="hidden space-y-2 sm:block">
<USkeleton
v-for="n in 8"
:key="`desktop-${n}`"
class="h-12 rounded-lg"
/>
</div>
</div>
<template v-else-if="listData && listData.items.length">
<div class="min-w-0 sm:hidden">
<div class="divide-y divide-default">
<article
v-for="row in listData.items"
:key="row.id"
class="min-w-0 px-4 py-3.5"
>
<div class="flex items-start justify-between gap-3">
<time class="text-xs text-muted">
{{ formatTimeShort(row.createdAt) }}
</time>
<span class="shrink-0 text-xs tabular-nums text-muted">
{{ formatFileSize(row.size) }}
</span>
</div>
<div class="mt-2 flex min-w-0 max-w-full flex-wrap items-center gap-1.5">
<UBadge
:color="actionColor(row.action)"
variant="subtle"
size="xs"
>
<UIcon
:name="actionIcon(row.action)"
class="mr-1 size-3"
/>
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }}
</UBadge>
<UBadge
color="neutral"
variant="subtle"
size="xs"
>
{{ sourceLabel(row.source) }}
</UBadge>
<span
v-if="isAdmin"
class="text-xs text-muted"
>
{{ row.username ?? '—' }}
</span>
<UBadge
v-if="row.storage"
color="neutral"
variant="subtle"
size="xs"
class="max-w-full truncate"
>
<UIcon
:name="storageIcon(row.storage)"
class="mr-1 size-3"
/>
{{ row.storage.name }}
</UBadge>
</div>
<p
class="mt-2 truncate text-sm"
:title="row.originalName"
>
{{ row.originalName }}
</p>
<div class="mt-2 flex min-w-0 items-center gap-1">
<a
v-if="row.action === 'upload'"
:href="imageUrl(row.key)"
target="_blank"
rel="noopener noreferrer"
class="min-w-0 flex-1 truncate font-mono text-xs text-primary hover:underline"
:title="row.key"
>
{{ row.key }}
</a>
<span
v-else
class="min-w-0 flex-1 truncate font-mono text-xs text-dimmed"
:title="row.key"
>
{{ row.key }}
</span>
<CopyButton
icon="i-lucide-copy"
icon-only
class="shrink-0"
:label="t('common.copy')"
:value="row.key"
:success-title="t('copy.copiedUrl')"
/>
</div>
</article>
</div>
</div>
<div class="hidden overflow-x-auto sm:block">
<table class="min-w-full text-left text-sm">
<thead class="border-b border-default bg-muted/30 text-xs text-muted">
<tr>
<th class="px-4 py-3 font-medium sm:px-6">
{{ t('logs.colTime') }}
</th>
<th
v-if="isAdmin"
class="px-4 py-3 font-medium"
>
{{ t('logs.colUser') }}
</th>
<th class="px-4 py-3 font-medium">
{{ t('logs.colAction') }}
</th>
<th class="px-4 py-3 font-medium">
{{ t('logs.colSource') }}
</th>
<th class="px-4 py-3 font-medium">
{{ t('logs.colStorage') }}
</th>
<th class="hidden px-4 py-3 font-medium md:table-cell">
{{ t('logs.colFile') }}
</th>
<th class="hidden px-4 py-3 font-medium lg:table-cell">
{{ t('logs.colFolder') }}
</th>
<th class="px-4 py-3 font-medium">
{{ t('logs.colSize') }}
</th>
<th class="hidden px-4 py-3 font-medium xl:table-cell">
{{ t('logs.colKey') }}
</th>
</tr>
</thead>
<tbody class="divide-y divide-default">
<tr
v-for="row in listData.items"
:key="row.id"
class="hover:bg-muted/20"
>
<td class="whitespace-nowrap px-4 py-3 text-xs text-muted sm:px-6">
{{ formatTime(row.createdAt) }}
</td>
<td
v-if="isAdmin"
class="px-4 py-3 text-xs"
>
{{ row.username ?? '—' }}
</td>
<td class="px-4 py-3">
<UBadge
:color="actionColor(row.action)"
variant="subtle"
size="xs"
>
<UIcon
:name="actionIcon(row.action)"
class="mr-1 size-3"
/>
{{ row.action === 'upload' ? t('logs.actionUpload') : t('logs.actionDelete') }}
</UBadge>
</td>
<td class="px-4 py-3">
<UBadge
color="neutral"
variant="subtle"
size="xs"
>
{{ sourceLabel(row.source) }}
</UBadge>
</td>
<td class="px-4 py-3 text-xs">
<span
v-if="row.storage"
class="inline-flex max-w-[8rem] items-center gap-1 truncate"
:title="row.storage.name"
>
<UIcon
:name="storageIcon(row.storage)"
class="size-3.5 shrink-0 opacity-70"
/>
<span class="truncate">{{ row.storage.name }}</span>
</span>
<span
v-else
class="text-muted"
>—</span>
</td>
<td
class="hidden max-w-[12rem] truncate px-4 py-3 md:table-cell"
:title="row.originalName"
>
{{ row.originalName }}
</td>
<td class="hidden px-4 py-3 font-mono text-xs text-muted lg:table-cell">
{{ folderFromKey(row.key) }}
</td>
<td class="whitespace-nowrap px-4 py-3 tabular-nums text-muted">
{{ formatFileSize(row.size) }}
</td>
<td class="hidden px-4 py-3 xl:table-cell">
<div class="flex max-w-[16rem] items-center gap-1">
<a
v-if="row.action === 'upload'"
:href="imageUrl(row.key)"
target="_blank"
rel="noopener noreferrer"
class="truncate font-mono text-xs text-primary hover:underline"
:title="row.key"
>
{{ row.key }}
</a>
<span
v-else
class="truncate font-mono text-xs text-dimmed"
:title="row.key"
>
{{ row.key }}
</span>
<CopyButton
icon="i-lucide-copy"
icon-only
:label="t('common.copy')"
:value="row.key"
:success-title="t('copy.copiedUrl')"
/>
</div>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<div
v-else
class="px-4 py-16 text-center text-sm text-muted sm:px-6"
>
{{ t('logs.empty') }}
</div>
<div
v-if="listData && listData.total > 0"
class="border-t border-default px-4 py-4 sm:px-6"
>
<PaginationBar
:page="listData.page"
:total-pages="listData.totalPages"
:total="listData.total"
:unit="t('logs.entriesUnit')"
:loading="loading"
@update:page="handlePageChange"
/>
</div>
</section>
</AppShell>
</div>
<div />
</template>
+39 -4
View File
@@ -2,9 +2,10 @@
import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png'
import { isPasswordValid } from '~/utils/password-strength'
import type { LoginVerificationPayload } from '~/types/auth'
const router = useRouter()
const { register, fetchStatus } = useAuth()
const { register, fetchStatus, authStatus } = useAuth()
const toast = useToast()
const { t } = useI18n()
@@ -12,14 +13,34 @@ const username = ref('')
const password = ref('')
const confirmPassword = ref('')
const loading = ref(false)
const verificationRef = ref<{ reset: () => Promise<void> } | null>(null)
const verificationPayload = ref<LoginVerificationPayload | null>(null)
const loginVerification = computed(() =>
authStatus.value?.loginVerification ?? { method: 'slider' as const }
)
const canSubmit = computed(() =>
Boolean(username.value && password.value && confirmPassword.value)
Boolean(verificationPayload.value)
&& Boolean(username.value && password.value && confirmPassword.value)
&& password.value === confirmPassword.value
&& isPasswordValid(password.value)
&& AUTH_USERNAME_PATTERN.test(username.value.trim())
)
function onVerificationVerified(payload: LoginVerificationPayload) {
verificationPayload.value = payload
}
function onVerificationCleared() {
verificationPayload.value = null
}
async function resetVerification() {
verificationPayload.value = null
await verificationRef.value?.reset()
}
onMounted(async () => {
const status = await fetchStatus()
if (!status.initialized && !status.legacyMode) {
@@ -32,7 +53,7 @@ onMounted(async () => {
})
async function submit() {
if (!canSubmit.value || loading.value) return
if (!canSubmit.value || loading.value || !verificationPayload.value) return
if (password.value !== confirmPassword.value) {
toast.add({ title: t('auth.passwordMismatch'), color: 'error' })
@@ -41,11 +62,16 @@ async function submit() {
loading.value = true
try {
const result = await register(username.value.trim(), password.value)
const result = await register(
username.value.trim(),
password.value,
verificationPayload.value
)
if (result.ok) {
toast.add({ title: t('auth.registerSuccess'), color: 'success' })
await router.replace('/')
} else {
await resetVerification()
toast.add({ title: result.error, color: 'error' })
}
} finally {
@@ -142,6 +168,15 @@ async function submit() {
/>
</div>
<LoginVerification
ref="verificationRef"
:method="loginVerification.method"
:turnstile-site-key="loginVerification.turnstileSiteKey"
:cap-api-endpoint="loginVerification.capApiEndpoint"
@verified="onVerificationVerified"
@cleared="onVerificationCleared"
/>
<UButton
type="submit"
:label="t('auth.register')"
File diff suppressed because it is too large. Load diff
+47 -1
View File
@@ -2,6 +2,7 @@
import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png'
import { isPasswordValid } from '~/utils/password-strength'
import { willActivateDomainSeparation } from '~/utils/domain-separation'
const route = useRoute()
const router = useRouter()
@@ -26,6 +27,15 @@ const domainSeparation = ref(false)
const siteBaseUrl = ref('')
const imageBaseUrl = ref('')
const loading = ref(false)
const domainSeparationConfirmOpen = ref(false)
const domainSeparationWouldActivate = computed(() =>
willActivateDomainSeparation(
domainSeparation.value,
siteBaseUrl.value,
imageBaseUrl.value
)
)
const canSubmit = computed(() => {
if (!username.value || !password.value || !confirmPassword.value) return false
@@ -33,7 +43,7 @@ const canSubmit = computed(() => {
if (!isPasswordValid(password.value)) return false
if (!AUTH_USERNAME_PATTERN.test(username.value.trim())) return false
if (domainSeparation.value) {
return Boolean(siteBaseUrl.value.trim() && imageBaseUrl.value.trim())
if (!siteBaseUrl.value.trim() || !imageBaseUrl.value.trim()) return false
}
return true
})
@@ -63,6 +73,18 @@ async function submit() {
return
}
if (domainSeparationWouldActivate.value) {
domainSeparationConfirmOpen.value = true
return
}
await performSubmit()
}
async function performSubmit() {
domainSeparationConfirmOpen.value = false
if (!canSubmit.value || loading.value) return
loading.value = true
try {
const payload = {
@@ -248,5 +270,29 @@ async function submit() {
/>
</form>
</div>
<UModal
:open="domainSeparationConfirmOpen"
:title="t('domainSeparationConfirm.title')"
:description="t('domainSeparationConfirm.description')"
@update:open="(v) => { if (!v) domainSeparationConfirmOpen = false }"
>
<template #footer>
<div class="flex justify-end gap-2">
<UButton
:label="t('common.cancel')"
color="neutral"
variant="outline"
@click="() => { domainSeparationConfirmOpen = false }"
/>
<UButton
:label="t('domainSeparationConfirm.confirm')"
color="warning"
:loading="loading"
@click="performSubmit"
/>
</div>
</template>
</UModal>
</div>
</template>
+60 -49
View File
@@ -21,6 +21,11 @@ const deleteTarget = ref<StorageBackendItem | null>(null)
const deleteConfirmName = ref('')
const deleting = ref(false)
const defaultBackendName = computed(() => {
const backend = storageData.value?.backends.find(item => item.isDefault)
return backend?.name ?? t('storage.backendLocal')
})
async function loadStorage() {
loading.value = true
try {
@@ -43,6 +48,7 @@ function buildPatchBody(payload: StorageFormPayload) {
const quotaBytes = quotaToBytes(payload.quotaValue, payload.quotaUnit)
const body: Record<string, unknown> = {
name: payload.name,
provider: payload.provider,
servingMode: payload.servingMode,
publicUrl: payload.publicUrl,
quotaBytes,
@@ -232,59 +238,59 @@ watch(isAuthenticated, async (authed) => {
<AdminLoginGate v-else-if="!isAuthenticated" />
<AppShell v-else-if="isAdmin">
<section class="overflow-hidden rounded-2xl border border-default bg-elevated shadow-sm">
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default px-5 py-4 sm:px-6">
<div class="flex items-start gap-2">
<UIcon
name="i-lucide-hard-drive"
class="mt-0.5 size-5 shrink-0 text-primary"
/>
<div>
<h1 class="text-base font-semibold">
{{ t('storage.pageTitle') }}
</h1>
<p class="mt-0.5 text-xs text-muted">
{{ t('storage.pageSubtitle') }}
</p>
</div>
</div>
<UButton
:label="t('storage.addBackend')"
icon="i-lucide-plus"
size="sm"
:disabled="storageData?.envOverride"
@click="openCreate"
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<h1 class="text-2xl font-semibold tracking-tight">
{{ t('storage.pageTitle') }}
</h1>
<p class="text-sm text-muted">
{{ t('storage.pageSubtitle') }}
</p>
</div>
<UButton
:label="t('storage.addBackend')"
icon="i-lucide-plus"
size="sm"
:disabled="storageData?.envOverride"
@click="openCreate"
/>
</div>
<section class="mt-5 space-y-5">
<UAlert
v-if="storageData?.envOverride"
color="warning"
variant="subtle"
:title="t('storage.envOverride')"
icon="i-lucide-triangle-alert"
/>
<div
v-if="loading"
class="flex justify-center py-16"
>
<UIcon
name="i-lucide-loader-circle"
class="size-6 animate-spin text-muted"
/>
</div>
<div class="p-5 sm:p-6">
<UAlert
v-if="storageData?.envOverride"
color="warning"
variant="subtle"
class="mb-5"
:title="t('storage.envOverride')"
icon="i-lucide-triangle-alert"
<template v-else-if="storageData">
<StorageOverview
:backends="storageData.backends"
:loading="loading"
/>
<p class="mb-5 text-xs text-muted">
{{ t('storage.switchHint') }}
</p>
<UAlert
v-if="!storageData.envOverride"
color="success"
variant="subtle"
icon="i-lucide-info"
:description="t('storage.defaultStorageTip', { name: defaultBackendName })"
/>
<div
v-if="loading"
class="flex justify-center py-16"
>
<UIcon
name="i-lucide-loader-circle"
class="size-6 animate-spin text-muted"
/>
</div>
<div
v-else-if="storageData"
class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3"
>
<div class="grid grid-cols-1 gap-4 xl:grid-cols-2">
<StorageBackendCard
v-for="backend in storageData.backends"
:key="backend.id"
@@ -298,11 +304,16 @@ watch(isAuthenticated, async (authed) => {
@delete="confirmDelete(backend)"
/>
</div>
</div>
<StorageSupportedBackends />
</template>
</section>
</AppShell>
<UModal v-model:open="formOpen">
<UModal
v-model:open="formOpen"
:ui="{ content: 'max-w-2xl sm:max-w-3xl' }"
>
<template #content>
<div class="p-5 sm:p-6">
<h2 class="mb-4 text-base font-semibold">
+19
View File
@@ -0,0 +1,19 @@
export type LoginVerificationMethod = 'slider' | 'turnstile' | 'cap'
export interface LoginVerificationPublicConfig {
method: LoginVerificationMethod
turnstileSiteKey?: string
capApiEndpoint?: string
}
export type LoginVerificationPayload = {
method: 'slider'
captchaId: string
captchaPosition: number
} | {
method: 'turnstile'
turnstileToken: string
} | {
method: 'cap'
capToken: string
}
+5
View File
@@ -0,0 +1,5 @@
export type SettingsTab = 'basic' | 'domains' | 'access' | 'logs'
export const ADMIN_SETTINGS_TABS: SettingsTab[] = ['basic', 'domains', 'access', 'logs']
export const USER_SETTINGS_TABS: SettingsTab[] = ['logs']
+24
View File
@@ -0,0 +1,24 @@
export function hostnameFromBaseUrl(value: string): string | null {
const trimmed = value.trim()
if (!trimmed) return null
try {
return new URL(trimmed).hostname.toLowerCase()
} catch {
return null
}
}
/** 勾选分离且网站域、图片域主机名不同 → 保存后将启用双域名中间件隔离 */
export function willActivateDomainSeparation(
enabled: boolean,
siteBaseUrl: string,
imageBaseUrl: string
): boolean {
if (!enabled) return false
const site = siteBaseUrl.trim()
const image = imageBaseUrl.trim()
if (!site || !image) return false
const siteHost = hostnameFromBaseUrl(site)
const imageHost = hostnameFromBaseUrl(image)
return Boolean(siteHost && imageHost && siteHost !== imageHost)
}
+1 -1
View File
@@ -10,7 +10,7 @@ services:
- "6892:6892"
# 首次访问 Web 引导创建管理员,无需预先配置环境变量
# 可选:environment 中设置 API_UPLOAD_TOKEN、ALLOWED_REFERER_HOSTS 等
# 运维:docker exec pichost reset-password | migrate [--apply]
# 运维:docker exec pichost reset-password | migrate [--apply] | slider | clear-domains [--site]
volumes:
# 冒号左边改成 NAS 上的实际存图目录(飞牛示例:/vol1/1000/pichost-data)
- ./data:/data
+8
View File
@@ -9,4 +9,12 @@ if [ "$1" = "migrate" ]; then
exec node /app/server/cli/migrate-to-single-images.mjs "${@:2}"
fi
if [ "$1" = "slider" ]; then
exec node /app/server/cli/slider.mjs "${@:2}"
fi
if [ "$1" = "clear-domains" ]; then
exec node /app/server/cli/clear-domains.mjs "${@:2}"
fi
exec node /app/.output/server/index.mjs "$@"
+1 -1
View File
@@ -1,6 +1,6 @@
# API
PicHost exposes REST endpoints and a Twikoo-compatible upload. After deployment, open the in-app **API** page for your token and copyable cURL snippets.
PicHost exposes REST endpoints and a Twikoo-compatible upload. After sign-in, open **API** in the nav: a sidebar lists endpoints and token controls, the center shows parameters and copyable cURL, and the right panel supports **live debugging**.
## Authentication
+39
View File
@@ -4,6 +4,45 @@ Version history and notable changes. The full log is also in the repo root [CHAN
---
## [1.2.8] — 2026-09-04
### Improved
- **Dual-domain**: confirm dialog on save/setup with lockout risks and `clear-domains` recovery; no longer blocks save based on current Host
### Added
- **Ops CLI**: `clear-domains` clears site/image URL settings from DB (`docker exec pichost clear-domains`)
### Docs
- FAQ and dual-domain / reverse-proxy guides updated with recovery steps
## [1.2.7] — 2026-09-03
### Added
- **Login verification**: slider, Cloudflare Turnstile, or Cap on login/register; configure under Settings → Access
- **Ops CLI**: `slider` resets verification to the local slider (`docker exec pichost slider`)
### Improved
- Login captcha reloads correctly after logout
## [1.2.6] — 2026-09-01
### Added
- **Admin UI**: redesigned Settings, API, Gallery, and Storage pages; API page includes live debugging
- **Gallery filter**: filter by storage backend
- **Storage IDs**: new R2 / COS / OSS / S3 backends get `r2-*`, `cos-*`, `oss-*`, or `s3-*` prefixes
### Improved
- Activity log table styling and path truncation
- Storage backend card metadata layout
- Docs site and README screenshots updated
## [1.2.5] — 2026-08-31
### Added
+15 -1
View File
@@ -1,6 +1,6 @@
# Environment variables
Configure PicHost via environment variables (Docker / `.env`) or the in-app **Settings** page. Most values prefer **SQLite** when saved; some env vars override or lock UI editing.
Configure PicHost via environment variables (Docker / `.env`) or the in-app **Settings** page. Admins use **Settings** (`/settings`) with sidebar sections **Basic**, **Domains & paths**, **Access control**, and **Activity log**. Most values prefer **SQLite** when saved; some env vars override or lock UI editing.
## Priority overview
@@ -13,6 +13,7 @@ Configure PicHost via environment variables (Docker / `.env`) or the in-app **Se
| Short image links | SQLite → env → default false | No |
| Date-based paths | SQLite → env → default true | No |
| Global auto-delete days | SQLite → env → default 0 | No |
| Login verification | SQLite (Settings → Access control) | No |
## Variables
@@ -64,6 +65,18 @@ Delete images older than N days globally; `0` disables. Affects **new uploads af
Local dev only: `true` bypasses login. Never use in production.
### Login verification (Settings only)
Configure under **Settings → Access control** (stored in SQLite; no env vars):
| Method | Notes |
| ------ | ----- |
| **Local slider** (default) | No third-party service |
| **Cloudflare Turnstile** | Site key + secret key |
| **Cap** | API endpoint + secret |
Login and registration share the same method. If misconfigured: `docker exec pichost slider` (or `npm run slider`) resets to the slider.
### Storage backends (optional)
Admins usually add backends in **Storage** UI; env vars such as `STORAGE_BACKEND=s3` and `S3_*` are also supported. See [Storage](./storage.md).
@@ -99,5 +112,6 @@ Restart the container after changing env vars.
| Date-based paths | `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` |
| WebP quality | `WEBP_QUALITY` |
| Auto-delete | `AUTO_DELETE_DAYS` |
| Login verification | (Settings → Access control only) |
Template: [`.env.example`](https://github.com/O96u/PicHost/blob/main/.env.example) in the repo root.
+15 -4
View File
@@ -69,10 +69,21 @@ This is independent of hyphenated or long domain names. Older versions did not b
1. Configure `server_name` only for the site and image hosts; add a **default server** to reject other Host values and bare IP access (see Nginx example above; complements app-layer blocking)
2. With Cloudflare **orange-cloud** DNS, restrict the origin firewall to **[Cloudflare IP ranges](https://www.cloudflare.com/ips/)** so traffic cannot bypass the CDN
3. Sign in only on the **site hostname** from Settings; do not mix `localhost`, IP, or unlisted domains
4. Do **not** put Cloudflare Pages / Workers in front of PicHost as a **full-site reverse proxy** (`IMAGE_BASE_URL` may point at a CDN URL, but the app itself should run on Docker/VPS)
5. If you must proxy at the edge, preserve the client **`Host` or `X-Forwarded-Host`** or host isolation will fail
6. PicHost **cannot** run as-is on Pages/Workers (needs `node-server`, SQLite, `sharp`, local `data/`). Keep Docker/VPS; use orange-cloud DNS and optional R2 storage on CF
3. **Before saving**, read the risk confirmation in Settings / setup; saving via IP, LAN, or a proxy that does not forward Host correctly may lock you out — see **Recovery when locked out** below
4. Sign in only on the **site hostname** from Settings; do not mix `localhost`, IP, or unlisted domains
5. Do **not** put Cloudflare Pages / Workers in front of PicHost as a **full-site reverse proxy** (`IMAGE_BASE_URL` may point at a CDN URL, but the app itself should run on Docker/VPS)
6. If you must proxy at the edge, preserve the client **`Host` or `X-Forwarded-Host`** (Lucky/NPM “force hostname” must match PicHost settings) or isolation fails or you get locked out after save
7. PicHost **cannot** run as-is on Pages/Workers (needs `node-server`, SQLite, `sharp`, local `data/`). Keep Docker/VPS; use orange-cloud DNS and optional R2 storage on CF
### Recovery when locked out
If IP / LAN access returns 404 after a bad save:
```bash
docker exec pichost clear-domains
```
Local: `npm run clear-domains`. Then reconfigure using the site hostname and verify proxy `Host` headers.
### Cloudflare orange cloud (incl. preferred edge IPs)
+18
View File
@@ -19,6 +19,24 @@ Local: `npm run reset-password`. See [Quick start](./getting-started.md#forgot-p
Check the **Referer whitelist** (`ALLOWED_REFERER_HOSTS` or Settings). Referring sites must be listed; PicHost’s own hosts and dual-domain pair are allowed automatically.
## Admin 404 / locked out after dual-domain setup?
**Cause:** With dual-domain enabled, PicHost returns **404 for every request** whose Host is not the configured site or image hostname. Common triggers:
1. Saving dual-domain URLs while browsing via IP or an internal address
2. Reverse proxy “force hostname” or wrong `Host` header so PicHost sees a different host than configured
**Recovery (when locked out):**
```bash
docker exec pichost clear-domains
# Site URL only: docker exec pichost clear-domains --site
```
Local dev: `npm run clear-domains`. Then reopen admin via your previous IP/internal URL and reconfigure using the [dual-domain guide](./domain-separation.md#middleware-isolation-and-third-hosts).
**Prevention:** Read the risk confirmation when saving dual-domain settings; proxy must send `Host $host` and `X-Forwarded-Proto`. See [Dual-domain separation](./domain-separation.md#middleware-isolation-and-third-hosts).
## Why can admin load on pages.dev / workers.dev / IP with dual-domain?
**From v1.2.2:** when dual-domain is on, PicHost returns **404** for Host values **other than** the configured site and image hostnames (`localhost` / `127.0.0.1` exempt in development). See [Changelog](./changelog.md#1-2-2-2026-08-30).
+25 -3
View File
@@ -35,15 +35,27 @@ See `docker-compose.yml` in the repository.
1. Open your instance URL (Docker default `http://<host>:6892`).
2. Complete `/setup` with admin username and password.
3. (Optional) Configure site URL, image URL, Referer rules — see [Environment variables](./configuration.md) and [Dual-domain separation](./domain-separation.md).
4. Upload from the home page; admins can open **Storage**, **Settings**, and **API**.
4. Upload from the home page; use the top nav for **Gallery**, **Storage** (admin), **Settings**, and **API**.
## Sign in
Management pages (upload, stats, settings, etc.) require login. Enter username and password, **drag the slider to align with the gap**, then click **Sign in**.
Management pages (upload, gallery, settings, etc.) require login. Enter username and password, complete the verification challenge, then click **Sign in**.
The default is a **local slider** (align the thumb with the gap). Admins can switch to **Cloudflare Turnstile** or **Cap** under **Settings → Access control**, with the matching site key / secret or API endpoint.
![Login](/screenshots/login.png)
If registration is enabled, create an account from the register page. Legacy deployments may still use a secret key (see the on-screen hint).
If registration is enabled, create an account from the register page (same verification). Legacy deployments may still use a secret key (see the on-screen hint).
### Locked out of verification
If Turnstile / Cap is misconfigured and you cannot sign in, reset to the local slider on the server:
```bash
docker exec pichost slider
```
Local dev: `npm run slider`
## Forgot password
@@ -58,6 +70,16 @@ A random password is printed. Change it after login.
Local dev: `npm run reset-password` or `npm run reset-password -- <username>`
## Dual-domain lockout
If dual-domain is enabled and IP / LAN access returns 404:
```bash
docker exec pichost clear-domains
```
Local: `npm run clear-domains`. See [FAQ — Admin 404 after dual-domain setup](./faq.md#admin-404--locked-out-after-dual-domain-setup).
## Upgrading to v1.2.0
If `data/` has legacy top-level folders next to `images` (e.g. `blog/`, `twikoo/`), read the [v1.2 migration guide](./migration.md) first.
+5 -9
View File
@@ -12,18 +12,14 @@ Welcome to the PicHost user guide. This site is the single source of truth; the
## Screenshots
**main** has no public demo. Below are v1.2.0 product screenshots.
**main** has no public demo. Below are current product screenshots (v1.2.5+).
| First-time setup | Login |
| :--------------: | :---: |
| ![Setup](/screenshots/setup.png) | ![Login](/screenshots/login.png) |
| API | Stats & gallery |
| :-: | :-------------: |
| ![API](/screenshots/api.png) | ![Stats & gallery](/screenshots/stats.png) |
| API | Gallery |
| :-: | :-----: |
| ![API](/screenshots/api.png) | ![Gallery](/screenshots/gallery.png) |
| Storage | Settings |
| :-----: | :------: |
| :-----: | :-------: |
| ![Storage](/screenshots/storage.png) | ![Settings](/screenshots/settings-en.png) |
| Activity log |
+2
View File
@@ -28,6 +28,8 @@ Open `http://localhost:3000/setup` to create the admin account. Data directory d
| `npm run typecheck` | Type check |
| `npm test` | Unit tests |
| `npm run reset-password` | Reset password (optional username) |
| `npm run slider` | Reset login verification to local slider |
| `npm run clear-domains` | Clear site/image URL settings from DB (recover from dual-domain lockout) |
| `npm run migrate` | Preview legacy dir migration (`-- --apply` to run) |
## Dev-only variables
+3 -1
View File
@@ -57,12 +57,14 @@ See [Cloudflare deployment](./cloudflare-deployment.md).
## Origin hardening (dual-domain)
PicHost middleware does **not** reject unlisted Host values. Complement with:
Complement PicHost middleware with:
1. **`server_name` allowlist** — site + image hosts only; `default_server` blocks bare IP and unknown Host
2. **Do not expose 6892 on the public Internet** — only local reverse proxy; public 80/443 only
3. **Orange cloud** — origin firewall limited to Cloudflare IP ranges
**From v1.2.2**, when dual-domain is active PicHost also returns **404 at the app layer** for Host values other than the configured site and image names (complementing, not replacing, a default server block). If misconfiguration locks you out, run `docker exec pichost clear-domains` — see [FAQ](./faq.md#admin-404--locked-out-after-dual-domain-setup).
## Caddy
```caddy
+4 -2
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.
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.
![Storage management](/screenshots/storage.png)
@@ -25,6 +25,8 @@ All **keys** start with `images/`. The upload API does **not** accept a `folder`
3. Enter connection details (bucket, endpoint, keys).
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).
### Cloudflare R2
| Field | Value |
@@ -52,7 +54,7 @@ Copied links use **IMAGE_BASE_URL**. “Hide folder prefix” may shorten URLs;
## Usage & gallery filter
- Per-backend usage on the Storage page
- Gallery filter by backend (admin)
- Gallery filters by **storage backend** and **upload source**; grid/list view toggle
## Backup
+7 -5
View File
@@ -12,12 +12,13 @@ PicHost uses role-based access control (RBAC): **admin** and **user**. Enforceme
| Storage management (`/storage`) | ✓ | — |
| System settings (`/settings`) | ✓ | — |
| Allow registration | ✓ | — |
| Login verification (slider / Turnstile / Cap) | ✓ | — |
| Global API token | ✓ | — |
| Personal API token | ✓ | ✓ |
| Stats (incl. user count) | ✓ | partial |
| Activity log | ✓ | — |
| Gallery stats overview (incl. user count) | ✓ | partial |
| Activity log (Settings → Activity log) | ✓ | — |
Regular users see **API**, **Stats** in the nav; user menu: **Change password**, **Sign out**.
Regular users see **API**, **Gallery** in the nav; user menu: **Change password**, **Sign out**.
## Auth scenarios
@@ -34,12 +35,13 @@ Regular users see **API**, **Stats** in the nav; user menu: **Change password**,
- By default only admins create users; **allow registration** is an admin setting
- Passwords hashed with scrypt
- Web login requires a slider captcha (align the thumb with the gap)
- Web login/register requires verification: local slider by default; admins can switch to Turnstile or Cap under **Settings → Access control**
- If verification is misconfigured: `docker exec pichost slider` resets to the local slider
- Login rate limiting
## Upload preferences & auto-delete
- **Upload preferences** (home card flip): client compression, auto-copy links, per user
- **Upload preferences**: admins configure client compression and auto-copy in **Settings → Basic**; regular users can flip the home upload card for personal preferences
- **Auto-delete**: global (admin) and per-user policies; affects **new uploads after enable** only
## API tokens
+1 -1
View File
@@ -1,6 +1,6 @@
# API
PicHost 提供 REST 接口与 Twikoo 兼容端点。部署后登录 **API** 页可查看当前 Token 与可复制 cURL 示例。
PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API** 页:左侧为接口目录与 Token 管理,中间为参数说明与 cURL 示例,右侧可 **在线调试** 发送请求。
## 鉴权
+39
View File
@@ -4,6 +4,45 @@ PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [C
---
## [1.2.8] — 2026-09-04
### 改进
- **双域名**:保存 / 初始化时弹出风险确认(含锁死说明与 `clear-domains` 恢复方式),不再强制校验当前 Host
### 新增
- **运维 CLI**:`clear-domains` 清除数据库域名配置(`docker exec pichost clear-domains`)
### 文档
- FAQ 与双域名、反代文档补充恢复步骤
## [1.2.7] — 2026-09-03
### 新增
- **登录验证**:登录/注册支持本地滑块、Cloudflare Turnstile、Cap;在「设置 → 访问控制」配置
- **运维 CLI**:`slider` 将验证方式重置为本地滑块(`docker exec pichost slider`)
### 改进
- 登出后登录页验证码可正常重新加载
## [1.2.6] — 2026-09-01
### 新增
- **管理界面**:设置、API、图库、存储页 UI 重构;API 页支持在线调试
- **图库筛选**:按存储后端筛选
- **存储标识**:新建 R2 / COS / OSS / S3 后端按类型生成 `r2-*`、`cos-*`、`oss-*`、`s3-*` 前缀
### 改进
- 操作日志表格样式与路径截断
- 存储后端卡片信息行布局
- 文档站与 README 截图更新
## [1.2.5] — 2026-08-31
### 新增
+15 -3
View File
@@ -1,6 +1,4 @@
# 环境变量
PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配置。多数项 **SQLite 优先**;部分项环境变量可覆盖或锁定后台编辑。
PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配置。管理员在 **设置与偏好**(`/settings`)左侧切换 **基础设置**、**域名与路径**、**访问控制**、**操作日志**;多数项 **SQLite 优先**;部分项环境变量可覆盖或锁定后台编辑。
## 优先级总览
@@ -13,6 +11,7 @@ PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配
| 简短图片链接 | SQLite → 环境变量 → 默认 false | 否 |
| 按年/月分组存储 | SQLite → 环境变量 → 默认 true | 否 |
| 全局自动删除天数 | SQLite → 环境变量 → 默认 0 | 否 |
| 登录人机验证 | SQLite(设置 → 访问控制) | 否 |
## 变量说明
@@ -64,6 +63,18 @@ PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配
仅本地开发:`true` 绕过登录验证。生产环境勿用。
### 登录人机验证(仅后台设置)
在 **设置 → 访问控制** 配置,存入 SQLite,无对应环境变量:
| 方式 | 说明 |
| ---- | ---- |
| **本地滑块**(默认) | 无需第三方服务 |
| **Cloudflare Turnstile** | 填写 Site Key 与 Secret Key |
| **Cap** | 填写 API Endpoint 与 Secret |
登录与注册共用同一验证方式。若第三方配置错误导致无法登录,执行 `docker exec pichost slider`(或 `npm run slider`)恢复为本地滑块。
### 存储后端(可选)
管理员通常在 **存储** 页添加后端;也可用环境变量引导(如 `STORAGE_BACKEND=s3` 与 `S3_*`)。详见 [存储](./storage.md)。
@@ -99,5 +110,6 @@ services:
| 按年/月分组 | `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` |
| WebP 质量 | `WEBP_QUALITY` |
| 自动删除 | `AUTO_DELETE_DAYS` |
| 登录验证 | (仅后台 **设置 → 访问控制**) |
完整模板见仓库根目录 [`.env.example`](https://github.com/O96u/PicHost/blob/main/.env.example)。
+15 -4
View File
@@ -72,10 +72,21 @@ PicHost 根据请求 **Host**(反代会转发为 `X-Forwarded-Host`,应用
1. 反代层仅为网站域、图片域配置 `server_name`,并增加 **default server** 拒绝其它 Host 与裸 IP(见上方 Nginx 示例,与应用层拦截互补)
2. 使用 Cloudflare **橙云** 时,源站防火墙 **仅放行 [Cloudflare IP 段](https://www.cloudflare.com/ips/)**,避免绕过 CDN 直连源站
3. **仅使用** 设置中的网站域名登录后台,不要用 `localhost`、IP 或未配置的域名混用
4. **不要** 用 Cloudflare Pages / Workers 对 PicHost **整站反代**(会多出 `pages.dev` / `workers.dev` 等第三入口;`IMAGE_BASE_URL` 可填 CDN 公网地址,但应用本体应 Docker/VPS 部署)
5. 若必须在边缘做反代,须保留客户端 **`Host` 或 `X-Forwarded-Host`**,否则 Host 隔离会失效
6. PicHost **不能** 作为 Node 应用直接部署到 Pages/Workers(依赖 `node-server`、SQLite、`sharp` 与本地 `data/`);应用请继续 Docker/VPS 部署,CF 侧用橙云 DNS + 可选 R2 存储即可
3. **保存前**阅读设置 / 初始化页的风险确认;若通过 IP、内网或未正确传递 Host 的反代保存,可能锁死后台;恢复见下方「已锁死时的恢复」
4. **仅使用** 设置中的网站域名登录后台,不要用 `localhost`、IP 或未配置的域名混用
5. **不要** 用 Cloudflare Pages / Workers 对 PicHost **整站反代**(会多出 `pages.dev` / `workers.dev` 等第三入口;`IMAGE_BASE_URL` 可填 CDN 公网地址,但应用本体应 Docker/VPS 部署)
6. 若必须在边缘做反代,须保留客户端 **`Host` 或 `X-Forwarded-Host`**(Lucky/NPM「强制域名」须与 PicHost 配置一致),否则 Host 隔离会失效或保存后被锁死
7. PicHost **不能** 作为 Node 应用直接部署到 Pages/Workers(依赖 `node-server`、SQLite、`sharp` 与本地 `data/`);应用请继续 Docker/VPS 部署,CF 侧用橙云 DNS + 可选 R2 存储即可
### 已锁死时的恢复
若已误保存导致 IP / 内网地址全站 404:
```bash
docker exec pichost clear-domains
```
本地:`npm run clear-domains`。清除后请用网站域名重新配置,并确认反代 `Host` 头正确。
### Cloudflare 橙云(含 DNS 优选)
+18
View File
@@ -20,6 +20,24 @@ docker exec pichost reset-password 用户名
检查 **防盗链白名单**(`ALLOWED_REFERER_HOSTS` 或设置页)。引用图片的站点域名需在白名单中;PicHost 自身域名与双域名场景下的网站域、图片域会自动放行。
## 双域名配置后后台 404 / 进不去?
**原因:** 启用双域名后,PicHost 会对**未配置的网站域、图片域之外**的 Host 全站返回 404。常见触发方式:
1. 通过 IP 或内网地址打开设置,保存了公网网站域 / 图片域
2. 反代「强制域名」或 Host 头配置错误,PicHost 收到的 Host 与设置中的网站域不一致
**恢复(已锁死时):**
```bash
docker exec pichost clear-domains
# 仅清除网站域:docker exec pichost clear-domains --site
```
本地开发:`npm run clear-domains`。执行后用原来的 IP / 内网地址刷新即可重新进入后台,再按文档正确配置双域名。
**预防:** 保存双域名时注意确认框中的风险提示;反代须 `proxy_set_header Host $host;` 并保留 `X-Forwarded-Proto`。详见 [双域名分离](./domain-separation.md#中间件隔离与第三-host)。
## 双域名下为什么用 pages.dev / workers.dev / IP 也能进后台?
**v1.2.2 起:** 双域名开启时,PicHost 中间件会对**未配置的网站域、图片域之外**的 Host 返回 **404**(开发环境 `localhost` / `127.0.0.1` 例外)。详见 [更新日志](./changelog.md#1-2-2-2026-08-30)。
+25 -3
View File
@@ -35,15 +35,27 @@ docker compose up -d
1. 访问实例 URL(Docker 默认 `http://<主机>:6892`)。
2. 在 `/setup` 填写管理员用户名与密码。
3. (可选)配置网站域名、图片域名、防盗链等 — 详见 [环境变量](./configuration.md) 与 [双域名分离](./domain-separation.md)。
4. 登录后可在首页上传图片;管理员可进入 **存储**、**设置**、**API** 页。
4. 登录后可在首页上传图片;顶栏可进入 **图库**、**存储**(管理员)、**设置**、**API**。
## 登录
访问上传、统计、设置等管理页面前需登录。在登录卡片中填写用户名与密码,**拖动滑块对齐缺口**完成验证后点击 **登录**。
访问上传、图库、设置等管理页面前需登录。在登录卡片中填写用户名与密码,完成人机验证后点击 **登录**。
默认使用**本地滑块**(拖动滑块对齐缺口)。管理员可在 **设置 → 访问控制** 切换为 **Cloudflare Turnstile** 或 **Cap**,并填写对应 Site Key / Secret 或 API 端点。
![登录页](/screenshots/login.png)
若管理员开启了开放注册,可前往注册页创建账号。遗留部署仍可能使用密钥登录(见界面提示)。
若管理员开启了开放注册,可前往注册页创建账号(同样需完成人机验证)。遗留部署仍可能使用密钥登录(见界面提示)。
### 验证方式被锁死时
若 Turnstile / Cap 配置错误导致无法登录,可在服务器上重置为本地滑块:
```bash
docker exec pichost slider
```
本地开发:`npm run slider`
## 忘记密码
@@ -61,6 +73,16 @@ docker exec pichost reset-password 用户名
本地开发:`npm run reset-password` 或 `npm run reset-password -- 用户名`
## 双域名配置锁死
若启用双域名后通过 IP / 内网地址无法进入后台:
```bash
docker exec pichost clear-domains
```
本地:`npm run clear-domains`。详见 [常见问题 — 双域名配置后后台 404](./faq.md#双域名配置后后台-404-进不去)。
## 升级到 v1.2.0
若 `data/` 下存在与 `images` 并列的遗留目录(如 `blog/`、`twikoo/`),升级前请阅读 [v1.2 迁移指南](./migration.md)。
+7 -11
View File
@@ -12,19 +12,15 @@
## 截图预览
**main** 分支暂无公网演示,以下为 v1.2.0 产品界面。
**main** 分支暂无公网演示,以下为当前产品界面(v1.2.5+)。
| 首次设置 | 登录 |
| :------: | :--: |
| ![首次设置](/screenshots/setup.png) | ![登录](/screenshots/login.png) |
| API | 图库 |
| :-: | :-: |
| ![API](/screenshots/api.png) | ![图库](/screenshots/gallery.png) |
| API | 统计与图库 |
| :-: | :--------: |
| ![API](/screenshots/api.png) | ![统计与图库](/screenshots/stats.png) |
| 存储管理 | 系统设置 |
| :------: | :------: |
| ![存储管理](/screenshots/storage.png) | ![系统设置](/screenshots/settings.png) |
| 存储管理 | 设置与偏好 |
| :------: | :--------: |
| ![存储管理](/screenshots/storage.png) | ![设置与偏好](/screenshots/settings.png) |
| 操作日志 |
| :------: |
+2
View File
@@ -28,6 +28,8 @@ npm run dev
| `npm run typecheck` | 类型检查 |
| `npm test` | 单元测试 |
| `npm run reset-password` | 重置密码(可选用户名) |
| `npm run slider` | 将登录验证重置为本地滑块 |
| `npm run clear-domains` | 清除数据库中的网站域 / 图片域配置(双域名锁死时恢复) |
| `npm run migrate` | 预览遗留目录迁移(加 `-- --apply` 执行) |
## 开发专用环境变量
+1 -1
View File
@@ -63,7 +63,7 @@ IMAGE_BASE_URL=https://pic.example.com
2. **禁止公网暴露 6892** — 仅本机或内网反代访问;公网只开 80/443
3. **橙云时限制源站来源 IP** — 仅 Cloudflare 回源 IP 段
双域名场景下 PicHost **不会** 拒绝未配置的 Host;上述措施由运维层补齐。
**v1.2.2 起**,双域名开启时 PicHost 应用层也会对**未配置的网站域、图片域之外**的 Host 全站返回 404(与反代 default server 互补,而非替代)。误配置导致锁死时执行 `docker exec pichost clear-domains` 恢复,见 [常见问题](./faq.md#双域名配置后后台-404-进不去)。
## Caddy 示例
+4 -2
View File
@@ -1,6 +1,6 @@
# 存储
PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、腾讯云 COS、阿里云 OSS、AWS S3 等)。管理员在 **存储**(`/storage`)页管理后端;新上传写入 **默认后端**。
PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、腾讯云 COS、阿里云 OSS、AWS S3 等)。管理员在 **存储**(`/storage`)页管理后端;新上传写入 **默认后端**。页面顶部展示 **存储总览**(总量、已用、剩余、使用率与容量分布),下方为各后端卡片与支持的后端类型说明。
![存储管理](/screenshots/storage.png)
@@ -25,6 +25,8 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
3. 填写连接信息(桶名、Endpoint、Access Key 等)。
4. 保存后可 **设默认**,新上传将写入该后端。
新建对象存储后端的 **存储标识** 按类型自动生成前缀:本地为 `local`;R2 为 `r2-*`;COS 为 `cos-*`;OSS 为 `oss-*`;AWS S3 及自定义 S3 兼容为 `s3-*`(创建后不可修改,图片索引会引用该 ID)。
### Cloudflare R2 要点
| 项 | 值 |
@@ -54,7 +56,7 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
## 用量与筛选
- 存储页展示各后端用量(本地扫描目录,对象存储查询 API)
- 图库可按存储后端筛选(管理员)
- 图库可按 **存储后端**、**上传来源** 筛选,支持网格/列表视图切换
## 备份
+7 -5
View File
@@ -12,12 +12,13 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
| 存储后端管理(`/storage`) | ✓ | — |
| 系统设置(`/settings`) | ✓ | — |
| 开放注册开关 | ✓ | — |
| 登录人机验证方式(滑块 / Turnstile / Cap) | ✓ | — |
| 全局 API Token 管理 | ✓ | — |
| 个人 API Token | ✓ | ✓ |
| 统计页(含注册用户数) | ✓ | 部分 |
| 操作日志 | ✓ | — |
| 图库统计概览(含注册用户数) | ✓ | 部分 |
| 操作日志(设置 → 操作日志) | ✓ | — |
普通用户顶栏:**API**、**统计**;用户菜单:**修改密码**、**退出登录**。
普通用户顶栏:**API**、**图库**;用户菜单:**修改密码**、**退出登录**。
## 鉴权场景
@@ -34,12 +35,13 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
- 默认仅管理员可创建用户;管理员可在设置中 **开放注册**
- 密码使用 scrypt 哈希存储
- Web 登录需先完成滑动拼图验证(拖动滑块对齐缺口)
- Web 登录/注册需完成人机验证:默认本地滑块;管理员可在 **设置 → 访问控制** 切换 Turnstile 或 Cap
- 验证配置错误无法登录时:`docker exec pichost slider` 重置为本地滑块
- 登录失败有速率限制
## 上传偏好与自动删除
- **上传偏好**(首页卡片翻转):客户端预压缩、自动复制链接等,按用户保存
- **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好
- **自动删除**:管理员可设全局策略;用户可设个人策略。启用后仅影响 **之后新上传** 的图片
## API Token 说明
Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

After

Width:  |  Height:  |  Size: 125 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 55 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 70 KiB

+208 -5
View File
@@ -67,6 +67,11 @@
"loginFailed": "Sign-in failed. Check username and password",
"captchaHint": "Drag the slider to the slot",
"captchaSuccess": "Verified",
"verificationMisconfigured": "Human verification is not configured correctly. Contact an administrator.",
"capInitialState": "Verify you are human",
"capVerifying": "Verifying…",
"capSolved": "Verified",
"capError": "Verification failed",
"registerFailed": "Registration failed. Check your input",
"setupFailed": "Setup failed. Check your input",
"migrateFailed": "Migration failed. Check your input",
@@ -79,6 +84,11 @@
"invalidPassword": "Password must be at least 8 characters"
}
},
"domainSeparationConfirm": {
"title": "Save dual-domain settings?",
"description": "After saving, only the site URL can serve the admin UI and API, and only the image URL can serve public image links. Access via IP, an unlisted Host, or a reverse proxy that does not forward Host correctly may lock you out of the admin UI.\n\nIf locked out, run docker exec pichost clear-domains (local dev: npm run clear-domains), or disable domain separation in Settings when you can access it again.\n\nSave anyway?",
"confirm": "Save anyway"
},
"setup": {
"migrateTitle": "Migrate to username/password",
"initTitle": "First run — create admin account",
@@ -149,11 +159,13 @@
"url": "URL",
"markdown": "Markdown",
"html": "HTML",
"bbcode": "BBCode",
"copied": "Copied to clipboard",
"copiedLabel": "Copied {label}",
"copiedUrl": "URL copied",
"copiedMarkdown": "Markdown copied",
"copiedHtml": "HTML copied",
"copiedBbcode": "BBCode copied",
"copiedFormat": "Copied {format}",
"failed": "Copy failed",
"failedManual": "Copy failed — select the link manually",
@@ -181,12 +193,55 @@
},
"settings": {
"title": "System settings",
"pageTitle": "Settings & preferences",
"pageSubtitle": "Manage system configuration and activity logs",
"pageSubtitleBasic": "Manage system configuration and upload preferences",
"navBasic": "Basic",
"navDomains": "Domains & paths",
"navAccess": "Access control",
"navPreferences": "Preferences",
"navLogs": "Activity log",
"systemVersion": "Version",
"checkUpdate": "Check for updates",
"saveSettings": "Save settings",
"subtitle": "Saved to database; environment variables take precedence",
"featureToggles": "Feature toggles",
"featureTogglesHint": "Control registration and system behavior",
"pathAndLink": "Paths & links",
"pathAndLinkHint": "Control image URL format and upload directory structure",
"domainSeparationSection": "Domain separation",
"allowRegistration": "Open registration",
"allowRegistrationHint": "Allow new users to register (regular users see only their images)",
"accessControl": "Access control",
"refererHint": "Referer hotlink protection; comma-separated hostnames, empty = no restriction",
"refererDomainsLabel": "Allowed domains",
"refererTip": "Separate multiple domains with commas (,); wildcards are not supported",
"refererExamplesTitle": "Example",
"refererExamplesSample": "example.com, static.example.com",
"refererScenarioTitle": "Common use case",
"refererScenarioDesc": "Allow your main site and static site to embed images",
"refererEnabled": "Enabled",
"refererUnrestricted": "Unrestricted",
"loginVerification": "Login verification",
"loginVerificationHint": "Human verification for login and registration (choose one)",
"loginVerificationSlider": "Local slider",
"loginVerificationSliderHint": "Built-in slider puzzle; no third-party service",
"loginVerificationTurnstile": "Cloudflare Turnstile",
"loginVerificationTurnstileHint": "Create a widget in Cloudflare Dashboard, then enter Site Key and Secret Key",
"loginVerificationCap": "Cap POW",
"loginVerificationCapHint": "Self-hosted Cap Standalone; enter API Endpoint and Secret Key",
"turnstileSiteKey": "Turnstile Site Key",
"turnstileSiteKeyPlaceholder": "0x4AAAAAAA…",
"turnstileSecretKey": "Turnstile Secret Key",
"turnstileSecretKeyPlaceholder": "0x4AAAAAAA…",
"capApiEndpoint": "Cap API Endpoint",
"capApiEndpointPlaceholder": "https://cap.example.com/your-site-key/",
"capSecretKey": "Cap Secret Key",
"capSecretKeyPlaceholder": "Secret key from your Cap dashboard",
"systemInfo": "System",
"systemInfoHint": "Current version and updates",
"uploadConvenience": "Upload convenience",
"defaultCopyFormat": "Default copy format",
"refererPlaceholder": "example.com, www.example.com",
"domainSettings": "Domain settings",
"domainSeparationActive": "Domain separation enabled: image host serves images only; site host serves admin and API",
@@ -214,12 +269,15 @@
"badgeSaved": "Saved",
"badgeDefault": "Default",
"badgeUnset": "Not set",
"badgeOptional": "Optional",
"tokenEnv": "Environment",
"tokenDb": "Generated in app",
"tokenNone": "Not configured",
"apiTokenLine": "API Token · {source} ·",
"apiTokenLine": "Source: {source}",
"viewReleases": "View releases",
"updateAvailable": "Update available: {version}",
"upToDate": "You are on the latest version",
"checkUpdateFailed": "Failed to check for updates. Please try again later",
"unsavedChanges": "Unsaved changes",
"manageToken": "Manage token",
"envOverride": "Overridden by environment variable; cannot edit in UI",
@@ -278,11 +336,36 @@
"servingPublicShort": "Public",
"backendName": "Display name",
"badgeDefault": "Default",
"badgeDefaultStorage": "Default storage",
"badgeDisabled": "Disabled",
"badgeEnabled": "Enabled",
"overviewTitle": "Storage overview",
"overviewSubtitle": "Usage across all storage backends",
"overviewTotal": "Total capacity",
"overviewUsed": "Used",
"overviewFree": "Free",
"overviewUsageRate": "Overall usage",
"overviewQuota": "Total quota",
"overviewInstances": "Backends",
"overviewActive": "Active",
"capacityDistribution": "Distribution",
"backendType": "Type",
"storageId": "Storage ID",
"storageType": "Storage type",
"badgeLocal": "Local",
"defaultStorageTip": "Default storage: new uploads are saved to “{name}”. Use “Set as default” on another backend to change this.",
"supportedTitle": "Supported backends",
"supportedSubtitle": "PicHost supports multiple storage backends for different scenarios",
"supportedLocalDesc": "Ideal for small deployments and personal use",
"supportedR2Desc": "Highly available, low-cost object storage",
"supportedS3Title": "S3 compatible",
"supportedS3Desc": "Storage services compatible with the Amazon S3 API",
"footerTip": "The default backend receives all new uploads",
"statTotal": "Total",
"statUsed": "Used",
"statFree": "Free",
"statFileCount": "Files",
"statQuota": "Quota",
"usageRate": "Usage",
"indexImages": "PicHost images {count} · {size}",
"setDefault": "Set as default",
@@ -313,7 +396,16 @@
"uploadToday": "Uploaded today",
"uploadMonth": "Uploaded this month",
"uploadTotal": "Total uploads",
"storedCount": "Stored images",
"storedCount": "Stored now",
"totalFiles": "Total files",
"totalOccupied": "{size} used",
"storageUsage": "Storage usage",
"noQuota": "No quota configured",
"vsYesterday": "vs yesterday",
"vsLastMonth": "vs last month",
"trendUp": "↑ {p}%",
"trendDown": "↓ {p}%",
"trendFlat": "flat",
"deleteToday": "Deleted today",
"deleteMonth": "Deleted this month",
"deleteTotal": "Total deleted",
@@ -322,15 +414,39 @@
"sourceDistribution": "Uploads by source",
"sourceWeb": "Web",
"sourceApi": "API",
"tagWeb": "Web",
"tagApi": "API",
"noData": "No data",
"gallery": "Gallery",
"imagesSection": "All images",
"filterStorageAll": "All storage",
"storage": "Storage",
"searchPlaceholder": "Search filename",
"searchPlaceholderWide": "Search filename, tags, or links",
"filterType": "Image type",
"filterTypeAll": "All types",
"filterSource": "Upload source",
"filterSourceAll": "All sources",
"sourceWeb": "Web upload",
"sourceApi": "API upload",
"resetFilters": "Reset",
"batchActions": "Bulk actions",
"selectedItems": "{n} selected",
"colFilename": "Filename",
"colPreview": "Preview",
"colSize": "Size",
"colType": "Type",
"colSource": "Source",
"colUploadedAt": "Uploaded",
"colActions": "Actions",
"previewBadge": "Image",
"clear": "Clear",
"selected": "{n} selected",
"batchDelete": "Delete selected",
"batchSelect": "Batch select",
"viewMode": "View mode",
"viewGrid": "Grid view",
"viewList": "List view",
"selectAll": "Select all",
"invertSelection": "Invert",
"clearSelection": "Clear selection",
@@ -378,19 +494,23 @@
"previewFailed": "Preview failed",
"openPreview": "View full image",
"previewTitle": "Image details",
"previewSubtitle": "View image info and links",
"previewOriginalName": "Filename",
"previewUploadedAt": "Uploaded",
"previewSize": "Size",
"previewContentType": "Type",
"previewSizeDetail": "{size} ({bytes} bytes)",
"previewContentType": "File type",
"previewOwner": "Uploader",
"previewStorage": "Storage",
"previewKey": "Storage path",
"previewKey": "Image path",
"previewExtension": "Extension",
"previewDimensions": "Dimensions",
"previewDimensionsUnknown": "Loading…",
"previewUploadSource": "Upload source",
"uploadSourceUnknown": "Unknown",
"previewLinks": "Links",
"previewLinks": "Links & embed",
"previewCopyLink": "Copy link",
"previewDownload": "Download",
"previewOpen": "Open in new tab",
"previewClose": "Close",
"uploader": "Uploader: {name}",
@@ -402,6 +522,11 @@
"confirm": "Delete"
},
"pagination": {
"totalCount": "{total} {unit}",
"pageStatus": "Page {page} / {totalPages}",
"perPage": "{size} / page",
"pageSize": "Page size",
"pageNumber": "Page {page}",
"pageOf": "Page {page} / {totalPages} · {total} {unit}",
"totalOnly": "{total} {unit}",
"first": "First page",
@@ -409,6 +534,8 @@
"next": "Next page",
"last": "Last page",
"goTo": "Go",
"goToPrefix": "Go to",
"goToSuffix": "",
"pagePlaceholder": "Page"
},
"api": {
@@ -437,6 +564,74 @@
"newTokenDesc": "Copy and save it now. You can copy again from the field above after closing.",
"copyToken": "Copy token",
"saved": "Saved",
"searchPlaceholder": "Search endpoints…",
"showToken": "Show",
"hideToken": "Hide",
"helpText": "Need help? Read the full API docs",
"helpTitle": "Need help?",
"helpSubtitle": "Read the full API docs",
"expand": "Expand",
"collapse": "Collapse",
"viewDocs": "View docs",
"requestParams": "Request parameters",
"paramName": "Name",
"paramType": "Type",
"paramLocation": "In",
"paramRequired": "Required",
"paramDescription": "Description",
"required": "Yes",
"optional": "No",
"requestExample": "Request example",
"responseExample": "Response example",
"categories": {
"image": "Images",
"extension": "Plugins",
"system": "System"
},
"params": {
"upload": {
"image": "Primary upload field",
"file": "Compatibility field, single file",
"files": "Compatibility field, multiple files",
"token": "Twikoo protocol form token"
},
"list": {
"limit": "Page size, default 20, max 100",
"page": "Page number, starts at 1"
},
"search": {
"q": "Search keyword, required"
},
"delete": {
"key": "Storage path, e.g. images/2026/08/xxx.webp"
},
"batchDelete": {
"keys": "Array of image keys to delete"
},
"twikoo": {
"image": "Image file",
"token": "API token"
},
"backendId": "Storage backend ID, optional"
},
"debug": {
"title": "Try it",
"headers": "Headers",
"query": "Query",
"body": "Body",
"send": "Send request",
"response": "Response",
"selectFile": "Select file",
"noFileSelected": "No file selected",
"tokenPlaceholder": "Enter Auth-Token",
"invalidJson": "Invalid JSON",
"sendFailed": "Request failed",
"networkError": "Network error or unreachable",
"notesTitle": "Notes",
"noteSuccess": "200 means success with JSON body",
"noteError": "4xx / 5xx means failure; check error field",
"noteLimit": "Upload limit: up to 10 files, 10 MB each"
},
"docs": {
"upload": {
"title": "Upload images",
@@ -461,6 +656,14 @@
"twikoo": {
"title": "Twikoo-compatible upload",
"desc": "Twikoo / EasyImage 2.0 protocol; stored under images/. Fields: image + token."
},
"config": {
"title": "Get config",
"desc": "Public system config; no authentication required."
},
"count": {
"title": "Image count",
"desc": "Total images in your visible scope."
}
}
},
+211 -8
View File
@@ -67,6 +67,11 @@
"loginFailed": "登录失败,请检查用户名和密码",
"captchaHint": "拖动滑块对齐缺口",
"captchaSuccess": "验证通过",
"verificationMisconfigured": "人机验证未正确配置,请联系管理员",
"capInitialState": "验证你是人类",
"capVerifying": "验证中…",
"capSolved": "验证通过",
"capError": "验证失败",
"registerFailed": "注册失败,请检查输入",
"setupFailed": "初始化失败,请检查输入",
"migrateFailed": "迁移失败,请检查输入",
@@ -79,6 +84,11 @@
"invalidPassword": "密码至少 8 位"
}
},
"domainSeparationConfirm": {
"title": "确认保存双域名配置?",
"description": "保存后,仅网站域名可访问管理后台与 API,仅图片域名可提供图片直链。若通过 IP、未配置的 Host,或反代未正确传递 Host 访问,可能无法打开后台。\n\n若发生锁死,可执行 docker exec pichost clear-domains(本地开发:npm run clear-domains)清除域名配置,或在能访问时于设置中关闭「域名分离」。\n\n确定仍要保存吗?",
"confirm": "确认保存"
},
"setup": {
"migrateTitle": "迁移到账号密码登录",
"initTitle": "首次使用,创建管理员账号",
@@ -149,11 +159,13 @@
"url": "直链",
"markdown": "Markdown",
"html": "HTML",
"bbcode": "BBCode",
"copied": "已复制到剪贴板",
"copiedLabel": "已复制 {label}",
"copiedUrl": "已复制直链",
"copiedMarkdown": "已复制 Markdown",
"copiedHtml": "已复制 HTML",
"copiedBbcode": "已复制 BBCode",
"copiedFormat": "已复制 {format}",
"failed": "复制失败",
"failedManual": "复制失败,请手动选中链接复制",
@@ -181,12 +193,55 @@
},
"settings": {
"title": "系统设置",
"pageTitle": "设置与偏好",
"pageSubtitle": "管理系统配置与操作日志",
"pageSubtitleBasic": "管理系统配置与上传偏好",
"navBasic": "基础设置",
"navDomains": "域名与路径",
"navAccess": "访问控制",
"navPreferences": "偏好设置",
"navLogs": "操作日志",
"systemVersion": "系统版本",
"checkUpdate": "检查更新",
"saveSettings": "保存设置",
"subtitle": "保存后写入数据库;环境变量优先级更高",
"featureToggles": "功能开关",
"featureTogglesHint": "控制注册与系统行为",
"pathAndLink": "路径与链接",
"pathAndLinkHint": "控制图片直链格式与上传目录结构",
"domainSeparationSection": "域名分离",
"allowRegistration": "开放用户注册",
"allowRegistrationHint": "允许新用户自行注册(普通用户仅可见自己的图片)",
"accessControl": "访问控制",
"refererHint": "Referer 防盗链,逗号分隔允许引用的域名,留空不限制",
"refererDomainsLabel": "允许引用的域名",
"refererTip": "多个域名请使用英文逗号 (,) 分隔,不支持通配符",
"refererExamplesTitle": "推荐示例",
"refererExamplesSample": "example.com, static.example.com",
"refererScenarioTitle": "常见场景",
"refererScenarioDesc": "允许主站与静态站点引用图片",
"refererEnabled": "已开启",
"refererUnrestricted": "未限制",
"loginVerification": "登录验证",
"loginVerificationHint": "登录与注册时使用的人机验证方式,三选一",
"loginVerificationSlider": "本地滑块",
"loginVerificationSliderHint": "内置滑块拼图,无需第三方服务",
"loginVerificationTurnstile": "Cloudflare Turnstile",
"loginVerificationTurnstileHint": "在 Cloudflare 控制台创建 Widget,填写 Site Key 与 Secret Key",
"loginVerificationCap": "Cap POW",
"loginVerificationCapHint": "自托管 Cap Standalone,填写 API Endpoint 与 Secret Key",
"turnstileSiteKey": "Turnstile Site Key",
"turnstileSiteKeyPlaceholder": "0x4AAAAAAA…",
"turnstileSecretKey": "Turnstile Secret Key",
"turnstileSecretKeyPlaceholder": "0x4AAAAAAA…",
"capApiEndpoint": "Cap API Endpoint",
"capApiEndpointPlaceholder": "https://cap.example.com/your-site-key/",
"capSecretKey": "Cap Secret Key",
"capSecretKeyPlaceholder": "在 Cap Dashboard 创建的 Secret Key",
"systemInfo": "系统信息",
"systemInfoHint": "当前系统版本与更新",
"uploadConvenience": "上传便捷功能",
"defaultCopyFormat": "默认复制格式",
"refererPlaceholder": "example.com, www.example.com",
"domainSettings": "域名配置",
"domainSeparationActive": "已启用域名分离:图片域仅出图,管理域提供后台与 API",
@@ -214,12 +269,15 @@
"badgeSaved": "已保存",
"badgeDefault": "默认",
"badgeUnset": "未设置",
"badgeOptional": "可选",
"tokenEnv": "环境变量",
"tokenDb": "后台生成",
"tokenNone": "未配置",
"apiTokenLine": "API Token · {source} ·",
"apiTokenLine": "来源:{source}",
"viewReleases": "查看发行版",
"updateAvailable": "有新版本 {version}",
"upToDate": "当前已是最新版本",
"checkUpdateFailed": "检查更新失败,请稍后重试",
"unsavedChanges": "有未保存的更改",
"manageToken": "管理 Token",
"envOverride": "该项已由环境变量覆盖,无法在后台修改",
@@ -278,11 +336,36 @@
"servingPublicShort": "公开",
"backendName": "显示名称",
"badgeDefault": "默认",
"badgeDefaultStorage": "默认存储",
"badgeDisabled": "已停用",
"badgeEnabled": "已启用",
"overviewTitle": "存储总览",
"overviewSubtitle": "所有存储后端使用情况",
"overviewTotal": "总容量",
"overviewUsed": "已用容量",
"overviewFree": "剩余容量",
"overviewUsageRate": "总体使用率",
"overviewQuota": "总配额",
"overviewInstances": "存储实例",
"overviewActive": "活跃后台",
"capacityDistribution": "容量分布",
"backendType": "类型",
"storageId": "存储标识",
"storageType": "存储类型",
"badgeLocal": "本地",
"defaultStorageTip": "默认存储提示:新上传的图片将默认保存到「{name}」。可点击其他后端的「设为默认」进行修改。",
"supportedTitle": "支持的存储后端",
"supportedSubtitle": "PicHost 支持多种存储后端,满足不同场景需求",
"supportedLocalDesc": "适合小型部署和个人使用",
"supportedR2Desc": "高可用、低成本的对象存储",
"supportedS3Title": "S3 兼容",
"supportedS3Desc": "兼容 Amazon S3 协议的存储服务",
"footerTip": "默认存储后端将自动接收所有新上传的图片",
"statTotal": "总量",
"statUsed": "已用",
"statFree": "剩余",
"statFileCount": "文件数量",
"statQuota": "配额",
"usageRate": "使用率",
"indexImages": "PicHost 图片 {count} 张 · {size}",
"setDefault": "设为默认",
@@ -313,7 +396,16 @@
"uploadToday": "今日上传",
"uploadMonth": "本月上传",
"uploadTotal": "累计上传",
"storedCount": "当前库存",
"storedCount": "当前存储",
"totalFiles": "总文件数",
"totalOccupied": "共占用 {size}",
"storageUsage": "存储使用率",
"noQuota": "未配置容量上限",
"vsYesterday": "较昨日",
"vsLastMonth": "较上月",
"trendUp": "↑ {p}%",
"trendDown": "↓ {p}%",
"trendFlat": "持平",
"deleteToday": "今日删除",
"deleteMonth": "本月删除",
"deleteTotal": "累计删除",
@@ -322,15 +414,39 @@
"sourceDistribution": "上传来源分布",
"sourceWeb": "网页",
"sourceApi": "API",
"tagWeb": "网页",
"tagApi": "API",
"noData": "暂无数据",
"gallery": "图库记录",
"imagesSection": "全部图片",
"filterStorageAll": "全部存储",
"storage": "存储",
"searchPlaceholder": "搜索文件名",
"clear": "清除",
"searchPlaceholderWide": "搜索文件名、标签或链接",
"filterType": "图片类型",
"filterTypeAll": "全部类型",
"filterSource": "上传来源",
"filterSourceAll": "全部来源",
"sourceWeb": "网页上传",
"sourceApi": "API 上传",
"resetFilters": "重置",
"batchActions": "批量操作",
"selectedItems": "已选择 {n} 项",
"colFilename": "文件名",
"colPreview": "预览",
"colSize": "大小",
"colType": "类型",
"colSource": "来源",
"colUploadedAt": "上传时间",
"colActions": "操作",
"previewBadge": "图片",
"clear": "清空",
"selected": "已选 {n}",
"batchDelete": "批量删除",
"batchSelect": "批量选择",
"viewMode": "视图模式",
"viewGrid": "网格视图",
"viewList": "列表视图",
"selectAll": "全选",
"invertSelection": "反选",
"clearSelection": "取消选择",
@@ -378,19 +494,23 @@
"previewFailed": "预览失败",
"openPreview": "查看大图",
"previewTitle": "图片详情",
"previewSubtitle": "查看图片信息与链接",
"previewOriginalName": "文件名",
"previewUploadedAt": "上传时间",
"previewSize": "大小",
"previewContentType": "类型",
"previewOwner": "上传者",
"previewStorage": "存储",
"previewKey": "存储路径",
"previewSizeDetail": "{size}({bytes} 字节)",
"previewContentType": "文件类型",
"previewOwner": "上传用户",
"previewStorage": "存储位置",
"previewKey": "图片路径",
"previewExtension": "扩展名",
"previewDimensions": "尺寸",
"previewDimensionsUnknown": "加载中…",
"previewUploadSource": "上传方式",
"uploadSourceUnknown": "未知",
"previewLinks": "链接",
"previewLinks": "链接与嵌入",
"previewCopyLink": "复制链接",
"previewDownload": "下载原图",
"previewOpen": "新窗口打开",
"previewClose": "关闭",
"uploader": "上传者:{name}",
@@ -402,6 +522,11 @@
"confirm": "确认删除"
},
"pagination": {
"totalCount": "共 {total} {unit}",
"pageStatus": "第 {page} / {totalPages} 页",
"perPage": "{size} 条/页",
"pageSize": "每页条数",
"pageNumber": "第 {page} 页",
"pageOf": "第 {page} / {totalPages} 页 · 共 {total} {unit}",
"totalOnly": "共 {total} {unit}",
"first": "第一页",
@@ -409,6 +534,8 @@
"next": "下一页",
"last": "最后一页",
"goTo": "跳转",
"goToPrefix": "前往",
"goToSuffix": "页",
"pagePlaceholder": "页码"
},
"api": {
@@ -437,6 +564,74 @@
"newTokenDesc": "请立即复制保存。关闭弹窗后仍可在上方输入框复制,但请尽快更新到你的脚本配置中。",
"copyToken": "复制 Token",
"saved": "我已保存",
"searchPlaceholder": "搜索接口…",
"showToken": "显示",
"hideToken": "隐藏",
"helpText": "需要帮助?查看完整 API 文档",
"helpTitle": "需要帮助?",
"helpSubtitle": "查看完整 API 文档",
"expand": "展开",
"collapse": "收起",
"viewDocs": "查看文档",
"requestParams": "请求参数",
"paramName": "参数名",
"paramType": "类型",
"paramLocation": "位置",
"paramRequired": "必填",
"paramDescription": "说明",
"required": "是",
"optional": "否",
"requestExample": "请求示例",
"responseExample": "响应示例",
"categories": {
"image": "图片接口",
"extension": "插件接口",
"system": "系统通用"
},
"params": {
"upload": {
"image": "上传图片,主字段",
"file": "兼容字段,单图上传",
"files": "兼容字段,多图上传",
"token": "Twikoo 协议兼容,表单 token"
},
"list": {
"limit": "每页条数,默认 20,最大 100",
"page": "页码,从 1 开始"
},
"search": {
"q": "搜索关键词,必填"
},
"delete": {
"key": "图片存储路径,如 images/2026/08/xxx.webp"
},
"batchDelete": {
"keys": "要删除的图片 key 数组"
},
"twikoo": {
"image": "上传图片",
"token": "API Token"
},
"backendId": "存储后端 ID,可选"
},
"debug": {
"title": "在线调试",
"headers": "Headers",
"query": "Query",
"body": "Body",
"send": "发送请求",
"response": "响应",
"selectFile": "选择文件",
"noFileSelected": "未选择任何文件",
"tokenPlaceholder": "输入 Auth-Token",
"invalidJson": "JSON 格式无效",
"sendFailed": "请求发送失败",
"networkError": "网络错误或无法连接",
"notesTitle": "响应说明",
"noteSuccess": "200 表示请求成功,返回 JSON 数据",
"noteError": "4xx / 5xx 表示请求失败,查看 error 字段",
"noteLimit": "上传限制:单次最多 10 张,单张最大 10 MB"
},
"docs": {
"upload": {
"title": "上传图片",
@@ -461,6 +656,14 @@
"twikoo": {
"title": "twikoo 兼容上传",
"desc": "兼容 Twikoo / EasyImage 2.0 协议,图片存入 images/ 目录;字段 image + token。"
},
"config": {
"title": "获取配置",
"desc": "获取系统公开配置,无需鉴权。"
},
"count": {
"title": "图片数量统计",
"desc": "获取当前可见范围内的图片总数。"
}
}
},
+6
View File
@@ -21,6 +21,12 @@ export default defineNuxtConfig({
css: ['~/assets/css/main.css'],
vue: {
compilerOptions: {
isCustomElement: tag => tag.startsWith('cap-')
}
},
colorMode: {
preference: 'system',
fallback: 'light'
+9 -2
View File
@@ -1,12 +1,12 @@
{
"name": "pichost",
"version": "1.2.5",
"version": "1.2.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "pichost",
"version": "1.2.5",
"version": "1.2.8",
"hasInstallScript": true,
"license": "GPL-3.0-only",
"dependencies": {
@@ -14,6 +14,7 @@
"@iconify-json/lucide": "^1.2.114",
"@nuxt/ui": "^4.9.0",
"@nuxtjs/i18n": "^10.6.0",
"cap-widget": "^0.1.57",
"nuxt": "^4.4.8",
"sharp": "^0.35.3",
"tailwindcss": "^4.3.1"
@@ -10704,6 +10705,12 @@
],
"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==",
"license": "Apache-2.0"
},
"node_modules/ccount": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/ccount/-/ccount-2.0.1.tgz",
+4 -1
View File
@@ -1,6 +1,6 @@
{
"name": "pichost",
"version": "1.2.5",
"version": "1.2.8",
"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": {
@@ -35,6 +35,8 @@
"start": "node .output/server/index.mjs",
"reset-password": "node server/cli/reset-password.mjs",
"migrate": "node server/cli/migrate-to-single-images.mjs",
"slider": "node server/cli/slider.mjs",
"clear-domains": "node server/cli/clear-domains.mjs",
"docs:prepare": "node docs-site/copy-screenshots.mjs",
"docs:dev": "npm run docs:prepare && vitepress dev docs-site",
"docs:build": "npm run docs:prepare && vitepress build docs-site",
@@ -45,6 +47,7 @@
"@iconify-json/lucide": "^1.2.114",
"@nuxt/ui": "^4.9.0",
"@nuxtjs/i18n": "^10.6.0",
"cap-widget": "^0.1.57",
"nuxt": "^4.4.8",
"sharp": "^0.35.3",
"tailwindcss": "^4.3.1"
+2
View File
@@ -10,6 +10,7 @@ import type { ServingMode } from '../../../utils/storage/types'
interface StorageCreateBody {
name?: string
provider?: string
config?: {
endpoint?: string
region?: string
@@ -70,6 +71,7 @@ export default defineEventHandler(async (event) => {
const id = insertStorageBackend({
name,
provider: body.provider?.trim(),
config,
secrets: { accessKeyId, secretAccessKey },
servingMode: body.servingMode,
+3 -2
View File
@@ -1,5 +1,5 @@
import { isAllowRegistration } from '../../utils/db'
import { isAdminSecretConfigured, isApiUploadTokenConfigured } from '../../utils/env'
import { getLoginVerificationPublicConfig, isAdminSecretConfigured, isApiUploadTokenConfigured } from '../../utils/env'
import { isInitialized } from '../../utils/auth'
export default defineEventHandler((event) => {
@@ -8,6 +8,7 @@ export default defineEventHandler((event) => {
allowRegistration: isAllowRegistration(),
legacyMode: !isInitialized() && isAdminSecretConfigured(event),
adminSecretConfigured: isAdminSecretConfigured(event),
apiUploadTokenConfigured: isApiUploadTokenConfigured(event)
apiUploadTokenConfigured: isApiUploadTokenConfigured(event),
loginVerification: getLoginVerificationPublicConfig(event)
}
})
+5 -15
View File
@@ -1,4 +1,3 @@
import type { H3Event } from 'h3'
import {
checkAdminSecret,
setLegacyAuthCookie
@@ -7,19 +6,18 @@ import { createApiError } from '../../utils/api-error'
import {
createSession,
isInitialized,
rowToAuthUser,
verifyPassword
} from '../../utils/auth'
import { findUserByUsername } from '../../utils/db'
import { getAdminSecret } from '../../utils/env'
import { verifyLoginCaptcha } from '../../utils/login-captcha'
import { verifyLoginVerification, type VerificationBody } from '../../utils/login-verification'
import { clientIp, logInfo, logWarn } from '../../utils/logger'
interface LoginBody {
interface LoginBody extends VerificationBody {
username?: string
password?: string
secret?: string
captchaId?: string
captchaPosition?: number
}
const loginAttempts = new Map<string, { count: number, resetAt: number }>()
@@ -42,20 +40,12 @@ function checkRateLimit(ip: string): void {
}
}
function verifyCaptchaOrFail(event: H3Event, body: LoginBody) {
const id = body.captchaId?.trim() ?? ''
const position = Number(body.captchaPosition)
if (!id || !verifyLoginCaptcha(id, position)) {
createApiError(event, 'INVALID_REQUEST', '请先完成滑块验证', 400)
}
}
export default defineEventHandler(async (event) => {
const ip = clientIp(event)
checkRateLimit(ip)
const body = await readBody<LoginBody>(event)
verifyCaptchaOrFail(event, body ?? {})
await verifyLoginVerification(event, body ?? {})
const initialized = isInitialized()
if (!initialized) {
@@ -94,6 +84,6 @@ export default defineEventHandler(async (event) => {
return {
success: true,
user: { id: user.id, username: user.username, role: user.role }
user: rowToAuthUser(user)
}
})
+5 -1
View File
@@ -9,6 +9,10 @@ export default defineEventHandler(async (event) => {
return {
authenticated: true,
user: { id: user.id, username: user.username, role: user.role }
user: {
id: user.id,
username: user.username,
role: user.role
}
}
})
+9 -2
View File
@@ -5,9 +5,10 @@ import {
isInitialized
} from '../../utils/auth'
import { isAllowRegistration } from '../../utils/db'
import { verifyLoginVerification, type VerificationBody } from '../../utils/login-verification'
import { clientIp, logInfo } from '../../utils/logger'
interface RegisterBody {
interface RegisterBody extends VerificationBody {
username?: string
password?: string
}
@@ -22,6 +23,8 @@ export default defineEventHandler(async (event) => {
}
const body = await readBody<RegisterBody>(event)
await verifyLoginVerification(event, body ?? {})
const username = body?.username?.trim() ?? ''
const password = body?.password ?? ''
@@ -38,7 +41,11 @@ export default defineEventHandler(async (event) => {
return {
success: true,
user: { id: user.id, username: user.username, role: user.role }
user: {
id: user.id,
username: user.username,
role: user.role
}
}
} catch (error: unknown) {
if (error instanceof Error) {
+7 -2
View File
@@ -1,5 +1,5 @@
import { isAllowRegistration } from '../../utils/db'
import { isAdminSecretConfigured } from '../../utils/env'
import { getLoginVerificationPublicConfig, isAdminSecretConfigured } from '../../utils/env'
import {
getCurrentUser,
isInitialized
@@ -17,8 +17,13 @@ export default defineEventHandler(async (event) => {
allowRegistration: isAllowRegistration(),
legacyMode,
needsMigration,
loginVerification: getLoginVerificationPublicConfig(event),
user: user
? { id: user.id, username: user.username, role: user.role }
? {
id: user.id,
username: user.username,
role: user.role
}
: null
}
})
+17 -2
View File
@@ -9,7 +9,7 @@ import { createApiError } from '../../utils/api-error'
import { getUploadSourcesForKeys, listUserIdUsernameMap } from '../../utils/db'
import { mapStoredImageToItem } from '../../utils/image-response'
import { listStorageBackendNameMap } from '../../utils/storage-backends'
import { readBackendIdQuery } from '../../utils/image-query'
import { readBackendIdQuery, readContentTypeQuery, readUploadSourceQuery } from '../../utils/image-query'
import { listImages } from '../../utils/storage'
export default defineEventHandler(async (event) => {
@@ -31,9 +31,24 @@ export default defineEventHandler(async (event) => {
if (backendId === null) {
createApiError(event, 'INVALID_REQUEST', '无效的存储后端', 400)
}
const contentType = readContentTypeQuery(query)
if (contentType === null) {
createApiError(event, 'INVALID_REQUEST', '无效的图片类型', 400)
}
const uploadSource = readUploadSourceQuery(query)
if (uploadSource === null) {
createApiError(event, 'INVALID_REQUEST', '无效的上传来源', 400)
}
const userFilter = await getImageUserFilter(event)
const listing = await listImages({ limit, page, userFilter, backendId })
const listing = await listImages({
limit,
page,
userFilter,
backendId,
contentType,
uploadSource
})
const user = await getCurrentUser(event)
const ownerMap = user?.role === 'admin' ? listUserIdUsernameMap() : undefined
+18 -2
View File
@@ -9,7 +9,7 @@ import { createApiError } from '../../utils/api-error'
import { getUploadSourcesForKeys, listUserIdUsernameMap } from '../../utils/db'
import { mapStoredImageToItem } from '../../utils/image-response'
import { listStorageBackendNameMap } from '../../utils/storage-backends'
import { readBackendIdQuery } from '../../utils/image-query'
import { readBackendIdQuery, readContentTypeQuery, readUploadSourceQuery } from '../../utils/image-query'
import { searchImages } from '../../utils/storage'
export default defineEventHandler(async (event) => {
@@ -40,9 +40,25 @@ export default defineEventHandler(async (event) => {
if (backendId === null) {
createApiError(event, 'INVALID_REQUEST', '无效的存储后端', 400)
}
const contentType = readContentTypeQuery(query)
if (contentType === null) {
createApiError(event, 'INVALID_REQUEST', '无效的图片类型', 400)
}
const uploadSource = readUploadSourceQuery(query)
if (uploadSource === null) {
createApiError(event, 'INVALID_REQUEST', '无效的上传来源', 400)
}
const userFilter = await getImageUserFilter(event)
const result = await searchImages({ query: q, limit, page, userFilter, backendId })
const result = await searchImages({
query: q,
limit,
page,
userFilter,
backendId,
contentType,
uploadSource
})
const user = await getCurrentUser(event)
const ownerMap = user?.role === 'admin' ? listUserIdUsernameMap() : undefined
Loaded 100 of 118 files, more files were not shown because too many files have changed in this diff. Show more