12 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
O96u 270af4e707 release: v1.2.5 — 图库页、图片详情弹层与列表体验优化
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
GitHub Release / release (push) Canceled after 0s
2026-08-31 16:05:53 +08:00
O96u 81dcc2c15e release: v1.2.4 — 修复未配置防盗链时外链图裂
GitHub Release / release (push) Canceled after 0s
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
2026-08-31 15:02:42 +08:00
O96u 20afda5869 release: v1.2.3 — 修复简短图片链接在按年/月存储下 404
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
GitHub Release / release (push) Canceled after 0s
开启简短链接时纯文件名直链先经 SQLite 索引反查完整 key,不再误解析为扁平 images/文件名路径。
2026-08-30 12:33:33 +08:00
O96u c9c34515dd release: v1.2.2 — 双域名配置与 Host 隔离修复
GitHub Release / release (push) Canceled after 0s
Publish Docker image / build (linux/amd64, ubuntu-latest, amd64) (push) Canceled after 0s
Publish Docker image / build (linux/arm64, ubuntu-24.04-arm, arm64) (push) Canceled after 0s
Publish Docker image / merge (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
修复设置页误清空管理域、配置与生效 URL 混淆及第三 Host 绕过隔离;加固 Settings API 与中间件,并更新文档站。
2026-08-30 10:57:26 +08:00
O96u 6c6766221b docs: refresh GitHub About description in metadata and FAQ 2026-08-29 12:04:05 +08:00
O96u 58a8e2082f fix: docs Pages deploy permissions and document GitHub Pages setup
Deploy job failed because Pages source must be GitHub Actions; document
About/description guidance and fix workflow job permissions.
2026-08-29 11:53:20 +08:00
O96u 9b0a3f4944 fix: trigger docs workflow when lockfile changes
docs:build uses npm ci; include package.json and package-lock.json in paths.
2026-08-29 11:50:20 +08:00
137 changed files with 9716 additions and 1986 deletions

No files matched your search

+3
View File
@@ -35,3 +35,6 @@
# 仅本地开发:设为 true 可绕过登录验证(跳过 /setup,一般无需开启) # 仅本地开发:设为 true 可绕过登录验证(跳过 /setup,一般无需开启)
# DEV_BYPASS_ACCESS=false # DEV_BYPASS_ACCESS=false
# 登录人机验证(滑块 / Turnstile / Cap)在后台「设置 → 访问控制」配置,无环境变量。
# 配置错误无法登录时:docker exec pichost slider(或 npm run slider)恢复为本地滑块。
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"description": "Self-hosted image hosting for your NAS / home server — Nuxt admin UI, local disk storage, server-side WebP compression, referer protection, Twikoo/EasyImage compatible.", "description": "Lightweight self-hosted image hosting — Docker, multi-user, gallery & API, local disk or S3-compatible storage.",
"homepage": "https://github.com/O96u/PicHost#readme", "homepage": "https://o96u.github.io/PicHost/",
"topics": [ "topics": [
"docker", "docker",
"image-hosting", "image-hosting",
+9
View File
@@ -7,6 +7,8 @@ on:
- 'docs-site/**' - 'docs-site/**'
- 'docs/screenshots/**' - 'docs/screenshots/**'
- '.github/workflows/docs.yml' - '.github/workflows/docs.yml'
- 'package.json'
- 'package-lock.json'
workflow_dispatch: workflow_dispatch:
permissions: permissions:
@@ -21,6 +23,10 @@ concurrency:
jobs: jobs:
build: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: read
pages: write
id-token: write
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v7 uses: actions/checkout@v7
@@ -50,6 +56,9 @@ jobs:
deploy: deploy:
needs: build needs: build
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment: environment:
name: github-pages name: github-pages
url: ${{ steps.deployment.outputs.page_url }} url: ${{ steps.deployment.outputs.page_url }}
+83
View File
@@ -4,6 +4,89 @@
## [Unreleased] ## [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
### 新增
- 图库页(`/gallery`)替代原「统计」导航;图片点击放大详情弹层(尺寸、上传方式、存储路径、链接复制)
- 图库列表支持全选、反选;单张删除移至详情弹层
- 图片列表 API 返回上传来源(网页 / API,来自活动日志)
### 改进
- README 补充技术栈说明
### 移除
- `/stats` 路由(不再兼容跳转)
## [1.2.4] - 2026-08-31
### 修复
- 访问控制(Referer 防盗链)留空时仍会拦截外链图片:浏览器直开无 Referer 可访问,博客/论坛嵌入带 Referer 会 403 图裂;现仅在配置了白名单时才校验
## [1.2.3] - 2026-08-30
### 修复
- 开启「简短图片链接」且按年/月分组时,纯文件名直链(如 `/xxx.webp`)误解析为 `images/xxx.webp` 导致 404;现先经 SQLite 索引反查完整 key
## [1.2.2] - 2026-08-30
### 修复
- 双域名:设置页保存时误清空管理域(`site_base_url`);仅改图片域时保护已有网站域配置
- 双域名:设置 API 配置值与 request origin fallback 混淆,导致「当前生效」显示错误
- 双域名:未配置的第三 Host(`pages.dev`、裸 IP 等)可绕过 Host 隔离访问后台
### 改进
- 设置 API 拆分 `siteBaseUrl` / `imageBaseUrl`(配置值)、`effective*`(直链)、`runtime`(当前访问检测)
- `PATCH /api/settings` 增加 `domainSeparation` 字段与保存校验
- 设置页:检测地址展示、关闭双域名确认、反代 Host 不一致警告;首次设置不再自动填入 origin
- Host 中间件:双域名开启时对未知 Host 返回 404(开发 `localhost` 例外)
- 文档站:新增 [更新日志](https://o96u.github.io/PicHost/guide/changelog);重写 Cloudflare 部署说明;同步 FAQ / 双域名文档
## [1.2.1] - 2026-08-29 ## [1.2.1] - 2026-08-29
### 新增 ### 新增
+2
View File
@@ -25,6 +25,8 @@ ENV NODE_ENV=production \
COPY --from=build /app/.output ./.output COPY --from=build /app/.output ./.output
COPY server/cli/reset-password.mjs ./server/cli/reset-password.mjs COPY server/cli/reset-password.mjs ./server/cli/reset-password.mjs
COPY server/cli/migrate-to-single-images.mjs ./server/cli/migrate-to-single-images.mjs COPY server/cli/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 COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh RUN chmod +x /docker-entrypoint.sh
+21 -7
View File
@@ -20,6 +20,7 @@
<a href="https://o96u.github.io/PicHost/en/">Docs</a> · <a href="https://o96u.github.io/PicHost/en/">Docs</a> ·
<a href="#screenshots">Screenshots</a> · <a href="#screenshots">Screenshots</a> ·
<a href="#features">Features</a> · <a href="#features">Features</a> ·
<a href="#tech-stack">Tech Stack</a> ·
<a href="#quick-start">Quick Start</a> · <a href="#quick-start">Quick Start</a> ·
<a href="README.md">简体中文</a> <a href="README.md">简体中文</a>
</p> </p>
@@ -30,23 +31,36 @@
**main** has no public demo. **cloudflare** branch live demo: [pic.roven.cc](https://pic.roven.cc) **main** has no public demo. **cloudflare** branch live demo: [pic.roven.cc](https://pic.roven.cc)
| 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 | | Storage | Settings |
| :---: | :-------: | | :-----: | :-------: |
| ![Stats](docs/screenshots/stats.png) | ![Settings](docs/screenshots/settings-en.png) | | ![Storage](docs/screenshots/storage.png) | ![Settings](docs/screenshots/settings-en.png) |
## Features ## Features
- **Drag, click, or Ctrl+V paste** — server-side WebP, Referer hotlink protection - **Drag, click, or Ctrl+V paste** — server-side WebP, Referer hotlink protection
- **Multi-user** — login with slider 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 - **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 - **API & Twikoo** — global / per-user tokens; `POST /api/index.php` compatible
- **Zero-config Docker** — first-run web wizard, no secrets upfront - **Zero-config Docker** — first-run web wizard, no secrets upfront
## Tech Stack
| Layer | Technologies |
| ----- | ------------ |
| Frontend | [Nuxt 4](https://nuxt.com) · [Nuxt UI 4](https://ui.nuxt.com) · [Vue 3](https://vuejs.org) · [Tailwind CSS 4](https://tailwindcss.com) · TypeScript |
| Backend | [Nitro](https://nitro.build) (`node-server`) · REST API |
| Data | SQLite · local `data/pichost.db` |
| Images | [sharp](https://sharp.pixelplumbing.com) (server-side WebP) |
| Storage | Local disk · S3-compatible ([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS, etc.) |
| i18n | [@nuxtjs/i18n](https://i18n.nuxtjs.org) (zh-CN / English) |
| Quality & docs | [Vitest](https://vitest.dev) · [VitePress](https://vitepress.dev) docs site |
| Deploy | Docker · Node.js 22 |
## Quick Start ## Quick Start
```bash ```bash
+20 -6
View File
@@ -20,6 +20,7 @@
<a href="https://o96u.github.io/PicHost/">文档</a> · <a href="https://o96u.github.io/PicHost/">文档</a> ·
<a href="#界面预览">预览</a> · <a href="#界面预览">预览</a> ·
<a href="#特性">特性</a> · <a href="#特性">特性</a> ·
<a href="#技术栈">技术栈</a> ·
<a href="#快速开始">快速开始</a> · <a href="#快速开始">快速开始</a> ·
<a href="README.en.md">English</a> <a href="README.en.md">English</a>
</p> </p>
@@ -30,23 +31,36 @@
**main** 分支暂无公网演示;**cloudflare** 分支在线体验:[pic.roven.cc](https://pic.roven.cc) **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 防盗链 - **拖拽 / 点击 / Ctrl+V 粘贴**上传;服务端 WebP 压缩、Referer 防盗链
- **多用户**:账号密码登录(滑动验证)、可选开放注册;普通用户仅见自己的图片 - **多用户**:账号密码登录(滑块 / Turnstile / Cap 人机验证)、可选开放注册;普通用户仅见自己的图片
- **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public` - **多后端存储**:本地磁盘 + S3 兼容(R2 / COS / OSS / AWS);混合直链 `proxy` / `public`
- **图库与统计**:浏览、搜索、批量删除;上传趋势与来源分布 - **图库**:浏览、搜索、按存储/来源筛选、网格/列表切换、批量删除;统计概览与来源分布
- **API 与 Twikoo**:全局 / 个人 Token;`POST /api/index.php` 兼容 - **API 与 Twikoo**:全局 / 个人 Token;`POST /api/index.php` 兼容
- **Docker 零配置**:首次访问 Web 引导创建管理员 - **Docker 零配置**:首次访问 Web 引导创建管理员
## 技术栈
| 层级 | 技术 |
| ---- | ---- |
| 前端 | [Nuxt 4](https://nuxt.com) · [Nuxt UI 4](https://ui.nuxt.com) · [Vue 3](https://vuejs.org) · [Tailwind CSS 4](https://tailwindcss.com) · TypeScript |
| 后端 | [Nitro](https://nitro.build)(`node-server`)· REST API |
| 数据 | SQLite · 本地 `data/pichost.db` |
| 图片处理 | [sharp](https://sharp.pixelplumbing.com)(服务端 WebP 压缩) |
| 存储 | 本地磁盘 · S3 兼容([AWS SDK](https://aws.amazon.com/sdk-for-javascript/) · R2 / COS / OSS 等) |
| 国际化 | [@nuxtjs/i18n](https://i18n.nuxtjs.org)(简体中文 / English) |
| 质量与文档 | [Vitest](https://vitest.dev) · [VitePress](https://vitepress.dev) 文档站 |
| 部署 | Docker · Node.js 22 |
## 快速开始 ## 快速开始
```bash ```bash
+18
View File
@@ -106,3 +106,21 @@
.upload-settings-btn:hover .upload-settings-icon { .upload-settings-btn:hover .upload-settings-icon {
transform: rotate(90deg); 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"> <script setup lang="ts">
import logoLight from '~/assets/image/logo-light.png' import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png' import logoDark from '~/assets/image/logo-dark.png'
import type { LoginVerificationPayload } from '~/types/auth'
const router = useRouter() const router = useRouter()
const { login, fetchStatus, authStatus } = useAuth() const { login, fetchStatus, authStatus } = useAuth()
@@ -11,45 +12,53 @@ const username = ref('')
const password = ref('') const password = ref('')
const secret = ref('') const secret = ref('')
const loading = ref(false) const loading = ref(false)
const captchaRef = ref<{ reset: () => Promise<void> } | null>(null) const verificationRef = ref<{ reset: () => Promise<void> } | null>(null)
const captchaPayload = ref<{ captchaId: string, captchaPosition: number } | null>(null) const verificationPayload = ref<LoginVerificationPayload | null>(null)
const verificationMountKey = ref(0)
const legacyMode = computed(() => authStatus.value?.legacyMode ?? false) const legacyMode = computed(() => authStatus.value?.legacyMode ?? false)
const allowRegistration = computed(() => authStatus.value?.allowRegistration ?? false) const allowRegistration = computed(() => authStatus.value?.allowRegistration ?? false)
const loginVerification = computed(() =>
authStatus.value?.loginVerification ?? { method: 'slider' as const }
)
const canSubmit = computed(() => const canSubmit = computed(() =>
Boolean(captchaPayload.value) Boolean(verificationPayload.value)
&& (legacyMode.value ? Boolean(secret.value) : Boolean(username.value && password.value)) && (legacyMode.value ? Boolean(secret.value) : Boolean(username.value && password.value))
) )
function onCaptchaVerified(payload: { id: string, positionPercent: number }) { function onVerificationVerified(payload: LoginVerificationPayload) {
captchaPayload.value = { verificationPayload.value = payload
captchaId: payload.id,
captchaPosition: payload.positionPercent
}
} }
async function resetCaptcha() { function onVerificationCleared() {
captchaPayload.value = null verificationPayload.value = null
await captchaRef.value?.reset() }
async function resetVerification() {
verificationPayload.value = null
await verificationRef.value?.reset()
} }
onMounted(async () => { onMounted(async () => {
verificationPayload.value = null
verificationMountKey.value += 1
const status = await fetchStatus() const status = await fetchStatus()
if (!status.initialized && !status.legacyMode) { if (!status.initialized && !status.legacyMode) {
await router.replace('/setup') await router.replace('/setup')
return
} }
}) })
async function submit() { async function submit() {
if (!canSubmit.value || loading.value || !captchaPayload.value) return if (!canSubmit.value || loading.value || !verificationPayload.value) return
loading.value = true loading.value = true
try { try {
const captcha = captchaPayload.value const verification = verificationPayload.value
const result = legacyMode.value const result = legacyMode.value
? await login({ secret: secret.value }, captcha) ? await login({ secret: secret.value }, verification)
: await login({ username: username.value.trim(), password: password.value }, captcha) : await login({ username: username.value.trim(), password: password.value }, verification)
if (result.ok) { if (result.ok) {
if (result.needsMigration) { if (result.needsMigration) {
@@ -59,10 +68,10 @@ async function submit() {
username.value = '' username.value = ''
password.value = '' password.value = ''
secret.value = '' secret.value = ''
await resetCaptcha() await resetVerification()
toast.add({ title: t('auth.loginSuccess'), color: 'success' }) toast.add({ title: t('auth.loginSuccess'), color: 'success' })
} else { } else {
await resetCaptcha() await resetVerification()
toast.add({ toast.add({
title: result.error ?? (legacyMode.value ? t('auth.loginFailedSecret') : t('auth.loginFailedCredentials')), title: result.error ?? (legacyMode.value ? t('auth.loginFailedSecret') : t('auth.loginFailedCredentials')),
color: 'error' color: 'error'
@@ -170,9 +179,14 @@ async function submit() {
</div> </div>
</template> </template>
<SliderCaptcha <LoginVerification
ref="captchaRef" :key="verificationMountKey"
@verified="onCaptchaVerified" ref="verificationRef"
:method="loginVerification.method"
:turnstile-site-key="loginVerification.turnstileSiteKey"
:cap-api-endpoint="loginVerification.capApiEndpoint"
@verified="onVerificationVerified"
@cleared="onVerificationCleared"
/> />
<UButton <UButton
+11 -3
View File
@@ -3,9 +3,11 @@ const props = withDefaults(
defineProps<{ defineProps<{
code: string code: string
scrollable?: boolean 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-[#ff5f56]" />
<span class="size-3 rounded-full border border-black/15 bg-[#ffbd2e]" /> <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 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> </div>
<UButton <UButton
icon="i-lucide-copy" icon="i-lucide-copy"
@@ -47,7 +55,7 @@ async function copyCode() {
</div> </div>
<pre <pre
class="overflow-auto p-4 text-xs leading-relaxed text-neutral-100" class="overflow-auto p-4 text-xs leading-relaxed text-neutral-100"
:class="props.scrollable ? 'max-h-80' : ''" :class="scrollable ? 'max-h-80' : ''"
><code class="font-mono">{{ props.code }}</code></pre> ><code class="font-mono whitespace-pre">{{ code }}</code></pre>
</div> </div>
</template> </template>
+3 -8
View File
@@ -13,21 +13,16 @@ const mobileUserOpen = ref(false)
const navItems = computed(() => { const navItems = computed(() => {
const items = [ const items = [
{ label: t('nav.api'), to: '/api', icon: 'i-lucide-code-2' }, { label: t('nav.api'), to: '/api', icon: 'i-lucide-code-2' },
{ label: t('nav.stats'), to: '/stats', icon: 'i-lucide-chart-column' } { label: t('nav.gallery'), to: '/gallery', icon: 'i-lucide-images' }
] ]
if (isAdmin.value) { if (isAdmin.value) {
items.push({ label: t('nav.storage'), to: '/storage', icon: 'i-lucide-hard-drive' }) 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 return items
}) })
const accountMenuItems = computed<DropdownMenuItem[]>(() => [ const accountMenuItems = computed<DropdownMenuItem[]>(() => [
{
label: t('nav.logs'),
icon: 'i-lucide-scroll-text',
to: '/logs'
},
{ {
label: t('nav.changePassword'), label: t('nav.changePassword'),
icon: 'i-lucide-key-round', icon: 'i-lucide-key-round',
@@ -48,7 +43,7 @@ const desktopUserMenuItems = computed<DropdownMenuItem[][]>(() => [
function isNavActive(to: string) { function isNavActive(to: string) {
if (to === '/settings') { if (to === '/settings') {
return route.path === '/settings' return route.path.startsWith('/settings')
} }
return route.path.startsWith(to) 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 icon?: string
block?: boolean block?: boolean
successTitle?: string successTitle?: string
variant?: 'solid' | 'outline' | 'soft' | 'subtle' | 'ghost' | 'link'
color?: 'primary' | 'secondary' | 'success' | 'info' | 'warning' | 'error' | 'neutral'
}>() }>()
const emit = defineEmits<{ const emit = defineEmits<{
@@ -76,7 +78,8 @@ async function copy() {
<template> <template>
<UButton <UButton
size="xs" size="xs"
variant="soft" :variant="variant ?? 'soft'"
:color="color"
:loading="copying" :loading="copying"
:disabled="!value" :disabled="!value"
:label="iconOnly ? undefined : label" :label="iconOnly ? undefined : label"
+166 -16
View File
@@ -5,25 +5,30 @@ import type { CopyFormat } from '~/composables/useUploadPreferences'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
image: ImageItem image: ImageItem
selected: boolean selected: boolean
deleting?: boolean
selectable?: boolean selectable?: boolean
showKey?: boolean showKey?: boolean
showStorage?: boolean showStorage?: boolean
compact?: boolean compact?: boolean
gallery?: boolean
allowDelete?: boolean
}>(), { }>(), {
selectable: true, selectable: true,
showKey: true, showKey: true,
showStorage: false, showStorage: false,
compact: false compact: false,
gallery: false,
allowDelete: true
}) })
const emit = defineEmits<{ const emit = defineEmits<{
'update:selected': [value: boolean] 'update:selected': [value: boolean]
'preview': []
'delete': [] 'delete': []
}>() }>()
const { formatFileSize } = useFileSize() const { formatFileSize } = useFileSize()
const { t, locale } = useI18n() const { t, locale } = useI18n()
const toast = useToast()
const { copyFormat } = useUploadPreferences() const { copyFormat } = useUploadPreferences()
const imageError = ref(false) const imageError = ref(false)
const retryCount = ref(0) const retryCount = ref(0)
@@ -111,21 +116,174 @@ const storageIcon = computed(() =>
props.image.storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud' 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') { function toggleSelected(value: boolean | 'indeterminate') {
emit('update:selected', value === true) 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> </script>
<template> <template>
<div class="flex flex-col overflow-hidden rounded-xl border border-default bg-elevated shadow-sm"> <div
<div class="relative aspect-square shrink-0 overflow-hidden bg-muted"> 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 <img
v-if="!imageError" v-if="!imageError"
:key="`${image.key}-${retryCount}`" :key="`${image.key}-${retryCount}`"
:src="previewSrc" :src="previewSrc"
:alt="image.originalName" :alt="image.originalName"
loading="lazy" loading="lazy"
class="absolute inset-0 size-full object-cover object-center" 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"
tabindex="0"
:aria-label="t('image.openPreview')"
@click="emit('preview')"
@keydown.enter="emit('preview')"
@keydown.space.prevent="emit('preview')"
>
<img
v-if="!imageError"
:key="`${image.key}-${retryCount}`"
:src="previewSrc"
:alt="image.originalName"
loading="lazy"
class="absolute inset-0 size-full cursor-zoom-in object-cover object-center"
@error="onPreviewError" @error="onPreviewError"
> >
<div <div
@@ -137,26 +295,17 @@ function toggleSelected(value: boolean | 'indeterminate') {
<div <div
v-if="selectable" v-if="selectable"
class="absolute top-2 left-2" class="absolute top-2 left-2"
@click.stop
> >
<UCheckbox <UCheckbox
:model-value="selected" :model-value="selected"
@update:model-value="toggleSelected" @update:model-value="toggleSelected"
/> />
</div> </div>
<div class="absolute top-2 right-2">
<UButton
size="xs"
color="error"
variant="solid"
icon="i-lucide-trash-2"
:aria-label="t('common.delete')"
:loading="deleting"
@click="emit('delete')"
/>
</div>
<div <div
v-if="image.owner" v-if="image.owner"
class="absolute bottom-2 left-2 max-w-[calc(50%-0.5rem)]" class="absolute bottom-2 left-2 max-w-[calc(50%-0.5rem)]"
@click.stop
> >
<span <span
class="inline-flex max-w-full items-center gap-1 rounded-md bg-black/65 px-2 py-0.5 text-xs font-medium text-white shadow-sm backdrop-blur-sm" class="inline-flex max-w-full items-center gap-1 rounded-md bg-black/65 px-2 py-0.5 text-xs font-medium text-white shadow-sm backdrop-blur-sm"
@@ -173,6 +322,7 @@ function toggleSelected(value: boolean | 'indeterminate') {
v-if="showStorage && image.storage" v-if="showStorage && image.storage"
class="absolute bottom-2 max-w-[calc(50%-0.5rem)]" class="absolute bottom-2 max-w-[calc(50%-0.5rem)]"
:class="image.owner ? 'right-2' : 'left-2'" :class="image.owner ? 'right-2' : 'left-2'"
@click.stop
> >
<span <span
class="inline-flex max-w-full items-center gap-1 rounded-md bg-black/65 px-2 py-0.5 text-xs font-medium text-white shadow-sm backdrop-blur-sm" class="inline-flex max-w-full items-center gap-1 rounded-md bg-black/65 px-2 py-0.5 text-xs font-medium text-white shadow-sm backdrop-blur-sm"
+24 -7
View File
@@ -4,24 +4,39 @@ import type { ImageItem } from '~/types/image'
const props = withDefaults(defineProps<{ const props = withDefaults(defineProps<{
items: ImageItem[] items: ImageItem[]
selectedKeys: Set<string> selectedKeys: Set<string>
deletingKeys: Set<string>
selectable?: boolean selectable?: boolean
showKey?: boolean showKey?: boolean
showStorage?: boolean showStorage?: boolean
emptyText?: string emptyText?: string
dense?: boolean dense?: boolean
compact?: boolean compact?: boolean
/** 图库:5 列 × 2 行,缩略图略扁 */
gallery?: boolean
allowDelete?: boolean
}>(), { }>(), {
selectable: true, selectable: true,
showKey: true, showKey: true,
showStorage: false, showStorage: false,
dense: 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<{ const emit = defineEmits<{
'update:selectedKeys': [value: Set<string>] 'update:selectedKeys': [value: Set<string>]
'delete': [key: string] 'preview': [image: ImageItem]
'delete': [image: ImageItem]
}>() }>()
const { t } = useI18n() const { t } = useI18n()
@@ -39,21 +54,23 @@ function updateSelection(key: string, selected: boolean) {
<template> <template>
<div <div
v-if="items.length" v-if="items.length"
class="grid items-start sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4" class="items-start"
:class="dense ? 'grid-cols-2 gap-3' : 'grid-cols-1 gap-4'" :class="gridClass"
> >
<ImageCard <ImageCard
v-for="image in items" v-for="image in items"
:key="image.key" :key="image.key"
:image="image" :image="image"
:selected="selectedKeys.has(image.key)" :selected="selectedKeys.has(image.key)"
:deleting="deletingKeys.has(image.key)"
:selectable="selectable" :selectable="selectable"
:show-key="showKey" :show-key="showKey"
:show-storage="showStorage" :show-storage="showStorage"
:compact="compact" :compact="compact"
:gallery="gallery"
:allow-delete="allowDelete"
@update:selected="updateSelection(image.key, $event)" @update:selected="updateSelection(image.key, $event)"
@delete="emit('delete', image.key)" @preview="emit('preview', image)"
@delete="emit('delete', image)"
/> />
</div> </div>
<div <div
+426
View File
@@ -0,0 +1,426 @@
<script setup lang="ts">
import type { ImageItem } from '~/types/image'
import type { CopyFormat } from '~/composables/useUploadPreferences'
import { formatImageDimensions } from '~/utils/image-display'
type EmbedFormat = CopyFormat | 'bbcode'
const props = withDefaults(defineProps<{
open: boolean
image: ImageItem | null
showStorage?: boolean
deleting?: boolean
allowDelete?: boolean
}>(), {
showStorage: false,
allowDelete: true
})
const emit = defineEmits<{
'update:open': [value: boolean]
'delete': []
}>()
const toast = useToast()
const { formatFileSize } = useFileSize()
const { t, locale } = useI18n()
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 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.bbcode'), value: 'bbcode' as const }
])
const uploadedLabel = computed(() => {
if (!props.image) return '—'
try {
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 (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 (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')
}
})
const storageIcon = computed(() =>
props.image?.storage?.type === 'local' ? 'i-lucide-hard-drive' : 'i-lucide-cloud'
)
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(() => {
const formatted = formatImageDimensions(naturalWidth.value, naturalHeight.value)
if (formatted) return formatted
return dimensionsLoaded.value ? '—' : t('image.previewDimensionsUnknown')
})
watch(() => props.image?.key, () => {
naturalWidth.value = null
naturalHeight.value = null
dimensionsLoaded.value = false
})
watch(() => props.open, (open) => {
if (open) {
embedFormat.value = copyFormat.value
}
})
function selectEmbedFormat(value: EmbedFormat) {
embedFormat.value = value
if (value !== 'bbcode') {
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() {
if (!props.image?.url) return
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')
}
function onImageLoad(event: Event) {
const img = event.target as HTMLImageElement
naturalWidth.value = img.naturalWidth
naturalHeight.value = img.naturalHeight
dimensionsLoaded.value = true
}
</script>
<template>
<UModal
:open="open && !!image"
:title="t('image.previewTitle')"
:description="t('image.previewSubtitle')"
:ui="{ content: 'max-w-5xl' }"
@update:open="emit('update:open', $event)"
>
<template
v-if="image"
#body
>
<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(60vh,24rem)] w-full object-contain"
@load="onImageLoad"
>
</div>
<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="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 text-muted"
/>
{{ image.storage.name }}
</span>
</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="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 embedFormatItems"
:key="item.value"
size="xs"
class="flex-1 justify-center"
:variant="embedFormat === item.value ? 'solid' : 'ghost'"
:color="embedFormat === item.value ? 'primary' : 'neutral'"
:label="item.label"
@click="selectEmbedFormat(item.value)"
/>
</div>
<div class="mt-2 flex items-center gap-2">
<UInput
:model-value="previewValue"
readonly
size="sm"
class="min-w-0 flex-1 font-mono text-xs"
/>
<CopyButton
:label="t('common.copy')"
:value="previewValue"
:success-title="copySuccessTitle"
/>
</div>
</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') }} {{ t('nav.account') }}
</h3> </h3>
<div class="space-y-2"> <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 <NuxtLink
to="/account/password" 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" 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"
+193 -67
View File
@@ -1,124 +1,250 @@
<script setup lang="ts"> <script setup lang="ts">
const props = defineProps<{ type PageItem = number | 'ellipsis'
const props = withDefaults(defineProps<{
page: number page: number
totalPages: number totalPages: number
total: number total: number
unit?: string unit?: string
loading?: boolean loading?: boolean
}>() pageSize?: number
pageSizeOptions?: number[]
}>(), {
loading: false,
pageSizeOptions: () => [10, 20, 30, 50]
})
const emit = defineEmits<{ const emit = defineEmits<{
'update:page': [page: number] 'update:page': [page: number]
'update:pageSize': [pageSize: number]
}>() }>()
const { t } = useI18n() const { t } = useI18n()
const unitLabel = computed(() => props.unit ?? t('common.itemsUnit')) 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) { function goTo(target: number) {
if (target < 1 || target > props.totalPages || props.loading) { if (target < 1 || target > props.totalPages || props.loading) return
return if (target === props.page) return
}
if (target === props.page) {
jumpInput.value = ''
return
}
emit('update:page', target) emit('update:page', target)
} }
function submitJump() { function onPageSizeChange(value: unknown) {
const raw = String(jumpInput.value ?? '').trim() const size = Number(value)
if (!raw) return if (!Number.isFinite(size) || size <= 0 || size === props.pageSize) return
const parsed = Number.parseInt(raw, 10) emit('update:pageSize', size)
if (!Number.isFinite(parsed)) return
goTo(parsed)
} }
watch(() => props.page, () => { function jumpToPage() {
jumpInput.value = '' 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> </script>
<template> <template>
<div <div
v-if="total > 0" 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 <div class="flex flex-col gap-3">
v-if="totalPages > 1" <div class="flex items-center justify-between gap-2 sm:hidden">
class="text-sm text-muted" <p class="text-sm text-muted">
> {{ t('pagination.totalCount', { total, unit: unitLabel }) }}
{{ t('pagination.pageOf', { page, totalPages, total, unit: unitLabel }) }}
</p> </p>
<p <USelect
v-else v-if="pageSize !== undefined"
class="text-sm text-muted" :model-value="pageSize"
> :items="pageSizeItems"
{{ t('pagination.totalOnly', { total, unit: unitLabel }) }} value-key="value"
size="sm"
class="w-[6.5rem] shrink-0"
:aria-label="t('pagination.pageSize')"
:disabled="loading"
@update:model-value="onPageSizeChange"
/>
</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> </p>
<div <div class="flex flex-col gap-3 sm:flex-row sm:flex-wrap sm:items-center sm:justify-end sm:gap-3">
v-if="totalPages > 1" <USelect
class="flex flex-wrap items-center justify-center gap-1" v-if="pageSize !== undefined"
> :model-value="pageSize"
<UButton :items="pageSizeItems"
icon="i-lucide-chevrons-left" value-key="value"
variant="outline"
size="sm" 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')" :aria-label="t('pagination.first')"
:disabled="page <= 1 || loading" :disabled="page <= 1 || loading"
@click="goTo(1)" @click="goTo(1)"
>
<UIcon
name="i-lucide-chevrons-left"
class="size-4"
/> />
<UButton </button>
icon="i-lucide-chevron-left" <button
variant="outline" type="button"
size="sm" :class="[navButtonClass, 'size-9 sm:size-8']"
:aria-label="t('pagination.prev')" :aria-label="t('pagination.prev')"
:disabled="page <= 1 || loading" :disabled="page <= 1 || loading"
@click="goTo(page - 1)" @click="goTo(page - 1)"
>
<UIcon
name="i-lucide-chevron-left"
class="size-4"
/> />
<UButton </button>
icon="i-lucide-chevron-right"
variant="outline" <p
size="sm" 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')" :aria-label="t('pagination.next')"
:disabled="page >= totalPages || loading" :disabled="page >= totalPages || loading"
@click="goTo(page + 1)" @click="goTo(page + 1)"
>
<UIcon
name="i-lucide-chevron-right"
class="size-4"
/> />
<UButton </button>
icon="i-lucide-chevrons-right" <button
variant="outline" type="button"
size="sm" :class="[navButtonClass, 'hidden size-8 sm:inline-flex']"
:aria-label="t('pagination.last')" :aria-label="t('pagination.last')"
:disabled="page >= totalPages || loading" :disabled="page >= totalPages || loading"
@click="goTo(totalPages)" @click="goTo(totalPages)"
/>
<form
class="ml-1 flex items-center gap-1"
@submit.prevent="submitJump"
> >
<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 <UInput
v-model="jumpInput" v-model="jumpPageInput"
type="number" type="number"
:min="1" min="1"
:max="totalPages" :max="totalPages"
size="sm" size="sm"
class="w-16" class="w-14"
:placeholder="t('pagination.pagePlaceholder')"
:disabled="loading"
:aria-label="t('pagination.pagePlaceholder')" :aria-label="t('pagination.pagePlaceholder')"
@keyup.enter="submitJump" :disabled="loading"
/> @blur="jumpToPage"
<UButton
type="button"
size="sm"
variant="outline"
:label="t('pagination.goTo')"
:disabled="loading || !String(jumpInput ?? '').trim()"
@click="submitJump"
/> />
<span v-if="t('pagination.goToSuffix')">{{ t('pagination.goToSuffix') }}</span>
</form> </form>
</div> </div>
</div> </div>
</div>
</div>
</template> </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"> <script setup lang="ts">
withDefaults(
defineProps<{
embedded?: boolean
}>(),
{
embedded: false
}
)
const emit = defineEmits<{ const emit = defineEmits<{
back: [] back: []
}>() }>()
@@ -57,17 +48,8 @@ onMounted(() => {
</script> </script>
<template> <template>
<div <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">
class="flex flex-col overflow-hidden max-sm:overflow-visible" <div class="flex items-start justify-between gap-3 border-b border-default px-5 py-4 sm:px-6">
: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="flex min-w-0 items-start gap-2"> <div class="flex min-w-0 items-start gap-2">
<UIcon <UIcon
name="i-lucide-settings-2" name="i-lucide-settings-2"
@@ -83,7 +65,6 @@ onMounted(() => {
</div> </div>
</div> </div>
<UButton <UButton
v-if="!embedded"
:label="t('common.back')" :label="t('common.back')"
icon="i-lucide-arrow-left" icon="i-lucide-arrow-left"
variant="ghost" variant="ghost"
@@ -95,10 +76,7 @@ onMounted(() => {
/> />
</div> </div>
<div <div class="flex flex-1 flex-col justify-center p-5 sm:p-6">
class="p-5 sm:p-6"
:class="embedded ? '' : 'flex flex-1 flex-col justify-center'"
>
<div class="grid gap-5 sm:grid-cols-3 sm:gap-6"> <div class="grid gap-5 sm:grid-cols-3 sm:gap-6">
<div class="space-y-4"> <div class="space-y-4">
<h3 class="text-sm font-semibold"> <h3 class="text-sm font-semibold">
@@ -128,9 +106,7 @@ onMounted(() => {
class="mt-0.5" class="mt-0.5"
/> />
<span class="min-w-0 flex-1"> <span class="min-w-0 flex-1">
<span <span class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm">
class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm"
>
<span>{{ t('preferences.autoDeletePrefix') }}</span> <span>{{ t('preferences.autoDeletePrefix') }}</span>
<UInput <UInput
v-model.number="userAutoDeleteDaysDraft" v-model.number="userAutoDeleteDaysDraft"
@@ -139,11 +115,7 @@ onMounted(() => {
max="3650" max="3650"
size="xs" size="xs"
class="w-14 tabular-nums" class="w-14 tabular-nums"
:class=" :class="userAutoDeleteEnabled ? '' : 'pointer-events-none opacity-40'"
userAutoDeleteEnabled
? ''
: 'pointer-events-none opacity-40'
"
/> />
<span>{{ t('preferences.autoDeleteSuffix') }}</span> <span>{{ t('preferences.autoDeleteSuffix') }}</span>
</span> </span>
@@ -171,9 +143,7 @@ onMounted(() => {
<p class="text-xs leading-relaxed text-muted"> <p class="text-xs leading-relaxed text-muted">
{{ t('preferences.webpQualityHint') }} {{ t('preferences.webpQualityHint') }}
</p> </p>
<div <div class="flex items-center justify-between gap-2 text-sm text-muted">
class="flex items-center justify-between gap-2 text-sm text-muted"
>
<span>{{ t('preferences.current', { n: clientWebpQuality }) }}</span> <span>{{ t('preferences.current', { n: clientWebpQuality }) }}</span>
<span>{{ clientQualityLevel }}</span> <span>{{ clientQualityLevel }}</span>
</div> </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>
+110 -151
View File
@@ -1,16 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import type { StorageBackendItem } from '~/types/storage' 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<{ const props = defineProps<{
backend: StorageBackendItem backend: StorageBackendItem
envOverride?: boolean envOverride?: boolean
@@ -35,181 +25,150 @@ const typeLabel = computed(() =>
props.backend.type === 'local' ? t('storage.backendLocal') : t('storage.backendCloud') 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 actionsDisabled = computed(() => props.envOverride || props.busy)
const actions = computed<CardAction[]>(() => { const isLocal = computed(() => props.backend.type === 'local')
const isLocal = props.backend.type === 'local'
const items: CardAction[] = []
if (!props.backend.isDefault && props.backend.enabled) { function canSetDefault() {
items.push({ return !props.backend.isDefault && props.backend.enabled
key: 'default',
icon: 'i-lucide-star',
label: t('storage.setDefault'),
shortLabel: isLocal ? t('storage.setDefault') : t('storage.actionSetDefault'),
onClick: () => emit('setDefault')
})
} }
if (props.backend.type === 's3') { function canEdit() {
items.push({ return props.backend.type === 's3'
key: 'edit',
icon: 'i-lucide-pencil',
label: t('common.edit'),
shortLabel: t('common.edit'),
onClick: () => emit('edit')
})
} }
items.push({ function canToggle() {
key: 'test', return props.backend.type !== 'local'
icon: 'i-lucide-plug-zap',
label: t('storage.testConnection'),
shortLabel: isLocal ? t('storage.testConnection') : t('storage.actionTest'),
onClick: () => emit('test')
})
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) { function canDelete() {
items.push({ return props.backend.type !== 'local' && !props.backend.isDefault
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'
}
})
</script> </script>
<template> <template>
<article <article
class="flex h-full flex-col rounded-2xl border border-default bg-elevated p-4 shadow-sm" class="flex h-full flex-col rounded-xl border border-default bg-elevated p-4 sm:p-5"
:class="{ :class="{ 'opacity-75': !backend.enabled }"
'ring-2 ring-primary/30': backend.isDefault,
'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 <UIcon
:name="typeIcon" :name="typeIcon"
class="size-4.5" class="size-5"
/> />
</div> </div>
<div class="min-w-0"> <h3 class="truncate text-base font-semibold">
<h3 class="truncate text-sm font-semibold">
{{ backend.name }} {{ backend.name }}
</h3> </h3>
<p class="mt-0.5 text-xs text-muted">
{{ typeLabel }}
<template v-if="bucketLine">
· {{ bucketLine }}
</template>
</p>
</div> </div>
</div> <div class="flex shrink-0 flex-wrap justify-end gap-1.5">
<div class="flex shrink-0 flex-wrap justify-end gap-1"> <span
<UBadge v-if="backend.isDefault"
v-if="backend.enabled" class="inline-flex rounded-md bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary"
color="success" >
variant="subtle" {{ t('storage.badgeDefaultStorage') }}
size="xs" </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') }} {{ t('storage.badgeEnabled') }}
</UBadge> </span>
<UBadge <span
v-if="backend.isDefault" v-else
color="primary" class="inline-flex rounded-md bg-muted px-2 py-0.5 text-xs font-medium text-muted"
variant="subtle"
size="xs"
>
{{ t('storage.badgeDefault') }}
</UBadge>
<UBadge
v-if="!backend.enabled"
color="warning"
variant="subtle"
size="xs"
> >
{{ t('storage.badgeDisabled') }} {{ t('storage.badgeDisabled') }}
</UBadge> </span>
</div> </div>
</div> </div>
<div class="mt-4">
<StorageUsageBar <StorageUsageBar
:capacity="backend.capacity" :capacity="backend.capacity"
:index-bytes="backend.usage.bytes" :index-bytes="backend.usage.bytes"
/> />
<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> </div>
<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> </div>
</article> </article>
</template> </template>
@@ -6,6 +6,7 @@ type StorageProvider = 'r2' | 'cos' | 'oss' | 'aws' | 'custom'
export interface StorageFormPayload { export interface StorageFormPayload {
name: string name: string
provider: StorageProvider
config: { config: {
endpoint: string endpoint: string
region: string region: string
@@ -158,6 +159,7 @@ watch(provider, (value) => {
function handleSubmit() { function handleSubmit() {
emit('submit', { emit('submit', {
name: name.value.trim() || providerLabel(provider.value), name: name.value.trim() || providerLabel(provider.value),
provider: provider.value,
config: { config: {
endpoint: endpoint.value.trim(), endpoint: endpoint.value.trim(),
region: region.value.trim() || 'auto', 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>
+26 -29
View File
@@ -36,56 +36,53 @@ function formatOptional(bytes: number | null): string {
<template> <template>
<div class="space-y-3"> <div class="space-y-3">
<div class="grid grid-cols-3 gap-2 text-center text-xs"> <div class="grid grid-cols-2 gap-3 sm:grid-cols-4">
<div class="rounded-lg bg-muted/30 px-2 py-2"> <div>
<p class="text-muted"> <p class="text-xs 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">
{{ $t('storage.statUsed') }} {{ $t('storage.statUsed') }}
</p> </p>
<p class="mt-1 font-medium tabular-nums text-highlighted"> <p class="mt-1 text-sm font-semibold tabular-nums">
{{ formatFileSize(displayUsedBytes) }} {{ formatFileSize(displayUsedBytes) }}
</p> </p>
</div> </div>
<div class="rounded-lg bg-muted/30 px-2 py-2"> <div>
<p class="text-muted"> <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') }} {{ $t('storage.statFree') }}
</p> </p>
<p <p
class="mt-1 font-medium tabular-nums" class="mt-1 text-sm font-semibold tabular-nums"
:class="overQuota ? 'text-error' : 'text-highlighted'" :class="overQuota ? 'text-error' : ''"
> >
{{ formatOptional(capacity.freeBytes) }} {{ formatOptional(capacity.freeBytes) }}
</p> </p>
</div> </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>
<div <div
v-if="hasBar" 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 <div
class="h-full rounded-full transition-all" class="h-full rounded-full transition-all"
:class="overQuota ? 'bg-error/80' : 'bg-primary/70'" :class="overQuota ? 'bg-error/80' : 'bg-primary'"
:style="{ width: `${barWidth}%` }" :style="{ width: `${barWidth}%` }"
/> />
</div> </div>
</div> </div>
</div>
</template> </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 AuthStatus = 'checking' | 'authenticated' | 'unauthenticated'
export type UserRole = 'admin' | 'user' export type UserRole = 'admin' | 'user'
@@ -8,11 +10,18 @@ export interface AuthUser {
role: UserRole role: UserRole
} }
export interface LoginVerificationPublicConfig {
method: 'slider' | 'turnstile' | 'cap'
turnstileSiteKey?: string
capApiEndpoint?: string
}
export interface AuthStatusResponse { export interface AuthStatusResponse {
initialized: boolean initialized: boolean
allowRegistration: boolean allowRegistration: boolean
legacyMode: boolean legacyMode: boolean
needsMigration: boolean needsMigration: boolean
loginVerification: LoginVerificationPublicConfig
user: AuthUser | null 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 type AuthActionResult = { ok: true } | { ok: false, error: string }
export interface LoginCaptchaPayload { export type { LoginVerificationPayload }
captchaId: string
captchaPosition: number 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() { export function useAuth() {
@@ -123,7 +142,7 @@ export function useAuth() {
async function login( async function login(
credentials: { username: string, password: string } credentials: { username: string, password: string }
| { secret: string }, | { secret: string },
captcha: LoginCaptchaPayload verification: LoginVerificationPayload
): Promise<{ ok: boolean, needsMigration?: boolean, error?: string }> { ): Promise<{ ok: boolean, needsMigration?: boolean, error?: string }> {
try { try {
const result = await $fetch<{ const result = await $fetch<{
@@ -135,8 +154,7 @@ export function useAuth() {
credentials: 'include', credentials: 'include',
body: { body: {
...credentials, ...credentials,
captchaId: captcha.captchaId, ...buildVerificationBody(verification)
captchaPosition: captcha.captchaPosition
} }
}) })
if (result.needsMigration) { if (result.needsMigration) {
@@ -159,7 +177,8 @@ export function useAuth() {
async function register( async function register(
username: string, username: string,
password: string password: string,
verification: LoginVerificationPayload
): Promise<AuthActionResult> { ): Promise<AuthActionResult> {
const validationError = validateAuthInput(username, password) const validationError = validateAuthInput(username, password)
if (validationError) { if (validationError) {
@@ -172,7 +191,11 @@ export function useAuth() {
{ {
method: 'POST', method: 'POST',
credentials: 'include', credentials: 'include',
body: { username: username.trim(), password } body: {
username: username.trim(),
password,
...buildVerificationBody(verification)
}
} }
) )
user.value = result.user user.value = result.user
@@ -291,15 +314,19 @@ export function useAuth() {
async function logout() { async function logout() {
try { try {
await $fetch('/api/auth/logout', { method: 'POST' }) await $fetch('/api/auth/logout', { method: 'POST', credentials: 'include' })
} catch { } catch {
// 忽略登出失败 // 忽略登出失败
} finally { } finally {
status.value = 'unauthenticated' status.value = 'unauthenticated'
user.value = null user.value = null
authStatus.value = null
hasValidatedOnce.value = true hasValidatedOnce.value = true
} }
try {
await fetchStatus()
} catch {
// 保留既有公开配置(loginVerification 等)
}
} }
function handleAuthError(error: unknown) { function handleAuthError(error: unknown) {
+72 -4
View File
@@ -3,12 +3,13 @@ import type {
ImageListResponse ImageListResponse
} from '~/types/image' } from '~/types/image'
const PAGE_SIZE = 12 const PAGE_SIZE_DEFAULT = 10
export function useImageList() { export function useImageList() {
const { t } = useI18n() const { t } = useI18n()
const items = ref<ImageItem[]>([]) const items = ref<ImageItem[]>([])
const page = ref(1) const page = ref(1)
const pageSize = ref(PAGE_SIZE_DEFAULT)
const totalPages = ref(1) const totalPages = ref(1)
const total = ref(0) const total = ref(0)
const loading = ref(false) const loading = ref(false)
@@ -17,6 +18,8 @@ export function useImageList() {
const searchQuery = ref('') const searchQuery = ref('')
const activeSearch = ref('') const activeSearch = ref('')
const activeStorageBackend = ref('all') const activeStorageBackend = ref('all')
const activeContentType = ref('all')
const activeUploadSource = ref('all')
const storageBackendOptions = ref<Array<{ id: string, name: string }>>([]) const storageBackendOptions = ref<Array<{ id: string, name: string }>>([])
function storageQueryParams(): Record<string, string> { function storageQueryParams(): Record<string, string> {
@@ -25,8 +28,21 @@ export function useImageList() {
return { backendId } 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> { function listQueryParams(): Record<string, string> {
return storageQueryParams() return filterQueryParams()
} }
function matchesActiveStorage(item: ImageItem) { function matchesActiveStorage(item: ImageItem) {
@@ -72,7 +88,7 @@ export function useImageList() {
const response = await $fetch<ImageListResponse>('/api/images', { const response = await $fetch<ImageListResponse>('/api/images', {
credentials: 'include', credentials: 'include',
query: { query: {
limit: PAGE_SIZE, limit: pageSize.value,
page: targetPage, page: targetPage,
...listQueryParams() ...listQueryParams()
} }
@@ -100,7 +116,7 @@ export function useImageList() {
credentials: 'include', credentials: 'include',
query: { query: {
q, q,
limit: PAGE_SIZE, limit: pageSize.value,
page: targetPage, page: targetPage,
...listQueryParams() ...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() { async function submitSearch() {
const q = searchQuery.value.trim() const q = searchQuery.value.trim()
activeSearch.value = q 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[]) { function prependItems(newItems: ImageItem[]) {
const matched = newItems.filter(item => matchesActiveStorage(item)) const matched = newItems.filter(item => matchesActiveStorage(item))
if (!matched.length || page.value !== 1) return if (!matched.length || page.value !== 1) return
@@ -220,10 +281,13 @@ export function useImageList() {
return { return {
items, items,
page, page,
pageSize,
totalPages, totalPages,
total, total,
loading, loading,
activeStorageBackend, activeStorageBackend,
activeContentType,
activeUploadSource,
storageBackendOptions, storageBackendOptions,
searchQuery, searchQuery,
activeSearch, activeSearch,
@@ -234,9 +298,13 @@ export function useImageList() {
refreshList, refreshList,
initializeList, initializeList,
setActiveStorageBackend, setActiveStorageBackend,
setActiveContentType,
setActiveUploadSource,
resetFilters,
loadStorageBackendOptions, loadStorageBackendOptions,
submitSearch, submitSearch,
goToPage, goToPage,
setPageSize,
prependItems, prependItems,
removeItems removeItems
} }
+34 -263
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 { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
@@ -31,6 +22,7 @@ const regenerating = ref(false)
const confirmRegenerateOpen = ref(false) const confirmRegenerateOpen = ref(false)
const regenerateResultOpen = ref(false) const regenerateResultOpen = ref(false)
const newToken = ref('') const newToken = ref('')
const activeEndpointId = ref('upload')
const baseUrl = computed(() => { const baseUrl = computed(() => {
const configured = settings.value?.env.siteBaseUrl const configured = settings.value?.env.siteBaseUrl
@@ -43,106 +35,24 @@ const baseUrl = computed(() => {
const tokenDisplay = computed(() => settings.value?.apiUploadToken ?? '') const tokenDisplay = computed(() => settings.value?.apiUploadToken ?? '')
const hasToken = computed(() => tokenDisplay.value.length > 0) 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(() => const authHeader = computed(() =>
hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN' hasToken.value ? tokenDisplay.value : 'YOUR-TOKEN'
) )
const authHeaderFlag = computed(() => `-H 'Auth-Token: ${authHeader.value}'`) const apiDocs = computed(() =>
buildApiDocs({
const apiDocs = computed<ApiDocItem[]>(() => { baseUrl: baseUrl.value,
const uploadDescription = t('api.docs.upload.desc') authHeader: authHeader.value
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(() => ({ const activeEndpoint = computed(() =>
method: 'POST' as const, apiDocs.value.find(endpoint => endpoint.id === activeEndpointId.value) ?? apiDocs.value[0]
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
}
}
async function loadSettings() { async function loadSettings() {
loading.value = true loading.value = true
@@ -251,175 +161,36 @@ watch(isAuthenticated, async (authed, prev) => {
<AppShell v-else> <AppShell v-else>
<section class="overflow-hidden rounded-2xl border border-default bg-elevated shadow-sm"> <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"> <div class="flex flex-col lg:flex-row lg:items-stretch">
<UIcon <ApiSidebar
name="i-lucide-key-round" :endpoints="apiDocs"
class="size-5 text-primary" :active-id="activeEndpointId"
/> @select="activeEndpointId = $event"
<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')"
/> />
<UAlert <div class="flex min-w-0 flex-1 flex-col bg-default lg:border-r lg:border-default">
v-else-if="!isAdmin" <ApiTokenCard
color="info" :token="tokenDisplay"
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"
:loading="loading" :loading="loading"
:regenerating="regenerating"
:can-regenerate="canRegenerate"
:token-source="settings?.tokenSource"
:env-token-override="settings?.envTokenOverride"
:is-admin="isAdmin"
@regenerate="requestRegenerate"
/> />
<div class="flex gap-2">
<CopyButton <ApiDocView
:label="t('common.copy')" v-if="activeEndpoint"
:value="tokenDisplay" :endpoint="activeEndpoint"
/>
<UButton
icon="i-lucide-refresh-cw"
:label="t('api.regenerate')"
color="warning"
variant="soft"
:loading="regenerating"
:disabled="!canRegenerate"
@click="requestRegenerate"
/> />
</div> </div>
</div>
<p <ApiDebugger
v-if="settings" v-if="activeEndpoint"
class="text-xs text-muted" :endpoint="activeEndpoint"
> :token="tokenDisplay"
{{ 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"
/> />
<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> </div>
</section> </section>
</AppShell> </AppShell>
+151 -211
View File
@@ -1,7 +1,11 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ImageItem } from '~/types/image'
interface StatsResponse { interface StatsResponse {
uploadToday: number uploadToday: number
uploadYesterday: number
uploadMonth: number uploadMonth: number
uploadLastMonth: number
deleteToday: number deleteToday: number
deleteMonth: number deleteMonth: number
uploadTotal: number uploadTotal: number
@@ -13,32 +17,39 @@ interface StatsResponse {
web: number web: number
api: number api: number
} }
storageUsage: {
usedBytes: number
totalBytes: number | null
percent: number | null
}
} }
const { const {
items, items,
page: galleryPage, page: galleryPage,
pageSize: galleryPageSize,
totalPages: galleryTotalPages, totalPages: galleryTotalPages,
total: galleryTotal, total: galleryTotal,
loading: galleryLoading, loading: galleryLoading,
searchQuery, searchQuery,
activeSearch, activeSearch,
listSummary,
refreshList,
fetchList, fetchList,
fetchSearch, fetchSearch,
fetchTotal, fetchTotal,
submitSearch, submitSearch,
goToPage, goToPage,
setPageSize,
removeItems, removeItems,
activeStorageBackend, activeStorageBackend,
storageBackendOptions,
setActiveStorageBackend, setActiveStorageBackend,
storageBackendOptions,
activeUploadSource,
setActiveUploadSource,
resetFilters,
loadStorageBackendOptions loadStorageBackendOptions
} = useImageList() } = useImageList()
const { formatFileSize } = useFileSize() const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus } = useAuth()
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
@@ -52,9 +63,20 @@ const deleteModalOpen = ref(false)
const deleteTargetKeys = ref<string[]>([]) const deleteTargetKeys = ref<string[]>([])
const batchDeleting = ref(false) const batchDeleting = ref(false)
const showScrollTop = 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' }, { label: t('stats.filterStorageAll'), value: 'all' },
...storageBackendOptions.value.map(backend => ({ ...storageBackendOptions.value.map(backend => ({
label: backend.name, label: backend.name,
@@ -64,47 +86,6 @@ const storageSelectItems = computed(() => [
const selectedCount = computed(() => selectedKeys.value.size) 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() { function onWindowScroll() {
showScrollTop.value = window.scrollY > 400 showScrollTop.value = window.scrollY > 400
} }
@@ -133,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() { async function reloadGallery() {
if (activeSearch.value) { if (activeSearch.value) {
await fetchSearch(galleryPage.value) await fetchSearch(galleryPage.value)
@@ -163,7 +133,8 @@ async function refreshAll() {
reloadGallery(), reloadGallery(),
loadStorageBackendOptions() loadStorageBackendOptions()
]) ])
currentStorage.value = activeStorageBackend.value currentUploadSource.value = activeUploadSource.value
currentStorageBackend.value = activeStorageBackend.value
} catch (error: unknown) { } catch (error: unknown) {
handleAuthError(error) handleAuthError(error)
if (isAuthenticated.value) { if (isAuthenticated.value) {
@@ -174,9 +145,9 @@ async function refreshAll() {
} }
} }
async function handleStorageChange(backendId: string) { async function handleStorageBackendChange(backendId: string) {
if (!isAuthenticated.value) return if (!isAuthenticated.value) return
currentStorage.value = backendId currentStorageBackend.value = backendId
selectedKeys.value = new Set() selectedKeys.value = new Set()
try { try {
await setActiveStorageBackend(backendId) await setActiveStorageBackend(backendId)
@@ -185,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() { async function handleSearch() {
if (!isAuthenticated.value) return if (!isAuthenticated.value) return
selectedKeys.value = new Set() selectedKeys.value = new Set()
@@ -195,14 +193,10 @@ async function handleSearch() {
} }
} }
async function clearSearch() {
searchQuery.value = ''
if (!activeSearch.value) return
await refreshGallery()
}
function requestDelete(key: string) { function requestDelete(key: string) {
if (!isAuthenticated.value) return if (!isAuthenticated.value) return
previewOpen.value = false
previewImage.value = null
deleteTargetKeys.value = [key] deleteTargetKeys.value = [key]
deleteModalOpen.value = true deleteModalOpen.value = true
} }
@@ -217,6 +211,10 @@ function requestBatchDelete() {
deleteModalOpen.value = true deleteModalOpen.value = true
} }
function clearSelection() {
selectedKeys.value = new Set()
}
async function confirmDelete() { async function confirmDelete() {
const keys = [...deleteTargetKeys.value] const keys = [...deleteTargetKeys.value]
if (!keys.length || !isAuthenticated.value) return if (!keys.length || !isAuthenticated.value) return
@@ -279,6 +277,8 @@ async function confirmDelete() {
async function handleGalleryPageChange(targetPage: number) { async function handleGalleryPageChange(targetPage: number) {
selectedKeys.value = new Set() selectedKeys.value = new Set()
previewOpen.value = false
previewImage.value = null
try { try {
await goToPage(targetPage) await goToPage(targetPage)
} catch (error: unknown) { } catch (error: unknown) {
@@ -286,6 +286,27 @@ 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
}
function requestPreviewDelete() {
if (!previewImage.value) return
requestDelete(previewImage.value.key)
}
onMounted(async () => { onMounted(async () => {
window.addEventListener('scroll', onWindowScroll, { passive: true }) window.addEventListener('scroll', onWindowScroll, { passive: true })
const status = await fetchStatus() const status = await fetchStatus()
@@ -357,168 +378,85 @@ watch(isAuthenticated, async (authed, prev) => {
/> />
</div> </div>
<section class="grid gap-3 lg:grid-cols-3 lg:items-stretch"> <GalleryStatsOverview
<div class="grid grid-cols-2 gap-3 lg:col-span-2 lg:grid-cols-4"> :stats="stats"
<div :loading="statsLoading"
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>
<div class="flex h-full min-h-0 flex-col rounded-xl border border-default bg-elevated p-4 lg:col-span-1"> <section class="space-y-3">
<h2 class="shrink-0 text-sm font-medium text-muted"> <div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-2">
{{ t('stats.sourceDistribution') }} <GallerySelectionBar
</h2> :items="items"
<div :selected-keys="selectedKeys"
v-if="!sourceUploadTotal" @update:selected-keys="updateSelectedKeys"
class="flex flex-1 items-center justify-center text-center text-xs text-muted" @clear="clearSelection"
>
{{ 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-4"> <GalleryFilterBar
<div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-3"> v-model:search-query="searchQuery"
<div class="min-w-0"> :storage-backend="currentStorageBackend"
<h2 class="text-lg font-medium"> :storage-backend-items="storageBackendItems"
{{ t('stats.gallery') }} :upload-source="currentUploadSource"
</h2> :upload-source-items="uploadSourceItems"
<p :view-mode="viewMode"
v-if="!galleryLoading" :selected-count="selectedCount"
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" :loading="galleryLoading"
> :show-batch-delete="true"
<span class="hidden sm:inline">{{ t('common.search') }}</span> @update:storage-backend="handleStorageBackendChange"
</UButton> @update:upload-source="handleUploadSourceChange"
<UButton @update:view-mode="viewMode = $event"
v-if="activeSearch" @search="handleSearch"
type="button" @reset="handleResetFilters"
icon="i-lucide-x" @batch-delete="requestBatchDelete"
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-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>
</div> </div>
<div <div
v-if="galleryLoading" 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 <USkeleton
v-for="n in 12" v-for="n in 10"
:key="n" :key="n"
class="aspect-square rounded-lg" :class="viewMode === 'grid' ? 'aspect-[4/3] rounded-lg' : 'h-16 rounded-lg'"
/> />
</div> </div>
<ImageGrid <ImageGrid
v-else v-else-if="viewMode === 'grid'"
gallery
:show-key="false" :show-key="false"
show-storage show-storage
:items="items" :items="items"
:selected-keys="selectedKeys" :selected-keys="selectedKeys"
:deleting-keys="deletingKeys" :selectable="true"
@update:selected-keys="selectedKeys = $event" :allow-delete="true"
@delete="requestDelete" @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
v-model:open="previewOpen"
:image="previewImage"
show-storage
:deleting="previewImage ? deletingKeys.has(previewImage.key) : false"
:allow-delete="true"
@delete="requestPreviewDelete"
/> />
<PaginationBar <PaginationBar
@@ -526,9 +464,11 @@ watch(isAuthenticated, async (authed, prev) => {
:page="galleryPage" :page="galleryPage"
:total-pages="galleryTotalPages" :total-pages="galleryTotalPages"
:total="galleryTotal" :total="galleryTotal"
:page-size="galleryPageSize"
:unit="t('common.imagesUnit')" :unit="t('common.imagesUnit')"
:loading="galleryLoading" :loading="galleryLoading"
@update:page="handleGalleryPageChange" @update:page="handleGalleryPageChange"
@update:page-size="handleGalleryPageSizeChange"
/> />
</section> </section>
+25 -2
View File
@@ -15,6 +15,8 @@ const { t } = useI18n()
const sessionItems = ref<ImageItem[]>([]) const sessionItems = ref<ImageItem[]>([])
const deletingKeys = ref<Set<string>>(new Set()) const deletingKeys = ref<Set<string>>(new Set())
const emptySelection = ref(new Set<string>()) const emptySelection = ref(new Set<string>())
const previewOpen = ref(false)
const previewImage = ref<ImageItem | null>(null)
const showProgress = computed( const showProgress = computed(
() => () =>
@@ -123,6 +125,10 @@ async function handleDelete(key: string) {
query: { key } query: { key }
}) })
sessionItems.value = sessionItems.value.filter(item => item.key !== key) sessionItems.value = sessionItems.value.filter(item => item.key !== key)
if (previewImage.value?.key === key) {
previewOpen.value = false
previewImage.value = null
}
toast.add({ title: t('stats.deletedSingle'), color: 'success' }) toast.add({ title: t('stats.deletedSingle'), color: 'success' })
} catch (error: unknown) { } catch (error: unknown) {
handleAuthError(error) handleAuthError(error)
@@ -132,6 +138,16 @@ async function handleDelete(key: string) {
deletingKeys.value = new Set(deletingKeys.value) deletingKeys.value = new Set(deletingKeys.value)
} }
} }
function openPreview(image: ImageItem) {
previewImage.value = image
previewOpen.value = true
}
function requestPreviewDelete() {
if (!previewImage.value) return
void handleDelete(previewImage.value.key)
}
</script> </script>
<template> <template>
@@ -178,14 +194,21 @@ async function handleDelete(key: string) {
<ImageGrid <ImageGrid
:items="sessionItems" :items="sessionItems"
:selected-keys="emptySelection" :selected-keys="emptySelection"
:deleting-keys="deletingKeys"
:selectable="false" :selectable="false"
:show-key="false" :show-key="false"
:empty-text="t('upload.sessionEmpty')" :empty-text="t('upload.sessionEmpty')"
@update:selected-keys="() => {}" @update:selected-keys="() => {}"
@delete="handleDelete" @preview="openPreview"
/> />
</section> </section>
<ImagePreviewModal
v-model:open="previewOpen"
:image="previewImage"
:deleting="previewImage ? deletingKeys.has(previewImage.key) : false"
:allow-delete="true"
@delete="requestPreviewDelete"
/>
</AppShell> </AppShell>
</div> </div>
</template> </template>
+2 -613
View File
@@ -1,618 +1,7 @@
<script setup lang="ts"> <script setup lang="ts">
import type { ActivityLogListResponse, ActivityLogStorage, LogAction, LogSource } from '~/types/logs' await navigateTo({ path: '/settings', query: { tab: 'logs' } }, { replace: true })
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) return key
const slash = key.lastIndexOf('/')
return slash >= 0 ? key.slice(slash + 1) : 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<{ imageBaseUrl: string, hideFolderInUrl: boolean }>('/api/settings', {
credentials: 'include'
})
imageLinkBase.value = data.imageBaseUrl
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()
}
})
</script> </script>
<template> <template>
<div class="min-h-screen"> <div />
<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>
</template> </template>
+39 -4
View File
@@ -2,9 +2,10 @@
import logoLight from '~/assets/image/logo-light.png' import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png' import logoDark from '~/assets/image/logo-dark.png'
import { isPasswordValid } from '~/utils/password-strength' import { isPasswordValid } from '~/utils/password-strength'
import type { LoginVerificationPayload } from '~/types/auth'
const router = useRouter() const router = useRouter()
const { register, fetchStatus } = useAuth() const { register, fetchStatus, authStatus } = useAuth()
const toast = useToast() const toast = useToast()
const { t } = useI18n() const { t } = useI18n()
@@ -12,14 +13,34 @@ const username = ref('')
const password = ref('') const password = ref('')
const confirmPassword = ref('') const confirmPassword = ref('')
const loading = ref(false) 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(() => const canSubmit = computed(() =>
Boolean(username.value && password.value && confirmPassword.value) Boolean(verificationPayload.value)
&& Boolean(username.value && password.value && confirmPassword.value)
&& password.value === confirmPassword.value && password.value === confirmPassword.value
&& isPasswordValid(password.value) && isPasswordValid(password.value)
&& AUTH_USERNAME_PATTERN.test(username.value.trim()) && 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 () => { onMounted(async () => {
const status = await fetchStatus() const status = await fetchStatus()
if (!status.initialized && !status.legacyMode) { if (!status.initialized && !status.legacyMode) {
@@ -32,7 +53,7 @@ onMounted(async () => {
}) })
async function submit() { async function submit() {
if (!canSubmit.value || loading.value) return if (!canSubmit.value || loading.value || !verificationPayload.value) return
if (password.value !== confirmPassword.value) { if (password.value !== confirmPassword.value) {
toast.add({ title: t('auth.passwordMismatch'), color: 'error' }) toast.add({ title: t('auth.passwordMismatch'), color: 'error' })
@@ -41,11 +62,16 @@ async function submit() {
loading.value = true loading.value = true
try { try {
const result = await register(username.value.trim(), password.value) const result = await register(
username.value.trim(),
password.value,
verificationPayload.value
)
if (result.ok) { if (result.ok) {
toast.add({ title: t('auth.registerSuccess'), color: 'success' }) toast.add({ title: t('auth.registerSuccess'), color: 'success' })
await router.replace('/') await router.replace('/')
} else { } else {
await resetVerification()
toast.add({ title: result.error, color: 'error' }) toast.add({ title: result.error, color: 'error' })
} }
} finally { } finally {
@@ -142,6 +168,15 @@ async function submit() {
/> />
</div> </div>
<LoginVerification
ref="verificationRef"
:method="loginVerification.method"
:turnstile-site-key="loginVerification.turnstileSiteKey"
:cap-api-endpoint="loginVerification.capApiEndpoint"
@verified="onVerificationVerified"
@cleared="onVerificationCleared"
/>
<UButton <UButton
type="submit" type="submit"
:label="t('auth.register')" :label="t('auth.register')"
File diff suppressed because it is too large. Load diff
+52 -5
View File
@@ -2,6 +2,7 @@
import logoLight from '~/assets/image/logo-light.png' import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png' import logoDark from '~/assets/image/logo-dark.png'
import { isPasswordValid } from '~/utils/password-strength' import { isPasswordValid } from '~/utils/password-strength'
import { willActivateDomainSeparation } from '~/utils/domain-separation'
const route = useRoute() const route = useRoute()
const router = useRouter() const router = useRouter()
@@ -26,6 +27,15 @@ const domainSeparation = ref(false)
const siteBaseUrl = ref('') const siteBaseUrl = ref('')
const imageBaseUrl = ref('') const imageBaseUrl = ref('')
const loading = ref(false) const loading = ref(false)
const domainSeparationConfirmOpen = ref(false)
const domainSeparationWouldActivate = computed(() =>
willActivateDomainSeparation(
domainSeparation.value,
siteBaseUrl.value,
imageBaseUrl.value
)
)
const canSubmit = computed(() => { const canSubmit = computed(() => {
if (!username.value || !password.value || !confirmPassword.value) return false if (!username.value || !password.value || !confirmPassword.value) return false
@@ -33,7 +43,7 @@ const canSubmit = computed(() => {
if (!isPasswordValid(password.value)) return false if (!isPasswordValid(password.value)) return false
if (!AUTH_USERNAME_PATTERN.test(username.value.trim())) return false if (!AUTH_USERNAME_PATTERN.test(username.value.trim())) return false
if (domainSeparation.value) { if (domainSeparation.value) {
return Boolean(siteBaseUrl.value.trim() && imageBaseUrl.value.trim()) if (!siteBaseUrl.value.trim() || !imageBaseUrl.value.trim()) return false
} }
return true return true
}) })
@@ -49,11 +59,12 @@ onMounted(async () => {
await router.replace('/') await router.replace('/')
return return
} }
if (import.meta.client) {
siteBaseUrl.value = window.location.origin
}
}) })
const detectedOriginPlaceholder = computed(() =>
import.meta.client ? window.location.origin : ''
)
async function submit() { async function submit() {
if (!canSubmit.value || loading.value) return if (!canSubmit.value || loading.value) return
@@ -62,6 +73,18 @@ async function submit() {
return 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 loading.value = true
try { try {
const payload = { const payload = {
@@ -217,7 +240,7 @@ async function submit() {
</p> </p>
<UInput <UInput
v-model="siteBaseUrl" v-model="siteBaseUrl"
:placeholder="t('setup.siteBaseUrlPlaceholder')" :placeholder="detectedOriginPlaceholder || t('setup.siteBaseUrlPlaceholder')"
class="w-full font-mono text-sm" class="w-full font-mono text-sm"
/> />
</div> </div>
@@ -247,5 +270,29 @@ async function submit() {
/> />
</form> </form>
</div> </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> </div>
</template> </template>
+34 -23
View File
@@ -21,6 +21,11 @@ const deleteTarget = ref<StorageBackendItem | null>(null)
const deleteConfirmName = ref('') const deleteConfirmName = ref('')
const deleting = ref(false) 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() { async function loadStorage() {
loading.value = true loading.value = true
try { try {
@@ -43,6 +48,7 @@ function buildPatchBody(payload: StorageFormPayload) {
const quotaBytes = quotaToBytes(payload.quotaValue, payload.quotaUnit) const quotaBytes = quotaToBytes(payload.quotaValue, payload.quotaUnit)
const body: Record<string, unknown> = { const body: Record<string, unknown> = {
name: payload.name, name: payload.name,
provider: payload.provider,
servingMode: payload.servingMode, servingMode: payload.servingMode,
publicUrl: payload.publicUrl, publicUrl: payload.publicUrl,
quotaBytes, quotaBytes,
@@ -232,22 +238,16 @@ watch(isAuthenticated, async (authed) => {
<AdminLoginGate v-else-if="!isAuthenticated" /> <AdminLoginGate v-else-if="!isAuthenticated" />
<AppShell v-else-if="isAdmin"> <AppShell v-else-if="isAdmin">
<section class="overflow-hidden rounded-2xl border border-default bg-elevated shadow-sm"> <div class="flex items-start justify-between gap-3">
<div class="flex flex-wrap items-start justify-between gap-3 border-b border-default px-5 py-4 sm:px-6"> <div class="min-w-0">
<div class="flex items-start gap-2"> <h1 class="text-2xl font-semibold tracking-tight">
<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') }} {{ t('storage.pageTitle') }}
</h1> </h1>
<p class="mt-0.5 text-xs text-muted"> <p class="text-sm text-muted">
{{ t('storage.pageSubtitle') }} {{ t('storage.pageSubtitle') }}
</p> </p>
</div> </div>
</div>
<UButton <UButton
:label="t('storage.addBackend')" :label="t('storage.addBackend')"
icon="i-lucide-plus" icon="i-lucide-plus"
@@ -257,20 +257,15 @@ watch(isAuthenticated, async (authed) => {
/> />
</div> </div>
<div class="p-5 sm:p-6"> <section class="mt-5 space-y-5">
<UAlert <UAlert
v-if="storageData?.envOverride" v-if="storageData?.envOverride"
color="warning" color="warning"
variant="subtle" variant="subtle"
class="mb-5"
:title="t('storage.envOverride')" :title="t('storage.envOverride')"
icon="i-lucide-triangle-alert" icon="i-lucide-triangle-alert"
/> />
<p class="mb-5 text-xs text-muted">
{{ t('storage.switchHint') }}
</p>
<div <div
v-if="loading" v-if="loading"
class="flex justify-center py-16" class="flex justify-center py-16"
@@ -281,10 +276,21 @@ watch(isAuthenticated, async (authed) => {
/> />
</div> </div>
<div <template v-else-if="storageData">
v-else-if="storageData" <StorageOverview
class="grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3" :backends="storageData.backends"
> :loading="loading"
/>
<UAlert
v-if="!storageData.envOverride"
color="success"
variant="subtle"
icon="i-lucide-info"
:description="t('storage.defaultStorageTip', { name: defaultBackendName })"
/>
<div class="grid grid-cols-1 gap-4 xl:grid-cols-2">
<StorageBackendCard <StorageBackendCard
v-for="backend in storageData.backends" v-for="backend in storageData.backends"
:key="backend.id" :key="backend.id"
@@ -298,11 +304,16 @@ watch(isAuthenticated, async (authed) => {
@delete="confirmDelete(backend)" @delete="confirmDelete(backend)"
/> />
</div> </div>
</div>
<StorageSupportedBackends />
</template>
</section> </section>
</AppShell> </AppShell>
<UModal v-model:open="formOpen"> <UModal
v-model:open="formOpen"
:ui="{ content: 'max-w-2xl sm:max-w-3xl' }"
>
<template #content> <template #content>
<div class="p-5 sm:p-6"> <div class="p-5 sm:p-6">
<h2 class="mb-4 text-base font-semibold"> <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
}
+2
View File
@@ -42,6 +42,8 @@ export interface ImageItem {
name: string name: string
type: 'local' | 's3' type: 'local' | 's3'
} }
/** 上传来源:网页或 API(来自活动日志) */
uploadSource?: 'web' | 'api'
} }
export interface UploadErrorItem { export interface UploadErrorItem {
+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)
}
+24
View File
@@ -0,0 +1,24 @@
export function getFileExtension(filename: string): string {
const base = filename.split(/[/\\]/).pop() ?? filename
const dot = base.lastIndexOf('.')
if (dot <= 0 || dot === base.length - 1) return '—'
return base.slice(dot + 1).toLowerCase()
}
export function getUrlPathname(url: string): string {
try {
return decodeURIComponent(new URL(url).pathname.replace(/^\/+/, ''))
} catch {
return url
}
}
export function getStorageKeyTail(key: string): string {
const prefix = 'images/'
return key.startsWith(prefix) ? key.slice(prefix.length) : key
}
export function formatImageDimensions(width: number | null, height: number | null): string | null {
if (!width || !height) return null
return `${width} × ${height} px`
}
+1 -1
View File
@@ -10,7 +10,7 @@ services:
- "6892:6892" - "6892:6892"
# 首次访问 Web 引导创建管理员,无需预先配置环境变量 # 首次访问 Web 引导创建管理员,无需预先配置环境变量
# 可选:environment 中设置 API_UPLOAD_TOKEN、ALLOWED_REFERER_HOSTS 等 # 可选:environment 中设置 API_UPLOAD_TOKEN、ALLOWED_REFERER_HOSTS 等
# 运维:docker exec pichost reset-password | migrate [--apply] # 运维:docker exec pichost reset-password | migrate [--apply] | slider | clear-domains [--site]
volumes: volumes:
# 冒号左边改成 NAS 上的实际存图目录(飞牛示例:/vol1/1000/pichost-data) # 冒号左边改成 NAS 上的实际存图目录(飞牛示例:/vol1/1000/pichost-data)
- ./data:/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}" exec node /app/server/cli/migrate-to-single-images.mjs "${@:2}"
fi 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 "$@" exec node /app/.output/server/index.mjs "$@"
+16 -3
View File
@@ -1,4 +1,5 @@
import { defineConfig } from 'vitepress' import { defineConfig } from 'vitepress'
import { withMermaid } from 'vitepress-plugin-mermaid'
const docsBase = 'https://o96u.github.io/PicHost' const docsBase = 'https://o96u.github.io/PicHost'
@@ -16,7 +17,8 @@ const zhSidebar = [
items: [ items: [
{ text: '环境变量', link: '/guide/configuration' }, { text: '环境变量', link: '/guide/configuration' },
{ text: '反向代理', link: '/guide/reverse-proxy' }, { text: '反向代理', link: '/guide/reverse-proxy' },
{ text: '双域名分离', link: '/guide/domain-separation' } { text: '双域名分离', link: '/guide/domain-separation' },
{ text: 'Cloudflare / CF 优选', link: '/guide/cloudflare-deployment' }
] ]
}, },
{ {
@@ -31,6 +33,7 @@ const zhSidebar = [
{ {
text: '升级', text: '升级',
items: [ items: [
{ text: '更新日志', link: '/guide/changelog' },
{ text: 'v1.2 迁移', link: '/guide/migration' }, { text: 'v1.2 迁移', link: '/guide/migration' },
{ text: '常见问题', link: '/guide/faq' } { text: '常见问题', link: '/guide/faq' }
] ]
@@ -51,7 +54,8 @@ const enSidebar = [
items: [ items: [
{ text: 'Environment variables', link: '/en/guide/configuration' }, { text: 'Environment variables', link: '/en/guide/configuration' },
{ text: 'Reverse proxy', link: '/en/guide/reverse-proxy' }, { text: 'Reverse proxy', link: '/en/guide/reverse-proxy' },
{ text: 'Dual-domain separation', link: '/en/guide/domain-separation' } { text: 'Dual-domain separation', link: '/en/guide/domain-separation' },
{ text: 'Cloudflare deployment', link: '/en/guide/cloudflare-deployment' }
] ]
}, },
{ {
@@ -66,17 +70,25 @@ const enSidebar = [
{ {
text: 'Upgrade', text: 'Upgrade',
items: [ items: [
{ text: 'Changelog', link: '/en/guide/changelog' },
{ text: 'v1.2 migration', link: '/en/guide/migration' }, { text: 'v1.2 migration', link: '/en/guide/migration' },
{ text: 'FAQ', link: '/en/guide/faq' } { text: 'FAQ', link: '/en/guide/faq' }
] ]
} }
] ]
export default defineConfig({ export default withMermaid(
defineConfig({
base: '/PicHost/', base: '/PicHost/',
title: 'PicHost', title: 'PicHost',
description: '自托管图床文档 · Self-hosted image hosting docs', description: '自托管图床文档 · Self-hosted image hosting docs',
head: [['link', { rel: 'icon', href: '/PicHost/favicon.ico' }]], head: [['link', { rel: 'icon', href: '/PicHost/favicon.ico' }]],
vite: {
optimizeDeps: {
// mermaid → fastdom 为 CJS;dev 模式须预构建,否则整站白屏
include: ['mermaid', 'fastdom']
}
},
locales: { locales: {
root: { root: {
label: '简体中文', label: '简体中文',
@@ -127,3 +139,4 @@ export default defineConfig({
} }
} }
}) })
)
+1 -1
View File
@@ -1,6 +1,6 @@
# API # 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 ## Authentication
+182
View File
@@ -0,0 +1,182 @@
# Changelog
Version history and notable changes. The full log is also in the repo root [CHANGELOG.md](https://github.com/O96u/PicHost/blob/main/CHANGELOG.md).
---
## [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
- **Gallery page**: nav “Stats” renamed to “Gallery” (`/gallery`); click a thumbnail for a detail modal (full image, dimensions, upload source, storage path, link copy)
- **List actions**: select all / invert selection; single-image delete moved into the detail modal
- **Upload source**: gallery API returns web / API upload source (from activity logs)
### Improved
- README tech stack section
### Removed
- `/stats` route (no compatibility redirect)
## [1.2.4] — 2026-08-31
### Fix
- **Empty referer whitelist still blocked hotlinks**: with no Referer whitelist configured, direct browser access worked but embedded images on blogs/forums returned 403; protection now runs only when a whitelist is configured
## [1.2.3] — 2026-08-30
### Fix
- **Short links + date-based storage**: bare filename URLs (e.g. `https://host/xxx.webp`) no longer map to flat `images/xxx.webp`; SQLite index resolves the full `images/YYYY/MM/xxx.webp` key so thumbnails and short links work again
---
## [1.2.2] — 2026-08-30
> **Restart the service** after upgrading so middleware and API updates take effect.
### Dual-domain settings & Host isolation
#### Fixes
| Issue | Description |
| ----- | ----------- |
| Site URL cleared by mistake | Saving Settings could write an empty `site_base_url` when disabling dual-domain or editing only the image URL |
| Config vs effective URL mixed | `GET /api/settings` used to blend DB values with `request.origin`, confusing the Settings UI |
| Third-host bypass | Unlisted hosts (`pages.dev`, bare IP, old image domains) were not blocked by middleware |
#### Improvements
**Settings API (`GET /api/settings`)**
| Field | Meaning |
| ----- | ------- |
| `siteBaseUrl` / `imageBaseUrl` | **Configured** values (DB → env), no request fallback |
| `effectiveSiteBaseUrl` / `effectiveImageBaseUrl` | **Link generation**, falls back to request origin when unset |
| `runtime.currentOrigin` | Detected access URL (display only, not saved) |
| `runtime.hostRole` | `site` / `image` / `unknown` / `single` |
**Save API (`PATCH /api/settings`)**
- New body field `domainSeparation` (`true` / `false`)
- `domainSeparation: true` requires both URLs with different hostnames
- `domainSeparation: false` allows clearing the site URL
- Without `domainSeparation`, cannot clear `siteBaseUrl` while dual-domain is active
**Settings / setup UI**
- Form uses configured values; “Active” line shows `effective*`
- Shows detected access URL; **no longer** auto-fills `window.location.origin`
- “Use detected URL” button (opt-in)
- Confirmation modal when disabling dual-domain
- Warning when `hostRole === 'unknown'` with dual-domain on
**Host middleware**
- When dual-domain is on, unlisted hosts get **404** at the app layer (all methods)
- `localhost` / `127.0.0.1` exempt in development
- Complements Nginx `default_server` — use both layers in production
#### Docs
- Rewrote [Cloudflare deployment](./cloudflare-deployment.md)
- Updated [Dual-domain separation](./domain-separation.md) for third-host blocking
- Added this changelog page
#### Upgrade notes
- **No** database migration or CLI step
- If the site URL was cleared earlier: re-enter it in **Settings**, or set `SITE_BASE_URL` in env and restart
- Production: match proxy `server_name` to Settings; keep a default server block
---
## [1.2.1] — 2026-08-29
### Added
- Slide puzzle login captcha
- VitePress docs site on GitHub Pages
- `npm run docs:dev` / `docs:build` / `docs:preview`
### Fixed
- Gallery not refreshing after delete on stats page
- Pagination jump with `type="number"` input
- Copy-link format preference not persisting off home route
- Captcha UI alignment
### Improved
- README trimmed; details moved to docs
- Dual-domain docs: unknown Host risk, Cloudflare guide
---
## [1.2.0] — 2026-08-28
### Changed
- All images under `data/images/`; legacy `blog/` / `twikoo/` need migration
### Added
- CLI: `docker exec pichost migrate` / `migrate --apply`
- Startup index sync (disk scan, legacy key normalization, orphan cleanup)
See [v1.2 migration](./migration.md).
---
## [1.1.x] summary
| Version | Highlights |
| ------- | ---------- |
| 1.1.5 | API upload preview fix; file existence check before serve |
| 1.1.4 | Date-based storage paths; site host blocks image URLs |
| 1.1.3 | Dual-domain (`SITE_BASE_URL` / `IMAGE_BASE_URL`); Host middleware |
| 1.1.0 | Multi storage backends (S3 / R2) |
Older entries: [GitHub CHANGELOG](https://github.com/O96u/PicHost/blob/main/CHANGELOG.md).
+236
View File
@@ -0,0 +1,236 @@
# Cloudflare & preferred-edge deployment
In dual-domain mode, PicHost distinguishes **site** vs **image** traffic from the request **Host** (and `X-Forwarded-Host` from a trusted reverse proxy). Cloudflare orange cloud, preferred-edge IPs, Workers, and Pages are all fine — as long as the hostname identity reaching PicHost stays correct.
> **One-line rule:** The network path may change; the hostname identity must not — `admin → admin`, `img → img`, never `img → admin`.
See [Dual-domain separation](./domain-separation.md) for middleware behavior and [Reverse proxy](./reverse-proxy.md) for general proxy requirements.
---
## Quick checklist
| # | Check | Expected |
| - | ----- | -------- |
| 1 | Browser hostname | `admin.*` or `img.*`; do not mix IP / `pages.dev` |
| 2 | Pages / Worker in the middle | Image host must **not** `fetch(admin…)` |
| 3 | Reverse-proxy upstream | Both hostnames → `http://127.0.0.1:6892` |
| 4 | Nginx `proxy_set_header Host` | `$host` (preserve client hostname) |
| 5 | PicHost settings | `SITE_BASE_URL` / `IMAGE_BASE_URL` match `server_name` |
| 6 | Port `6892` | Reachable only from localhost or internal proxy |
---
## Recommended layout
Both hostnames go through Cloudflare (proxied) and **independently** reverse-proxy to one PicHost instance:
```mermaid
flowchart TB
internet[Internet]
cf[Cloudflare proxied]
admin[admin.example.com]
img[img.example.com]
panel[1Panel / Nginx]
app[PicHost :6892]
internet --> cf
cf --> admin
cf --> img
admin --> panel
img --> panel
panel --> app
```
```env
SITE_BASE_URL=https://admin.example.com
IMAGE_BASE_URL=https://img.example.com
```
```text
admin.example.com → http://127.0.0.1:6892
img.example.com → http://127.0.0.1:6892
```
You do **not** need separate ports for “frontend / backend / images” — one PicHost instance on port `6892` is enough.
### Site hostname ≠ frontend domain
| Hostname | Serves |
| -------- | ------ |
| `admin.example.com` | Admin UI, login, settings, gallery, API, upload |
| `img.example.com` | Image delivery, hotlinks, CDN |
Use **site / image hostname**, not “frontend / backend”. PicHost does **not** require `frontend :3000 + backend :6892` in production.
---
## Orange cloud & preferred edge
**DNS Proxied (orange cloud)** is normal and recommended:
```text
admin.example.com, img.example.com
A/CNAME → origin → Proxied
```
Opening `admin.example.com` should yield `Host: admin.example.com` at PicHost; `img.example.com` should yield `Host: img.example.com`.
**Preferred-edge** setups (alternate IPs, entry hostnames) are also fine. Preferred routing may change the path to Cloudflare’s edge, but must **not** rewrite the image hostname’s origin identity to the site hostname:
```text
admin → CF → admin.example.com → origin → PicHost
img → CF → img.example.com → origin → PicHost
```
---
## 6. Typical bad topologies
These patterns break Host isolation even when the browser still shows the image hostname:
### ❌ Bad 1: Image host fetches site host
```mermaid
flowchart LR
user[User on img.example.com]
worker[Pages / Worker]
admin[fetch admin.example.com]
app[PicHost]
user --> worker --> admin --> app
```
The last hop has `Host: admin.example.com`, so PicHost treats it as site traffic — `https://img.example.com/` may show the admin UI. This is **Host rewrite**, not a cache bug.
### ❌ Bad 2: Preferred proxy upstreams to site host
```text
img.example.com → preferred hostname → admin.example.com → origin
```
Even for routing only, using the site hostname as upstream breaks image isolation.
### ❌ Bad 3: Public exposure of port 6892
```text
any host / IP:6892 → PicHost
```
Users can bypass Cloudflare and Nginx `server_name` rules. Port `6892` should be reachable only from `127.0.0.1` or an internal reverse proxy.
### ✅ Correct pattern
```text
admin → admin → PicHost
img → img → PicHost
```
Do **not** use Pages / Workers as a **full-site reverse proxy** for PicHost (extra `pages.dev` / `workers.dev` entry points). PicHost needs `node-server`, SQLite, `sharp`, and local `data/` — it **cannot** run as a Node app on Pages/Workers. Keep Docker/VPS for the app; use orange-cloud DNS and optional R2 on CF.
---
## Workers / Pages guidance
If you only need headers, auth, Referer rules, logging, or cache — and PicHost remains your origin:
| Prefer | Avoid |
| ------ | ----- |
| `img.example.com` → **Worker Route** → existing `img` origin | `img` → Worker → `fetch(admin.example.com)` |
Cloudflare recommends [Routes](https://developers.cloudflare.com/workers/configuration/routing/routes/) when an external origin already exists, rather than [Custom Domains](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/) used to chain cross-host `fetch()`.
Code like this on the image hostname is a smoking gun:
```js
fetch(`https://admin.example.com${url.pathname}`)
```
---
## Nginx / 1Panel layout
Two `server` blocks, same upstream. Critical line: `proxy_set_header Host $host;`
```nginx
server {
server_name admin.example.com;
location / {
proxy_pass http://127.0.0.1:6892;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 12m;
}
}
server {
server_name img.example.com;
location / {
proxy_pass http://127.0.0.1:6892;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# Reject bare IP and unknown hostnames (strongly recommended)
server {
listen 80 default_server;
listen 443 ssl default_server;
server_name _;
return 444;
}
```
With orange cloud, restrict the origin firewall to **[Cloudflare IP ranges](https://www.cloudflare.com/ips/)** only.
---
## Two-layer Host protection
Use reverse proxy and application layers **together**:
| Layer | Role |
| ----- | ---- |
| **Nginx default server** | Reject bare IP, `pages.dev`, and other undeclared hostnames |
| **PicHost middleware (v1.2.x+)** | When dual-domain is on, unconfigured hosts get 404 at the app (`localhost` / `127.0.0.1` exempt in development) |
Even with app-layer blocking, keep a default server at the proxy to reduce junk traffic to PicHost.
---
## X-Forwarded-Host
PicHost may consult `X-Forwarded-Host` behind a reverse proxy, but that header is **forgeable** by clients. Therefore:
- Do not expose port `6892` publicly
- Only trusted proxies should reach the app
- Prefer keeping `Host` correct from the first hop
---
## Troubleshooting: admin UI on image hostname?
**Inspect the proxy chain first — do not purge CF cache first.**
Cache issues usually mean stale JS/CSS/images or occasional 404s. If `/`, `/login`, and `/settings` work **reliably** on the image host, the Host was almost certainly rewritten.
```text
① Browser hostname?
② Pages / Worker / preferred proxy in the middle?
③ What URL does the proxy fetch?
④ Does it fetch admin.example.com?
⑤ Which Host does 1Panel / PicHost see?
```
---
## Related
- [Dual-domain separation](./domain-separation.md)
- [Reverse proxy](./reverse-proxy.md)
- [Environment variables](./configuration.md)
- [FAQ](./faq.md)
+21 -5
View File
@@ -1,6 +1,6 @@
# Environment variables # 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 ## Priority overview
@@ -9,10 +9,11 @@ Configure PicHost via environment variables (Docker / `.env`) or the in-app **Se
| API upload token | Env → SQLite | **Yes** (cannot regenerate in UI) | | API upload token | Env → SQLite | **Yes** (cannot regenerate in UI) |
| WebP quality | SQLite → env → default 80 | No | | WebP quality | SQLite → env → default 80 | No |
| Referer whitelist | SQLite → env | No | | Referer whitelist | SQLite → env | No |
| Site / image base URL | SQLite → env → request origin | No | | Site / image base URL | SQLite → env (configured in API); links use `effective*` or request origin | No |
| Hide `images/` prefix | SQLite → env → default false | No | | Short image links | SQLite → env → default false | No |
| Date-based paths | SQLite → env → default true | No | | Date-based paths | SQLite → env → default true | No |
| Global auto-delete days | SQLite → env → default 0 | No | | Global auto-delete days | SQLite → env → default 0 | No |
| Login verification | SQLite (Settings → Access control) | No |
## Variables ## Variables
@@ -33,11 +34,13 @@ Comma-separated Referer whitelist. Own hostnames are allowed automatically. Opti
- **Site URL**: admin UI, API, Twikoo upload - **Site URL**: admin UI, API, Twikoo upload
- **Image URL**: copied links and public image URLs - **Image URL**: copied links and public image URLs
Single-domain: set `IMAGE_BASE_URL` only or leave empty (request origin). Dual-domain: hostnames must differ — see [Dual-domain separation](./domain-separation.md). Values must match proxy `server_name`; do not use `localhost`, IP, or unlisted hostnames for production admin access. Single-domain: set `IMAGE_BASE_URL` only or leave empty (request origin). Dual-domain: hostnames must differ — see [Dual-domain separation](./domain-separation.md) and [Cloudflare deployment](./cloudflare-deployment.md). Values must match proxy `server_name`; do not use `localhost`, IP, or unlisted hostnames for production admin access.
In **Settings**, enable dual-domain explicitly and fill both URLs; disabling clears the site URL (with confirmation). Configured values vs effective link URLs are separate in the API — see [Changelog](./changelog.md#1-2-2-2026-08-30).
### `HIDE_FOLDER_IN_URL` ### `HIDE_FOLDER_IN_URL`
`true` hides the `images/` prefix in public URLs. `true`: short links (domain + filename only), e.g. `img.example.com/a8K3xP.webp`. `false`: keep date or custom folders, e.g. `img.example.com/2026/08/a8K3xP.webp`. Public URLs never expose the internal `images/` prefix; legacy `/images/...` paths still work.
### `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` ### `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT`
@@ -62,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. 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) ### 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). Admins usually add backends in **Storage** UI; env vars such as `STORAGE_BACKEND=s3` and `S3_*` are also supported. See [Storage](./storage.md).
@@ -97,5 +112,6 @@ Restart the container after changing env vars.
| Date-based paths | `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` | | Date-based paths | `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` |
| WebP quality | `WEBP_QUALITY` | | WebP quality | `WEBP_QUALITY` |
| Auto-delete | `AUTO_DELETE_DAYS` | | 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. Template: [`.env.example`](https://github.com/O96u/PicHost/blob/main/.env.example) in the repo root.
+28 -9
View File
@@ -16,6 +16,8 @@ Set during `/setup` or in **Settings**:
- **Site URL**: `https://admin.example.com` - **Site URL**: `https://admin.example.com`
- **Image URL**: `https://pic.example.com` - **Image URL**: `https://pic.example.com`
Setup and Settings **do not** auto-fill the site URL from `window.location.origin`; use manual input or “Use detected URL”. Disabling dual-domain requires confirmation and clears the site URL. Saves include `domainSeparation: true/false`. See [Changelog](./changelog.md#1-2-2-2026-08-30).
## Nginx example ## Nginx example
```nginx ```nginx
@@ -53,36 +55,53 @@ server {
## Security notes ## Security notes
### Middleware only splits the two configured hostnames ### Middleware isolation and third hosts
PicHost uses the request **Host** (and `X-Forwarded-Host` when proxied) to decide site vs image domain: PicHost uses the request **Host** (and `X-Forwarded-Host` when proxied) to decide site vs image domain:
- **Image host**: non-image paths (e.g. `/`, `/settings`) → 404 - **Image host**: non-image paths (e.g. `/`, `/settings`) → 404
- **Site host**: image URL paths (e.g. `/images/...`) → 404 - **Site host**: image URL paths (e.g. `/images/...`) → 404
- **Unconfigured third hosts** (e.g. `*.pages.dev`, bare IP, old image domains): **from v1.2.x the app returns 404 for all methods** (`localhost` / `127.0.0.1` are exempt in development for `npm run dev`)
If the Host is **neither** the configured site nor image hostname (e.g. `localhost`, the server **public IP**, Cloudflare **Pages** `*.pages.dev`, **Workers** `*.workers.dev`, or any other unlisted name), **the app does not block the request today** — admin and API may still be reachable. This is not about hyphenated or long domain names; it is an extra entry point outside your dual-domain pair. This is independent of hyphenated or long domain names. Older versions did not block third hosts; rely on a reverse-proxy default server as a complement in production.
**Production recommendations:** **Production recommendations:**
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) 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 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 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. Do **not** put Cloudflare Pages / Workers in front of PicHost as a **full-site reverse proxy** (extra `pages.dev` / `workers.dev` entry points worsen this issue) 4. Sign in only on the **site hostname** from Settings; do not mix `localhost`, IP, or unlisted domains
5. 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 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) ### Cloudflare orange cloud (incl. preferred edge IPs)
**Recommended:** both `admin.example.com` and `pic.example.com` **DNS Proxied** → origin Nginx / 1Panel → port `6892`, SSL **Full (strict)** (origin cert or Cloudflare Origin Certificate). Full guide: [Cloudflare deployment](./cloudflare-deployment.md).
**Recommended:** both `admin.example.com` and `pic.example.com` **DNS Proxied** → origin Nginx / 1Panel → port `6892`, SSL **Full (strict)**.
| Feature | Notes | | Feature | Notes |
| ------- | ----- | | ------- | ----- |
| Orange-cloud CDN | Compatible with dual-domain; preserve `Host` and `X-Forwarded-Proto` on origin | | Orange-cloud CDN | Compatible with dual-domain; preserve `Host` and `X-Forwarded-Proto` on origin |
| DNS “preferred IP” setups | Only changes which CF edge IP clients hit; Host stays your real domain | | DNS “preferred IP” setups | Only changes which CF edge IP clients hit; origin identity must stay **admin → admin**, **img → img** |
| R2 storage | Add an R2 backend under **Storage**; independent of orange cloud | | R2 storage | Add an R2 backend under **Storage**; independent of orange cloud |
| `cloudflare` Git branch | R2-focused deployment line; still Docker, **not** Workers hosting | | `cloudflare` Git branch | R2-focused deployment line; still Docker, **not** Workers hosting |
**Do not confuse** “Create Worker” in the CF dashboard (Git + `wrangler deploy`) with deploying PicHost — the repo uses `nitro.preset: 'node-server'` and is not Workers-ready. **Do not confuse** “Create Worker” in the CF dashboard (Git + `wrangler deploy`) with deploying PicHost — the repo uses `nitro.preset: 'node-server'` and is not Workers-ready.
**Do not** chain the image hostname to `fetch(admin…)` via Pages/Workers — that rewrites Host and breaks isolation ([bad topologies](./cloudflare-deployment.md#6-typical-bad-topologies)).
See [Reverse proxy](./reverse-proxy.md#cloudflare-orange-cloud) for origin hardening. See [Reverse proxy](./reverse-proxy.md#cloudflare-orange-cloud) for origin hardening.
## FN NAS · Lucky reverse proxy ## FN NAS · Lucky reverse proxy
@@ -152,7 +171,7 @@ Always open admin on the **site hostname**, not `localhost` (cookies and Host mu
| `http://admin.pichost.test:3000/images/...` or `/2026/08/xxx.webp` | **404** (use image host) | | `http://admin.pichost.test:3000/images/...` or `/2026/08/xxx.webp` | **404** (use image host) |
| `http://pic.pichost.test:3000/` | **404** (image host has no admin) | | `http://pic.pichost.test:3000/` | **404** (image host has no admin) |
| `http://pic.pichost.test:3000/images/...` | Image served | | `http://pic.pichost.test:3000/images/...` | Image served |
| `http://localhost:3000/` or `http://127.0.0.1:3000/` | **Admin still loads** (third Host — isolation skipped; OK for dev only; block at proxy in production) | | `http://localhost:3000/` or `http://127.0.0.1:3000/` | **Admin still loads** (development exception; block unconfigured hosts at proxy in production) |
After upload, copied links should use `pic.pichost.test`; gallery thumbnails should load. After upload, copied links should use `pic.pichost.test`; gallery thumbnails should load.
+34 -3
View File
@@ -19,13 +19,35 @@ 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. 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? ## Why can admin load on pages.dev / workers.dev / IP with dual-domain?
Dual-domain isolation only splits paths on the **configured site and image hostnames**. Other Host values (`localhost`, public IP, Cloudflare **Pages** `*.pages.dev`, **Workers** `*.workers.dev`, etc.) are **not blocked today**, so admin may appear on unexpected URLs. **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).
Common cause: **full-site reverse proxy** via Pages/Workers on top of orange-cloud DNS, or an origin that accepts any Host / bare IP. If admin still loads:
Fix: use only the two configured domains; add a default `server_name` block; with orange cloud, allow only CF IPs on the origin. See [Security notes](./domain-separation.md#security-notes). 1. **Dual-domain not active** (image URL set but site URL empty) — neither path split nor third-host blocking applies
2. **Proxy rewrote Host to site hostname** — e.g. Pages/Worker `fetch(admin…)` on the image hostname
3. **Port `6892` exposed publicly** — bypasses Cloudflare and Nginx `server_name`
Fix: configure both URLs in Settings; add a default server block; with orange cloud, allow only CF IPs on origin; do not full-proxy through Pages/Workers. See [Dual-domain separation](./domain-separation.md#middleware-isolation-and-third-hosts), [Cloudflare deployment](./cloudflare-deployment.md), and [Changelog](./changelog.md#1-2-2-2026-08-30).
## Can I deploy PicHost on Cloudflare Workers / Pages? ## Can I deploy PicHost on Cloudflare Workers / Pages?
@@ -62,3 +84,12 @@ Use `data/mapping.json` from `migrate` preview. Keys are **storage paths**, not
## Docs vs README? ## Docs vs README?
This **VitePress site** is the full guide; README is a short overview. Online: <https://o96u.github.io/PicHost/> This **VitePress site** is the full guide; README is a short overview. Online: <https://o96u.github.io/PicHost/>
## What should the GitHub repo About say?
For **main**:
- **Description**: `Lightweight self-hosted image hosting — Docker, multi-user, gallery & API, local disk or S3-compatible storage.`
- **Website**: `https://o96u.github.io/PicHost/` (docs, not a live demo)
Do not claim the app runs on Cloudflare Pages/Workers. The **cloudflare** branch demo is [pic.roven.cc](https://pic.roven.cc).
+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`). 1. Open your instance URL (Docker default `http://<host>:6892`).
2. Complete `/setup` with admin username and password. 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). 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 ## 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) ![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 ## 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>` 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 ## 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. If `data/` has legacy top-level folders next to `images` (e.g. `blog/`, `twikoo/`), read the [v1.2 migration guide](./migration.md) first.
+8 -11
View File
@@ -6,23 +6,20 @@ Welcome to the PicHost user guide. This site is the single source of truth; the
1. [Quick start](./getting-started.md) — Docker and first-time setup 1. [Quick start](./getting-started.md) — Docker and first-time setup
2. [Environment variables](./configuration.md) — Production config vs in-app settings 2. [Environment variables](./configuration.md) — Production config vs in-app settings
3. [Storage](./storage.md) — Backends and URL modes 3. [Changelog](./changelog.md) — Version history and upgrade notes
4. [API](./api.md) — REST endpoints and tokens 4. [Storage](./storage.md) — Backends and URL modes
5. [API](./api.md) — REST endpoints and tokens
## Screenshots ## 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 | | API | Gallery |
| :--------------: | :---: | | :-: | :-----: |
| ![Setup](/screenshots/setup.png) | ![Login](/screenshots/login.png) | | ![API](/screenshots/api.png) | ![Gallery](/screenshots/gallery.png) |
| API | Stats & gallery |
| :-: | :-------------: |
| ![API](/screenshots/api.png) | ![Stats & gallery](/screenshots/stats.png) |
| Storage | Settings | | Storage | Settings |
| :-----: | :------: | | :-----: | :-------: |
| ![Storage](/screenshots/storage.png) | ![Settings](/screenshots/settings-en.png) | | ![Storage](/screenshots/storage.png) | ![Settings](/screenshots/settings-en.png) |
| Activity log | | Activity log |
+3 -1
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 run typecheck` | Type check |
| `npm test` | Unit tests | | `npm test` | Unit tests |
| `npm run reset-password` | Reset password (optional username) | | `npm run reset-password` | Reset password (optional username) |
| `npm run slider` | Reset login verification to local slider |
| `npm run clear-domains` | Clear site/image URL settings from DB (recover from dual-domain lockout) |
| `npm run migrate` | Preview legacy dir migration (`-- --apply` to run) | | `npm run migrate` | Preview legacy dir migration (`-- --apply` to run) |
## Dev-only variables ## Dev-only variables
@@ -51,4 +53,4 @@ npm run docs:build
npm run docs:preview npm run docs:preview
``` ```
Sources live in `docs-site/`; screenshot sources are in `docs/screenshots/` (including `login.png`), copied to `docs-site/public/screenshots/` before build. Sources live in `docs-site/`; screenshot sources are in `docs/screenshots/` (including `login.png`), copied to `docs-site/public/screenshots/` before build. Live docs: <https://o96u.github.io/PicHost/>
+6 -4
View File
@@ -41,28 +41,30 @@ See [Dual-domain separation](./domain-separation.md).
## Cloudflare orange cloud ## Cloudflare orange cloud
Run PicHost on **your server / Docker** (port `6892`). On Cloudflare: See [Cloudflare deployment](./cloudflare-deployment.md).
| Practice | Notes | | Practice | Notes |
| -------- | ----- | | -------- | ----- |
| **Proxied DNS** | Both admin and image hostnames → origin proxy to `6892`, SSL **Full (strict)** | | **Proxied DNS** | Both admin and image hostnames → origin proxy to `6892`, SSL **Full (strict)** |
| Preferred edge IPs | Compatible; Host remains your real domain | | Preferred edge IPs | Compatible; keep **admin → admin**, **img → img** on origin |
| **R2** | Object storage backend in **Storage**; not the same as hosting the app on Pages | | **R2** | Object storage backend in **Storage**; not the same as hosting the app on Pages |
| Origin firewall | Allow only [Cloudflare IPs](https://www.cloudflare.com/ips/); do not expose `6892` publicly | | Origin firewall | Allow only [Cloudflare IPs](https://www.cloudflare.com/ips/); do not expose `6892` publicly |
**Avoid:** **Avoid:**
- **Cloudflare Pages** (`*.pages.dev`) or **Workers** (`*.workers.dev`) as a **full-site reverse proxy** to PicHost — extra hostnames can bypass dual-domain isolation ([Security notes](./domain-separation.md#security-notes)) - **Cloudflare Pages** (`*.pages.dev`) or **Workers** (`*.workers.dev`) as a **full-site reverse proxy**, or chaining the image host to `fetch(admin…)` — rewrites Host and bypasses dual-domain isolation ([guide](./cloudflare-deployment.md))
- “Create Worker” from Git on this repo — `node-server` preset is not Workers-ready - “Create Worker” from Git on this repo — `node-server` preset is not Workers-ready
## Origin hardening (dual-domain) ## 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 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 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 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
```caddy ```caddy
+4 -2
View File
@@ -1,6 +1,6 @@
# Storage # 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) ![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). 3. Enter connection details (bucket, endpoint, keys).
4. **Set as default** so new uploads use it. 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 ### Cloudflare R2
| Field | Value | | Field | Value |
@@ -52,7 +54,7 @@ Copied links use **IMAGE_BASE_URL**. “Hide folder prefix” may shorten URLs;
## Usage & gallery filter ## Usage & gallery filter
- Per-backend usage on the Storage page - Per-backend usage on the Storage page
- Gallery filter by backend (admin) - Gallery filters by **storage backend** and **upload source**; grid/list view toggle
## Backup ## Backup
+7 -5
View File
@@ -12,12 +12,13 @@ PicHost uses role-based access control (RBAC): **admin** and **user**. Enforceme
| Storage management (`/storage`) | ✓ | — | | Storage management (`/storage`) | ✓ | — |
| System settings (`/settings`) | ✓ | — | | System settings (`/settings`) | ✓ | — |
| Allow registration | ✓ | — | | Allow registration | ✓ | — |
| Login verification (slider / Turnstile / Cap) | ✓ | — |
| Global API token | ✓ | — | | Global API token | ✓ | — |
| Personal API token | ✓ | ✓ | | Personal API token | ✓ | ✓ |
| Stats (incl. user count) | ✓ | partial | | Gallery stats overview (incl. user count) | ✓ | partial |
| Activity log | ✓ | — | | 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 ## 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 - By default only admins create users; **allow registration** is an admin setting
- Passwords hashed with scrypt - 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 - Login rate limiting
## Upload preferences & auto-delete ## 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 - **Auto-delete**: global (admin) and per-user policies; affects **new uploads after enable** only
## API tokens ## API tokens
+1 -1
View File
@@ -1,6 +1,6 @@
# API # API
PicHost 提供 REST 接口与 Twikoo 兼容端点。部署后登录 **API** 页可查看当前 Token 与可复制 cURL 示例。 PicHost 提供 REST 接口与 Twikoo 兼容端点。登录后打开顶栏 **API** 页:左侧为接口目录与 Token 管理,中间为参数说明与 cURL 示例,右侧可 **在线调试** 发送请求。
## 鉴权 ## 鉴权
+182
View File
@@ -0,0 +1,182 @@
# 更新日志
PicHost 版本历史与重要变更说明。完整记录亦见仓库根目录 [CHANGELOG.md](https://github.com/O96u/PicHost/blob/main/CHANGELOG.md)。
---
## [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
### 新增
- **图库页**:导航「统计」改为「图库」(`/gallery`);点击图片打开详情弹层(大图、尺寸、上传方式、存储路径、链接复制)
- **列表操作**:全选 / 反选;单张删除移至详情弹层
- **上传来源**:图库 API 返回网页 / API 上传方式(来自活动日志)
### 改进
- README 补充技术栈章节
### 移除
- `/stats` 路由(不再保留兼容跳转)
## [1.2.4] — 2026-08-31
### 修复
- **访问控制留空仍拦截外链**:未配置 Referer 白名单时,浏览器直开图片正常,但博客/论坛嵌入会因 Referer 校验返回 403 图裂;现仅在配置了白名单时才启用防盗链
## [1.2.3] — 2026-08-30
### 修复
- **简短图片链接 + 按年/月分组**:纯文件名直链(如 `https://域名/xxx.webp`)不再误当成 `images/xxx.webp`,改为经 SQLite 索引反查 `images/年/月/xxx.webp`,缩略图与短链恢复正常
---
## [1.2.2] — 2026-08-30
> 升级后请**重启服务**使中间件与 API 生效。
### 双域名配置与 Host 隔离
#### 修复
| 问题 | 说明 |
| ---- | ---- |
| 管理域被误清空 | 设置页保存时,关闭双域名或仅改图片域可能把 `site_base_url` 写成空字符串,导致 UI 切回单域、管理域「消失」 |
| 配置与生效 URL 混淆 | `GET /api/settings` 的 `siteBaseUrl` / `imageBaseUrl` 曾混入当前请求的 `origin`,设置页「当前生效」与数据库配置难以区分 |
| 第三 Host 绕过隔离 | `pages.dev`、裸 IP、旧图片域等未纳入配置的 Host 此前不被中间件拦截,后台/API 可能仍可访问 |
#### 改进
**设置 API(`GET /api/settings`)**
| 字段 | 含义 |
| ---- | ---- |
| `siteBaseUrl` / `imageBaseUrl` | **配置值**(DB → 环境变量),不含 request fallback |
| `effectiveSiteBaseUrl` / `effectiveImageBaseUrl` | **直链生成用**,未配置时回退到当前请求 origin |
| `runtime.currentOrigin` | 检测到的当前访问地址(仅展示,不写入配置) |
| `runtime.hostRole` | `site` / `image` / `unknown` / `single` |
**保存 API(`PATCH /api/settings`)**
- 新增 body 字段 `domainSeparation`(`true` / `false`),显式表达是否启用双域名
- `domainSeparation: true` 时网站域与图片域**均必填**,且主机名不能相同
- `domainSeparation: false` 时允许清空网站域
- 未传 `domainSeparation` 且双域名已配置时,**禁止**单独把 `siteBaseUrl` 置空
**设置页 / 首次设置**
- 表单回填配置值;「当前生效」显示 `effective*` 字段
- 展示「检测到当前访问」地址,**不再**自动写入 `window.location.origin`
- 提供「填入检测地址」按钮(用户主动点击才填)
- 关闭双域名需确认弹窗
- 双域名开启且 `hostRole === 'unknown'` 时显示反代绕过警告
**Host 中间件**
- 双域名开启时,非 site/image 的 Host **应用层一律 404**(所有 HTTP 方法)
- 开发环境 `localhost` / `127.0.0.1` 例外,便于 `npm run dev`
- 与 Nginx `default_server` **互补**,建议两层都配置
#### 文档
- 重写 [Cloudflare / CF 优选部署](./cloudflare-deployment.md)(精简结构、检查清单、双层防护)
- 更新 [双域名分离](./domain-separation.md) 第三 Host 与应用层拦截说明
- 新增本页 **更新日志**
#### 升级说明
- **无需**数据库迁移或 CLI 操作
- 若管理域此前已被误清空:在 **设置** 中重新填写网站域,或设置环境变量 `SITE_BASE_URL` 后重启
- 生产双域名部署:确认反代 `server_name` 与设置一致;建议保留 Nginx default server
---
## [1.2.1] — 2026-08-29
### 新增
- 登录滑动拼图验证(缺口对齐);验证与登录分两步
- VitePress 文档站(`docs-site/`),部署至 GitHub Pages
- `npm run docs:dev` / `docs:build` / `docs:preview`
### 修复
- 统计页删除图片后图库不刷新
- 分页跳转输入框在 `type="number"` 下无法跳转
- 非首页路由下复制链接格式偏好不持久化
- 滑动验证 UI:滑块垂直居中、缺口尺寸与滑块一致
### 改进
- README 精简,详细说明迁入文档站
- 双域名文档补充未知 Host 风险与 Cloudflare 部署说明
---
## [1.2.0] — 2026-08-28
### 变更
- 图片统一存放在 `data/images/`;遗留 `blog/`、`twikoo/` 等并列目录需迁移
### 新增
- CLI:`docker exec pichost migrate` / `migrate --apply`
- 启动时自动同步图片索引(扫描磁盘、归一化遗留 key、清理孤儿记录)
详见 [v1.2 迁移](./migration.md)。
---
## [1.1.x] 摘要
| 版本 | 要点 |
| ---- | ---- |
| 1.1.5 | API 上传后预览偶发失败修复;出图前校验文件存在 |
| 1.1.4 | 按年/月分组存储;网站域禁止直链出图 |
| 1.1.3 | 双域名分离(`SITE_BASE_URL` / `IMAGE_BASE_URL`);Host 中间件 |
| 1.1.0 | 多存储后端(S3 / R2 等) |
更早版本见 [GitHub CHANGELOG](https://github.com/O96u/PicHost/blob/main/CHANGELOG.md)。
+240
View File
@@ -0,0 +1,240 @@
# Cloudflare / CF 优选部署说明
PicHost 双域名模式下,应用根据请求 **Host**(及可信反代转发的 `X-Forwarded-Host`)区分**管理域**与**图片域**。使用 Cloudflare 橙云、优选线路、Workers 或 Pages 时,只要最终到达 PicHost 的 Host 身份不变,即可正常工作。
> **一句话原则:** 网络线路可以改变,请求的域名身份不能改变 — `admin → admin`,`img → img`,不要 `img → admin`。
基础概念见 [双域名分离](./domain-separation.md);反代通用要求见 [反向代理](./reverse-proxy.md)。
---
## 快速检查清单
部署或排错时,按顺序确认:
| # | 检查项 | 期望 |
| - | ------ | ---- |
| 1 | 浏览器地址栏域名 | `admin.*` 或 `img.*`,不要用 IP / `pages.dev` 混用 |
| 2 | 中间是否经过 Pages / Worker | 图片域**不得** `fetch(admin…)` |
| 3 | 反代 upstream | 两个域名均指向 `http://127.0.0.1:6892` |
| 4 | Nginx `proxy_set_header Host` | `$host`(保持客户端域名) |
| 5 | PicHost 设置 | `SITE_BASE_URL` / `IMAGE_BASE_URL` 与 `server_name` 一致 |
| 6 | 端口 `6892` | 仅本机或内网反代可达,不对公网裸露 |
---
## 推荐拓扑
两个域名经 Cloudflare(橙云)后,**各自独立**反代到同一 PicHost 实例:
```mermaid
flowchart TB
internet[Internet]
cf[Cloudflare 橙云]
admin[admin.example.com]
img[img.example.com]
panel[1Panel / Nginx]
app[PicHost :6892]
internet --> cf
cf --> admin
cf --> img
admin --> panel
img --> panel
panel --> app
```
```env
SITE_BASE_URL=https://admin.example.com
IMAGE_BASE_URL=https://img.example.com
```
```text
admin.example.com → http://127.0.0.1:6892
img.example.com → http://127.0.0.1:6892
```
不需要为「前端 / 后端 / 图片」开不同端口;一个 PicHost 实例、一个内部端口(默认 `6892`)即可。
### 管理域 ≠ 前端域名
| 域名 | 用途 |
| ---- | ---- |
| `admin.example.com` | 后台、登录、设置、图库、API、上传 |
| `img.example.com` | 图片直链、外链、CDN 分发 |
更准确的说法是**管理域 / 图片域**,而非「前端 / 后端」。PicHost 生产环境也**不需要** `前端 :3000 + 后端 :6892` 这种拆分。
---
## Cloudflare 橙云与 CF 优选
**橙云(DNS Proxied)** 是正常且推荐的方式:
```text
admin.example.com、img.example.com
A / CNAME → 源站 → Proxied
```
用户访问 `admin.example.com` 时,PicHost 应收到 `Host: admin.example.com`;访问 `img.example.com` 时应收到 `Host: img.example.com`。
**CF 优选**(优选 IP、优选域名、边缘入口)同样可用。优选可以改变用户到 Cloudflare 边缘的路径,但**不能**把图片域的回源身份变成管理域。两个域名应保持平行、独立的回源链:
```text
admin → CF → admin.example.com → 源站 → PicHost
img → CF → img.example.com → 源站 → PicHost
```
---
## 六、典型错误拓扑
以下方案会破坏 Host 隔离,即使浏览器地址栏仍显示图片域:
### ❌ 错误 1:图片域 fetch 到管理域
```mermaid
flowchart LR
user[用户 img.example.com]
worker[Pages / Worker]
admin[fetch admin.example.com]
app[PicHost]
user --> worker --> admin --> app
```
最后一跳 Host 变成 `admin.example.com`,PicHost 会认为这是管理域 — `https://img.example.com/` 可能看到后台。这是 **Host 被改写**,不是缓存问题。
### ❌ 错误 2:优选回源到管理域
```text
img.example.com → 优选域名 → admin.example.com → 源站
```
即使只为改善线路,只要 upstream 使用管理域,图片域隔离即失效。
### ❌ 错误 3:公网直接暴露 6892
```text
任意域名 / IP:6892 → PicHost
```
用户可绕开 Cloudflare 与 Nginx 的 `server_name` 限制。`6892` 应仅允许 `127.0.0.1` 或内网反代访问。
### ✅ 正确做法
```text
admin → admin → PicHost
img → img → PicHost
```
**不要** Pages / Workers **整站反代** PicHost(会多出 `pages.dev` / `workers.dev` 等第三入口)。PicHost 依赖 `node-server`、SQLite、`sharp` 与本地 `data/`,**不能**作为 Node 应用直接部署到 Pages/Workers;应用本体继续 Docker/VPS 部署,CF 侧用橙云 DNS + 可选 R2 即可。
---
## Workers / Pages 使用建议
若只需改响应头、鉴权、防盗链、日志或缓存,且源站仍是自己的 PicHost:
| 推荐 | 不推荐 |
| ---- | ------ |
| `img.example.com` → **Worker Route** → 原 `img` 源站 | `img` → Worker → `fetch(admin.example.com)` |
Cloudflare 对已有外部源站的场景更推荐 [Routes](https://developers.cloudflare.com/workers/configuration/routing/routes/)(在现有 proxied 域名与源站之前运行),而非用 [Custom Domain](https://developers.cloudflare.com/workers/configuration/routing/custom-domains/) 把 Worker 当作跨域 fetch 的中转。
Worker 中若出现:
```js
fetch(`https://admin.example.com${url.pathname}`)
```
即基本可确定隔离被破坏。
---
## Nginx / 1Panel 配置
两个 `server` 块,upstream 相同,**关键行**是 `proxy_set_header Host $host;`:
```nginx
server {
server_name admin.example.com;
location / {
proxy_pass http://127.0.0.1:6892;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
client_max_body_size 12m;
}
}
server {
server_name img.example.com;
location / {
proxy_pass http://127.0.0.1:6892;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
# 拒绝裸 IP 与未配置域名(强烈建议)
server {
listen 80 default_server;
listen 443 ssl default_server;
server_name _;
return 444;
}
```
橙云部署时,源站防火墙建议**仅放行 [Cloudflare IP 段](https://www.cloudflare.com/ips/)**,避免绕过 CDN 直连。
---
## 双层 Host 防护
生产环境建议反代层与应用层**互补**,而非二选一:
| 层级 | 作用 |
| ---- | ---- |
| **Nginx default server** | 拒绝裸 IP、`pages.dev` 等未在 `server_name` 中声明的 Host |
| **PicHost 中间件(v1.2.x+)** | 双域名开启时,非 site/image 的 Host 应用层返回 404(开发环境 `localhost` / `127.0.0.1` 例外) |
即使应用层已拦截第三 Host,仍建议在反代配置 default server — 减少无效流量到达 PicHost。
---
## X-Forwarded-Host 说明
PicHost 在反代场景会参考 `X-Forwarded-Host` 识别请求域名,但**不能无条件信任**该 Header(客户端可伪造)。因此:
- 不要让 `6892` 对公网裸露
- 确保只有可信反代能到达应用
- 首选方案仍是让 `Host` 从第一跳起就保持正确
---
## 排查:图片域能看到后台?
**先查反代链,不要先清 CF 缓存。**
缓存问题通常表现为旧 JS/CSS/图片或偶发 404;若图片域能**稳定**访问 `/`、`/login`、`/settings`,几乎都是 Host 被改写。
```text
① 浏览器实际域名?
② 是否经过 Pages / Worker / 优选反代?
③ 代理最终 fetch 的 URL?
④ 是否 fetch 到 admin.example.com?
⑤ 1Panel / PicHost 最终收到的 Host?
```
---
## 相关
- [双域名分离](./domain-separation.md) — 中间件行为与本地测试
- [反向代理](./reverse-proxy.md) — 单域名与源站加固
- [环境变量](./configuration.md) — `SITE_BASE_URL`、`IMAGE_BASE_URL`
- [常见问题](./faq.md) — Pages / Workers 与第三 Host
+21 -7
View File
@@ -1,6 +1,4 @@
# 环境变量 PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配置。管理员在 **设置与偏好**(`/settings`)左侧切换 **基础设置**、**域名与路径**、**访问控制**、**操作日志**;多数项 **SQLite 优先**;部分项环境变量可覆盖或锁定后台编辑。
PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配置。多数项 **SQLite 优先**;部分项环境变量可覆盖或锁定后台编辑。
## 优先级总览 ## 优先级总览
@@ -9,10 +7,11 @@ PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配
| API 上传 Token | 环境变量 → SQLite | **是**(设了则后台无法重新生成) | | API 上传 Token | 环境变量 → SQLite | **是**(设了则后台无法重新生成) |
| WebP 质量 | SQLite → 环境变量 → 默认 80 | 否(未在 DB 存时读 env) | | WebP 质量 | SQLite → 环境变量 → 默认 80 | 否(未在 DB 存时读 env) |
| 防盗链白名单 | SQLite → 环境变量 | 否 | | 防盗链白名单 | SQLite → 环境变量 | 否 |
| 网站 / 图片域名 | SQLite → 环境变量 → 当前请求 | 否 | | 网站 / 图片域名 | SQLite → 环境变量(设置 API 配置值);直链生成另用 `effective*` 或请求 origin | 否 |
| 隐藏 `images/` 前缀 | SQLite → 环境变量 → 默认 false | 否 | | 简短图片链接 | SQLite → 环境变量 → 默认 false | 否 |
| 按年/月分组存储 | SQLite → 环境变量 → 默认 true | 否 | | 按年/月分组存储 | SQLite → 环境变量 → 默认 true | 否 |
| 全局自动删除天数 | SQLite → 环境变量 → 默认 0 | 否 | | 全局自动删除天数 | SQLite → 环境变量 → 默认 0 | 否 |
| 登录人机验证 | SQLite(设置 → 访问控制) | 否 |
## 变量说明 ## 变量说明
@@ -33,11 +32,13 @@ PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配
- **网站域名**:管理后台、API、Twikoo 上传入口 - **网站域名**:管理后台、API、Twikoo 上传入口
- **图片域名**:复制链接与直链使用的公网地址 - **图片域名**:复制链接与直链使用的公网地址
双域名分离需两者主机名不同,详见 [双域名分离](./domain-separation.md)。填写后须与反代 `server_name` 一致;**勿**通过 `localhost`、IP 或未配置的域名访问生产后台。 双域名分离需两者主机名不同,详见 [双域名分离](./domain-separation.md) 与 [Cloudflare / CF 优选部署](./cloudflare-deployment.md)。填写后须与反代 `server_name` 一致;**勿**通过 `localhost`、IP 或未配置的域名访问生产后台。
在后台 **设置** 中保存时须显式勾选「启用后台与图片域名分离」,并同时填写两个域名;关闭双域名会清除网站域配置(需确认)。设置 API 返回的配置值与「当前生效」直链地址已分离,详见 [更新日志](./changelog.md#1-2-2-2026-08-30)。
### `HIDE_FOLDER_IN_URL` ### `HIDE_FOLDER_IN_URL`
`true` 时直链隐藏 `images/` 前缀(如 `images/2026/08/a.webp` → `/2026/08/a.webp` 或仅文件名,取决于路径模式)。 `true` 时使用简短图片链接(仅域名 + 文件名,如 `img.example.com/a8K3xP.webp`);`false` 时保留日期或自定义目录(如 `img.example.com/2026/08/a8K3xP.webp`)。对外 URL **不会** 暴露内部 `images/` 前缀;旧版含 `images/` 的直链仍兼容。
### `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` ### `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT`
@@ -62,6 +63,18 @@ PicHost 支持通过环境变量(Docker / `.env`)与后台 **设置** 页配
仅本地开发:`true` 绕过登录验证。生产环境勿用。 仅本地开发:`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)。 管理员通常在 **存储** 页添加后端;也可用环境变量引导(如 `STORAGE_BACKEND=s3` 与 `S3_*`)。详见 [存储](./storage.md)。
@@ -97,5 +110,6 @@ services:
| 按年/月分组 | `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` | | 按年/月分组 | `STORAGE_USE_DATE_PATH` / `STORAGE_LAYOUT` |
| WebP 质量 | `WEBP_QUALITY` | | WebP 质量 | `WEBP_QUALITY` |
| 自动删除 | `AUTO_DELETE_DAYS` | | 自动删除 | `AUTO_DELETE_DAYS` |
| 登录验证 | (仅后台 **设置 → 访问控制**) |
完整模板见仓库根目录 [`.env.example`](https://github.com/O96u/PicHost/blob/main/.env.example)。 完整模板见仓库根目录 [`.env.example`](https://github.com/O96u/PicHost/blob/main/.env.example)。
+29 -10
View File
@@ -19,6 +19,8 @@
- **网站域名**:`https://admin.example.com` - **网站域名**:`https://admin.example.com`
- **图片域名**:`https://pic.example.com` - **图片域名**:`https://pic.example.com`
首次设置与系统设置**不会**自动把当前浏览器地址写入网站域;可手动填写或点击「填入检测地址」。关闭双域名需确认,且会清除网站域配置。保存时 API 会收到 `domainSeparation: true/false` 字段。详见 [更新日志](./changelog.md#1-2-2-2026-08-30)。
## Nginx 示例 ## Nginx 示例
```nginx ```nginx
@@ -56,36 +58,53 @@ server {
## 安全与注意事项 ## 安全与注意事项
### 中间件只隔离「已配置的两个域名」 ### 中间件隔离与第三 Host
PicHost 根据请求 **Host**(反代会转发为 `X-Forwarded-Host`,应用会一并识别)判断当前是网站域还是图片域: PicHost 根据请求 **Host**(反代会转发为 `X-Forwarded-Host`,应用会一并识别)判断当前是网站域还是图片域:
- **图片域**:非图片路径(如 `/`、`/settings`)→ 404 - **图片域**:非图片路径(如 `/`、`/settings`)→ 404
- **网站域**:图片直链路径(如 `/images/...`)→ 404 - **网站域**:图片直链路径(如 `/images/...`)→ 404
- **未配置的第三 Host**(如 `*.pages.dev`、裸 IP、旧图片域):**v1.2.x 起应用层一律 404**(开发环境 `localhost` / `127.0.0.1` 例外,便于 `npm run dev`)
若 Host **既不是网站域也不是图片域**(例如 `localhost`、服务器 **公网 IP**、Cloudflare **Pages** 的 `*.pages.dev`、**Workers** 的 `*.workers.dev`、或其它未在设置里填写的域名),**当前版本不会拦截**,后台与 API 仍可能被访问。这与域名是否带 `-`、长短无关,而是多了一条未纳入双域名配置的入口。 这与域名是否带 `-`、长短无关;此前版本对第三 Host 不拦截,需依赖反代 default server 封堵。
**生产环境建议:** **生产环境建议:**
1. 反代层仅为网站域、图片域配置 `server_name`,并增加 **default server** 拒绝其它 Host 与裸 IP(见上方 Nginx 示例) 1. 反代层仅为网站域、图片域配置 `server_name`,并增加 **default server** 拒绝其它 Host 与裸 IP(见上方 Nginx 示例,与应用层拦截互补)
2. 使用 Cloudflare **橙云** 时,源站防火墙 **仅放行 [Cloudflare IP 段](https://www.cloudflare.com/ips/)**,避免绕过 CDN 直连源站 2. 使用 Cloudflare **橙云** 时,源站防火墙 **仅放行 [Cloudflare IP 段](https://www.cloudflare.com/ips/)**,避免绕过 CDN 直连源站
3. **仅使用** 设置中的网站域名登录后台,不要用 `localhost`、IP 或未配置的域名混用 3. **保存前**阅读设置 / 初始化页的风险确认;若通过 IP、内网或未正确传递 Host 的反代保存,可能锁死后台;恢复见下方「已锁死时的恢复」
4. **不要** 用 Cloudflare Pages / Workers 对 PicHost **整站反代**(会多出 `pages.dev` / `workers.dev` 等第三入口,且易出现上述绕过) 4. **仅使用** 设置中的网站域名登录后台,不要用 `localhost`、IP 或未配置的域名混用
5. PicHost **不能** 作为 Node 应用直接部署到 Pages/Workers(依赖 `node-server`、SQLite、`sharp` 与本地 `data/`);应用请继续 Docker/VPS 部署,CF 侧用橙云 DNS + 可选 R2 存储即可 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 优选) ### Cloudflare 橙云(含 DNS 优选)
**推荐架构:** `admin.example.com` 与 `pic.example.com` 均 **DNS Proxied(橙云)** → 源站 Nginx / 1Panel 反代 `6892`,SSL 模式 **Full (strict)**(源站可用 Cloudflare Origin Certificate)。 完整说明见专章:[Cloudflare / CF 优选部署](./cloudflare-deployment.md)。
**推荐:** `admin.example.com` 与 `pic.example.com` 均 **DNS Proxied(橙云)** → 源站 Nginx / 1Panel 反代 `6892`,SSL 模式 **Full (strict)**。
| 能力 | 说明 | | 能力 | 说明 |
| ---- | ---- | | ---- | ---- |
| 橙云 CDN | 与 PicHost 双域名兼容;回源须保留 `Host`、`X-Forwarded-Proto` | | 橙云 CDN | 与 PicHost 双域名兼容;回源须保留 `Host`、`X-Forwarded-Proto` |
| DNS 优选 | 仅改变用户连到 CF 边缘的 IP,Host 仍为正式域名,无额外配置 | | DNS 优选 | 仅改变用户连到 CF 边缘的 IP;**admin → admin、img → img** 的回源身份不能变 |
| R2 对象存储 | 在 **存储** 页添加 R2 后端即可,与是否橙云无关 | | R2 对象存储 | 在 **存储** 页添加 R2 后端即可,与是否橙云无关 |
| `cloudflare` Git 分支 | R2 专用部署线,仍是 Docker 运行,**不是** Workers 托管 | | `cloudflare` Git 分支 | R2 专用部署线,仍是 Docker 运行,**不是** Workers 托管 |
**勿混淆:** CF 控制台「创建 Worker」并连接本仓库 **无法** 直接部署 PicHost;`npm run build` + `wrangler deploy` 与当前 `node-server` 预设不兼容。 **勿混淆:** CF 控制台「创建 Worker」并连接本仓库 **无法** 直接部署 PicHost;`npm run build` + `wrangler deploy` 与当前 `node-server` 预设不兼容。
**勿用 Pages/Worker 把图片域 `fetch` 到管理域** — 会破坏 Host 隔离(详见 [Cloudflare 部署说明 · 典型错误拓扑](./cloudflare-deployment.md#六典型错误拓扑))。
反代与源站加固详见 [反向代理](./reverse-proxy.md#cloudflare-橙云)。 反代与源站加固详见 [反向代理](./reverse-proxy.md#cloudflare-橙云)。
## 飞牛 NAS · Lucky 反向代理 ## 飞牛 NAS · Lucky 反向代理
@@ -157,7 +176,7 @@ npm run dev
| `http://admin.pichost.test:3000/images/...` 或 `/2026/08/xxx.webp` | **404**(请用图片域直链) | | `http://admin.pichost.test:3000/images/...` 或 `/2026/08/xxx.webp` | **404**(请用图片域直链) |
| `http://pic.pichost.test:3000/` | **404**(正常,图片域不提供后台) | | `http://pic.pichost.test:3000/` | **404**(正常,图片域不提供后台) |
| `http://pic.pichost.test:3000/images/...` | 能出图 | | `http://pic.pichost.test:3000/images/...` | 能出图 |
| `http://localhost:3000/` 或 `http://127.0.0.1:3000/` | **能打开后台**(第三 Host,隔离不生效;仅开发可接受,生产须用反代封禁) | | `http://localhost:3000/` 或 `http://127.0.0.1:3000/` | **能打开后台**(开发环境例外;生产须用反代封禁未配置 Host) |
上传一张图后,复制链接应指向 `pic.pichost.test` 域名;在后台图库中缩略图也应能正常显示。 上传一张图后,复制链接应指向 `pic.pichost.test` 域名;在后台图库中缩略图也应能正常显示。
@@ -169,4 +188,4 @@ npm run dev
- 单域名部署可不启用分离,仅配置 `IMAGE_BASE_URL` 或使用默认当前访问域名 - 单域名部署可不启用分离,仅配置 `IMAGE_BASE_URL` 或使用默认当前访问域名
- 配置了 Referer 防盗链时,网站域与图片域会自动加入白名单,无需手写两个域名 - 配置了 Referer 防盗链时,网站域与图片域会自动加入白名单,无需手写两个域名
单域名反代要点见 [反向代理](./reverse-proxy.md)。英文版:[Dual-domain separation](/en/guide/domain-separation) 单域名反代要点见 [反向代理](./reverse-proxy.md)。
+34 -3
View File
@@ -20,13 +20,35 @@ docker exec pichost reset-password 用户名
检查 **防盗链白名单**(`ALLOWED_REFERER_HOSTS` 或设置页)。引用图片的站点域名需在白名单中;PicHost 自身域名与双域名场景下的网站域、图片域会自动放行。 检查 **防盗链白名单**(`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 也能进后台? ## 双域名下为什么用 pages.dev / workers.dev / IP 也能进后台?
PicHost 双域名隔离**只对已配置的网站域、图片域做路径分流**;其它 Host(`localhost`、公网 IP、Cloudflare Pages 的 `*.pages.dev`、Workers 的 `*.workers.dev` 等)**当前不会拦截**,因此可能出现「奇怪地址也能开后台」。 **v1.2.2 起:** 双域名开启时,PicHost 中间件会对**未配置的网站域、图片域之外**的 Host 返回 **404**(开发环境 `localhost` / `127.0.0.1` 例外)。详见 [更新日志](./changelog.md#1-2-2-2026-08-30)。
常见原因:在橙云之外又用 **Pages/Workers 整站反代** 到源站,或源站未限制 `server_name` / 允许裸 IP 访问。 若仍能访问,常见原因:
处理:仅用正式两个域名访问;反代加 default server;橙云时源站只放行 CF IP。详见 [双域名分离 · 安全与注意事项](./domain-separation.md#安全与注意事项)。 1. **未启用双域名**(仅配置了图片域、网站域为空)— 隔离与第三 Host 拦截均不生效
2. **反代把 Host 改成管理域** — 例如 Pages/Worker 对图片域 `fetch(admin…)`,PicHost 看到的是管理域
3. **源站裸暴露 `6892`** — 绕过 Cloudflare 与 Nginx `server_name`
处理:在设置中正确配置双域名;反代加 default server;橙云时源站只放行 CF IP;勿用 Pages/Workers 整站反代。详见 [双域名分离](./domain-separation.md#中间件隔离与第三-host)、[Cloudflare 部署](./cloudflare-deployment.md) 与 [更新日志](./changelog.md#1-2-2-2026-08-30)。
## 能把 PicHost 部署到 Cloudflare Workers / Pages 吗? ## 能把 PicHost 部署到 Cloudflare Workers / Pages 吗?
@@ -63,3 +85,12 @@ PicHost 双域名隔离**只对已配置的网站域、图片域做路径分流*
## 文档与仓库 README 哪个为准? ## 文档与仓库 README 哪个为准?
**本 VitePress 文档站** 为完整用户指南;README 保留摘要与快速开始。在线地址:<https://o96u.github.io/PicHost/> **本 VitePress 文档站** 为完整用户指南;README 保留摘要与快速开始。在线地址:<https://o96u.github.io/PicHost/>
## GitHub 仓库 About 怎么写?
**main** 分支建议:
- **Description**:`Lightweight self-hosted image hosting — Docker, multi-user, gallery & API, local disk or S3-compatible storage.`
- **Website**:`https://o96u.github.io/PicHost/`(文档站,非图床演示)
勿写「部署在 Cloudflare Pages/Workers」—— PicHost 应用跑在 Docker/VPS;**cloudflare** 分支在线演示为 [pic.roven.cc](https://pic.roven.cc)。
+25 -3
View File
@@ -35,15 +35,27 @@ docker compose up -d
1. 访问实例 URL(Docker 默认 `http://<主机>:6892`)。 1. 访问实例 URL(Docker 默认 `http://<主机>:6892`)。
2. 在 `/setup` 填写管理员用户名与密码。 2. 在 `/setup` 填写管理员用户名与密码。
3. (可选)配置网站域名、图片域名、防盗链等 — 详见 [环境变量](./configuration.md) 与 [双域名分离](./domain-separation.md)。 3. (可选)配置网站域名、图片域名、防盗链等 — 详见 [环境变量](./configuration.md) 与 [双域名分离](./domain-separation.md)。
4. 登录后可在首页上传图片;管理员可进入 **存储**、**设置**、**API** 页。 4. 登录后可在首页上传图片;顶栏可进入 **图库**、**存储**(管理员)、**设置**、**API**。
## 登录 ## 登录
访问上传、统计、设置等管理页面前需登录。在登录卡片中填写用户名与密码,**拖动滑块对齐缺口**完成验证后点击 **登录**。 访问上传、图库、设置等管理页面前需登录。在登录卡片中填写用户名与密码,完成人机验证后点击 **登录**。
默认使用**本地滑块**(拖动滑块对齐缺口)。管理员可在 **设置 → 访问控制** 切换为 **Cloudflare Turnstile** 或 **Cap**,并填写对应 Site Key / Secret 或 API 端点。
![登录页](/screenshots/login.png) ![登录页](/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 -- 用户名` 本地开发:`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 ## 升级到 v1.2.0
若 `data/` 下存在与 `images` 并列的遗留目录(如 `blog/`、`twikoo/`),升级前请阅读 [v1.2 迁移指南](./migration.md)。 若 `data/` 下存在与 `images` 并列的遗留目录(如 `blog/`、`twikoo/`),升级前请阅读 [v1.2 迁移指南](./migration.md)。
+10 -13
View File
@@ -6,24 +6,21 @@
1. [快速开始](./getting-started.md) — Docker 部署与首次设置 1. [快速开始](./getting-started.md) — Docker 部署与首次设置
2. [环境变量](./configuration.md) — 生产环境配置与后台设置对照 2. [环境变量](./configuration.md) — 生产环境配置与后台设置对照
3. [存储](./storage.md) — 多后端与直链模式 3. [更新日志](./changelog.md) — 版本变更与升级说明
4. [API](./api.md) — REST 接口与 Token 4. [存储](./storage.md) — 多后端与直链模式
5. [API](./api.md) — REST 接口与 Token
## 截图预览 ## 截图预览
**main** 分支暂无公网演示,以下为 v1.2.0 产品界面。 **main** 分支暂无公网演示,以下为当前产品界面(v1.2.5+)。
| 首次设置 | 登录 | | API | 图库 |
| :------: | :--: | | :-: | :-: |
| ![首次设置](/screenshots/setup.png) | ![登录](/screenshots/login.png) | | ![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) |
| 操作日志 | | 操作日志 |
| :------: | | :------: |
+3 -1
View File
@@ -28,6 +28,8 @@ npm run dev
| `npm run typecheck` | 类型检查 | | `npm run typecheck` | 类型检查 |
| `npm test` | 单元测试 | | `npm test` | 单元测试 |
| `npm run reset-password` | 重置密码(可选用户名) | | `npm run reset-password` | 重置密码(可选用户名) |
| `npm run slider` | 将登录验证重置为本地滑块 |
| `npm run clear-domains` | 清除数据库中的网站域 / 图片域配置(双域名锁死时恢复) |
| `npm run migrate` | 预览遗留目录迁移(加 `-- --apply` 执行) | | `npm run migrate` | 预览遗留目录迁移(加 `-- --apply` 执行) |
## 开发专用环境变量 ## 开发专用环境变量
@@ -51,4 +53,4 @@ npm run docs:build # 构建静态站点
npm run docs:preview # 预览构建结果 npm run docs:preview # 预览构建结果
``` ```
文档源码在 `docs-site/`;截图源文件在 `docs/screenshots/`(含 `login.png` 登录页),构建前会复制到 `docs-site/public/screenshots/`。 文档源码在 `docs-site/`;截图源文件在 `docs/screenshots/`(含 `login.png` 登录页),构建前会复制到 `docs-site/public/screenshots/`。在线文档:<https://o96u.github.io/PicHost/>
-2
View File
@@ -174,5 +174,3 @@ CLI 只负责**搬文件**;索引对齐、遗留 key、孤儿记录由启动
| `docker exec pichost migrate` | 预览磁盘迁移 | | `docker exec pichost migrate` | 预览磁盘迁移 |
| `docker exec pichost migrate --apply` | 执行磁盘迁移 | | `docker exec pichost migrate --apply` | 执行磁盘迁移 |
| `docker exec pichost reset-password` | 重置密码(与迁移无关) | | `docker exec pichost reset-password` | 重置密码(与迁移无关) |
英文版:[v1.2 migration guide](/en/guide/migration)
+5 -5
View File
@@ -41,18 +41,18 @@ IMAGE_BASE_URL=https://pic.example.com
## Cloudflare 橙云 ## Cloudflare 橙云
PicHost 应用运行在 **自有服务器 / Docker**(端口 `6892`),Cloudflare 侧推荐: 详见专章:[Cloudflare / CF 优选部署](./cloudflare-deployment.md)。
| 做法 | 说明 | | 做法 | 说明 |
| ---- | ---- | | ---- | ---- |
| **DNS 橙云** | `admin` / `pic` 两个子域 Proxied → 源站反代 `6892`,SSL **Full (strict)** | | **DNS 橙云** | `admin` / `img` 两个子域 Proxied → 源站反代 `6892`,SSL **Full (strict)** |
| **DNS 优选** | 与 PicHost 兼容;Host 仍为正式域名 | | **DNS 优选** | 与 PicHost 兼容;须保持 **admin → admin、img → img** 回源 |
| **R2** | 在存储页作对象后端,非 Pages 托管应用 | | **R2** | 在存储页作对象后端,非 Pages 托管应用 |
| **源站防火墙** | 仅放行 [Cloudflare IP](https://www.cloudflare.com/ips/),禁止公网直连 `6892` | | **源站防火墙** | 仅放行 [Cloudflare IP](https://www.cloudflare.com/ips/),禁止公网直连 `6892` |
**不建议:** **不建议:**
- 用 **Cloudflare Pages**(`*.pages.dev`)或 **Workers**(`*.workers.dev`)对 PicHost **整站反代** — 会多出第三 Host,且可能绕过双域名隔离(见 [双域名分离 · 安全与注意事项](./domain-separation.md#安全与注意事项)) - 用 **Cloudflare Pages**(`*.pages.dev`)或 **Workers**(`*.workers.dev`)对 PicHost **整站反代**,或让图片域 **fetch 到管理域** — 会改写 Host、绕过双域名隔离(见 [Cloudflare 部署说明](./cloudflare-deployment.md))
- 在 CF 控制台「从 Git 创建 Worker」部署本仓库 — 当前为 `node-server` 预设,无法直接 `wrangler deploy` - 在 CF 控制台「从 Git 创建 Worker」部署本仓库 — 当前为 `node-server` 预设,无法直接 `wrangler deploy`
## 源站安全(双域名推荐) ## 源站安全(双域名推荐)
@@ -63,7 +63,7 @@ PicHost 应用运行在 **自有服务器 / Docker**(端口 `6892`),Cloudf
2. **禁止公网暴露 6892** — 仅本机或内网反代访问;公网只开 80/443 2. **禁止公网暴露 6892** — 仅本机或内网反代访问;公网只开 80/443
3. **橙云时限制源站来源 IP** — 仅 Cloudflare 回源 IP 段 3. **橙云时限制源站来源 IP** — 仅 Cloudflare 回源 IP 段
双域名场景下 PicHost **不会** 拒绝未配置的 Host;上述措施由运维层补齐。 **v1.2.2 起**,双域名开启时 PicHost 应用层也会对**未配置的网站域、图片域之外**的 Host 全站返回 404(与反代 default server 互补,而非替代)。误配置导致锁死时执行 `docker exec pichost clear-domains` 恢复,见 [常见问题](./faq.md#双域名配置后后台-404-进不去)。
## Caddy 示例 ## 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) ![存储管理](/screenshots/storage.png)
@@ -25,6 +25,8 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
3. 填写连接信息(桶名、Endpoint、Access Key 等)。 3. 填写连接信息(桶名、Endpoint、Access Key 等)。
4. 保存后可 **设默认**,新上传将写入该后端。 4. 保存后可 **设默认**,新上传将写入该后端。
新建对象存储后端的 **存储标识** 按类型自动生成前缀:本地为 `local`;R2 为 `r2-*`;COS 为 `cos-*`;OSS 为 `oss-*`;AWS S3 及自定义 S3 兼容为 `s3-*`(创建后不可修改,图片索引会引用该 ID)。
### Cloudflare R2 要点 ### Cloudflare R2 要点
| 项 | 值 | | 项 | 值 |
@@ -54,7 +56,7 @@ PicHost 支持 **本地磁盘** 与 **S3 兼容对象存储**(Cloudflare R2、
## 用量与筛选 ## 用量与筛选
- 存储页展示各后端用量(本地扫描目录,对象存储查询 API) - 存储页展示各后端用量(本地扫描目录,对象存储查询 API)
- 图库可按存储后端筛选(管理员) - 图库可按 **存储后端**、**上传来源** 筛选,支持网格/列表视图切换
## 备份 ## 备份
+7 -5
View File
@@ -12,12 +12,13 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
| 存储后端管理(`/storage`) | ✓ | — | | 存储后端管理(`/storage`) | ✓ | — |
| 系统设置(`/settings`) | ✓ | — | | 系统设置(`/settings`) | ✓ | — |
| 开放注册开关 | ✓ | — | | 开放注册开关 | ✓ | — |
| 登录人机验证方式(滑块 / Turnstile / Cap) | ✓ | — |
| 全局 API Token 管理 | ✓ | — | | 全局 API Token 管理 | ✓ | — |
| 个人 API Token | ✓ | ✓ | | 个人 API Token | ✓ | ✓ |
| 统计页(含注册用户数) | ✓ | 部分 | | 图库统计概览(含注册用户数) | ✓ | 部分 |
| 操作日志 | ✓ | — | | 操作日志(设置 → 操作日志) | ✓ | — |
普通用户顶栏:**API**、**统计**;用户菜单:**修改密码**、**退出登录**。 普通用户顶栏:**API**、**图库**;用户菜单:**修改密码**、**退出登录**。
## 鉴权场景 ## 鉴权场景
@@ -34,12 +35,13 @@ PicHost 使用基于角色的访问控制(RBAC):**管理员(admin)**
- 默认仅管理员可创建用户;管理员可在设置中 **开放注册** - 默认仅管理员可创建用户;管理员可在设置中 **开放注册**
- 密码使用 scrypt 哈希存储 - 密码使用 scrypt 哈希存储
- Web 登录需先完成滑动拼图验证(拖动滑块对齐缺口) - Web 登录/注册需完成人机验证:默认本地滑块;管理员可在 **设置 → 访问控制** 切换 Turnstile 或 Cap
- 验证配置错误无法登录时:`docker exec pichost slider` 重置为本地滑块
- 登录失败有速率限制 - 登录失败有速率限制
## 上传偏好与自动删除 ## 上传偏好与自动删除
- **上传偏好**(首页卡片翻转):客户端预压缩、自动复制链接等,按用户保存 - **上传偏好**:管理员在 **设置 → 基础设置** 配置客户端预压缩、自动复制链接等;普通用户可在首页上传卡片背面调整个人偏好
- **自动删除**:管理员可设全局策略;用户可设个人策略。启用后仅影响 **之后新上传** 的图片 - **自动删除**:管理员可设全局策略;用户可设个人策略。启用后仅影响 **之后新上传** 的图片
## API Token 说明 ## 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

+238 -6
View File
@@ -23,6 +23,7 @@
}, },
"nav": { "nav": {
"api": "API", "api": "API",
"gallery": "Gallery",
"stats": "Stats", "stats": "Stats",
"logs": "Activity log", "logs": "Activity log",
"settings": "Settings", "settings": "Settings",
@@ -66,6 +67,11 @@
"loginFailed": "Sign-in failed. Check username and password", "loginFailed": "Sign-in failed. Check username and password",
"captchaHint": "Drag the slider to the slot", "captchaHint": "Drag the slider to the slot",
"captchaSuccess": "Verified", "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", "registerFailed": "Registration failed. Check your input",
"setupFailed": "Setup failed. Check your input", "setupFailed": "Setup failed. Check your input",
"migrateFailed": "Migration failed. Check your input", "migrateFailed": "Migration failed. Check your input",
@@ -78,6 +84,11 @@
"invalidPassword": "Password must be at least 8 characters" "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": { "setup": {
"migrateTitle": "Migrate to username/password", "migrateTitle": "Migrate to username/password",
"initTitle": "First run — create admin account", "initTitle": "First run — create admin account",
@@ -148,11 +159,13 @@
"url": "URL", "url": "URL",
"markdown": "Markdown", "markdown": "Markdown",
"html": "HTML", "html": "HTML",
"bbcode": "BBCode",
"copied": "Copied to clipboard", "copied": "Copied to clipboard",
"copiedLabel": "Copied {label}", "copiedLabel": "Copied {label}",
"copiedUrl": "URL copied", "copiedUrl": "URL copied",
"copiedMarkdown": "Markdown copied", "copiedMarkdown": "Markdown copied",
"copiedHtml": "HTML copied", "copiedHtml": "HTML copied",
"copiedBbcode": "BBCode copied",
"copiedFormat": "Copied {format}", "copiedFormat": "Copied {format}",
"failed": "Copy failed", "failed": "Copy failed",
"failedManual": "Copy failed — select the link manually", "failedManual": "Copy failed — select the link manually",
@@ -180,12 +193,55 @@
}, },
"settings": { "settings": {
"title": "System 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", "subtitle": "Saved to database; environment variables take precedence",
"featureToggles": "Feature toggles", "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", "allowRegistration": "Open registration",
"allowRegistrationHint": "Allow new users to register (regular users see only their images)", "allowRegistrationHint": "Allow new users to register (regular users see only their images)",
"accessControl": "Access control", "accessControl": "Access control",
"refererHint": "Referer hotlink protection; comma-separated hostnames, empty = no restriction", "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", "refererPlaceholder": "example.com, www.example.com",
"domainSettings": "Domain settings", "domainSettings": "Domain settings",
"domainSeparationActive": "Domain separation enabled: image host serves images only; site host serves admin and API", "domainSeparationActive": "Domain separation enabled: image host serves images only; site host serves admin and API",
@@ -198,20 +254,30 @@
"imageBaseUrlSingleHint": "No trailing slash; leave empty to use the current request host; single-domain setups do not need a site URL", "imageBaseUrlSingleHint": "No trailing slash; leave empty to use the current request host; single-domain setups do not need a site URL",
"imageBaseUrlPlaceholder": "https://pic.example.com", "imageBaseUrlPlaceholder": "https://pic.example.com",
"imageBaseUrlActive": "Active: {url}", "imageBaseUrlActive": "Active: {url}",
"hideFolderInUrl": "Hide folder in image URLs", "runtimeDetected": "Detected current access: {url} (will not be saved automatically)",
"hideFolderInUrlHint": "Links become /file.webp without folder or date paths; legacy full paths still work. Identical filenames under different subpaths may collide on short URLs", "fillDetectedOrigin": "Use detected URL",
"hostRoleUnknown": "Current Host does not match configured domains; reverse-proxy bypass may be possible",
"disableDomainSeparationTitle": "Disable domain separation",
"disableDomainSeparationDesc": "This clears the site URL and keeps only the image URL. Continue?",
"disableDomainSeparationConfirm": "Disable",
"domainSeparationRequired": "Both site and image URLs are required when domain separation is enabled",
"hideFolderInUrl": "Use short image links",
"hideFolderInUrlHint": "When on, links are only domain + filename, e.g. img.example.com/abc.webp. When off, date or custom folders are kept, e.g. img.example.com/2026/08/abc.webp",
"storageUseDatePath": "Group uploads by year/month", "storageUseDatePath": "Group uploads by year/month",
"storageUseDatePathHint": "When enabled, files are stored as images/2026/08/file.webp; when disabled, as images/file.webp. Applies only to new uploads after enabling", "storageUseDatePathHint": "When enabled, files are stored as images/2026/08/file.webp; when disabled, as images/file.webp. Applies only to new uploads after enabling",
"badgeEnv": ".env", "badgeEnv": ".env",
"badgeSaved": "Saved", "badgeSaved": "Saved",
"badgeDefault": "Default", "badgeDefault": "Default",
"badgeUnset": "Not set", "badgeUnset": "Not set",
"badgeOptional": "Optional",
"tokenEnv": "Environment", "tokenEnv": "Environment",
"tokenDb": "Generated in app", "tokenDb": "Generated in app",
"tokenNone": "Not configured", "tokenNone": "Not configured",
"apiTokenLine": "API Token · {source} ·", "apiTokenLine": "Source: {source}",
"viewReleases": "View releases", "viewReleases": "View releases",
"updateAvailable": "Update available: {version}", "updateAvailable": "Update available: {version}",
"upToDate": "You are on the latest version",
"checkUpdateFailed": "Failed to check for updates. Please try again later",
"unsavedChanges": "Unsaved changes", "unsavedChanges": "Unsaved changes",
"manageToken": "Manage token", "manageToken": "Manage token",
"envOverride": "Overridden by environment variable; cannot edit in UI", "envOverride": "Overridden by environment variable; cannot edit in UI",
@@ -270,11 +336,36 @@
"servingPublicShort": "Public", "servingPublicShort": "Public",
"backendName": "Display name", "backendName": "Display name",
"badgeDefault": "Default", "badgeDefault": "Default",
"badgeDefaultStorage": "Default storage",
"badgeDisabled": "Disabled", "badgeDisabled": "Disabled",
"badgeEnabled": "Enabled", "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", "statTotal": "Total",
"statUsed": "Used", "statUsed": "Used",
"statFree": "Free", "statFree": "Free",
"statFileCount": "Files",
"statQuota": "Quota",
"usageRate": "Usage", "usageRate": "Usage",
"indexImages": "PicHost images {count} · {size}", "indexImages": "PicHost images {count} · {size}",
"setDefault": "Set as default", "setDefault": "Set as default",
@@ -300,12 +391,21 @@
"manageStorageHint": "Configure R2 / S3 / COS backends and URL serving" "manageStorageHint": "Configure R2 / S3 / COS backends and URL serving"
}, },
"stats": { "stats": {
"title": "Statistics", "title": "Gallery",
"subtitle": "Overview and gallery", "subtitle": "Browse, search, and manage uploaded images",
"uploadToday": "Uploaded today", "uploadToday": "Uploaded today",
"uploadMonth": "Uploaded this month", "uploadMonth": "Uploaded this month",
"uploadTotal": "Total uploads", "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", "deleteToday": "Deleted today",
"deleteMonth": "Deleted this month", "deleteMonth": "Deleted this month",
"deleteTotal": "Total deleted", "deleteTotal": "Total deleted",
@@ -314,14 +414,42 @@
"sourceDistribution": "Uploads by source", "sourceDistribution": "Uploads by source",
"sourceWeb": "Web", "sourceWeb": "Web",
"sourceApi": "API", "sourceApi": "API",
"tagWeb": "Web",
"tagApi": "API",
"noData": "No data", "noData": "No data",
"gallery": "Gallery", "gallery": "Gallery",
"imagesSection": "All images",
"filterStorageAll": "All storage", "filterStorageAll": "All storage",
"storage": "Storage", "storage": "Storage",
"searchPlaceholder": "Search filename", "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", "clear": "Clear",
"selected": "{n} selected", "selected": "{n} selected",
"batchDelete": "Delete selected", "batchDelete": "Delete selected",
"batchSelect": "Batch select",
"viewMode": "View mode",
"viewGrid": "Grid view",
"viewList": "List view",
"selectAll": "Select all",
"invertSelection": "Invert",
"clearSelection": "Clear selection",
"scrollTop": "Back to top", "scrollTop": "Back to top",
"loadFailed": "Failed to load statistics", "loadFailed": "Failed to load statistics",
"selectFirst": "Select images first", "selectFirst": "Select images first",
@@ -364,6 +492,27 @@
"image": { "image": {
"empty": "No images", "empty": "No images",
"previewFailed": "Preview failed", "previewFailed": "Preview failed",
"openPreview": "View full image",
"previewTitle": "Image details",
"previewSubtitle": "View image info and links",
"previewOriginalName": "Filename",
"previewUploadedAt": "Uploaded",
"previewSize": "Size",
"previewSizeDetail": "{size} ({bytes} bytes)",
"previewContentType": "File type",
"previewOwner": "Uploader",
"previewStorage": "Storage",
"previewKey": "Image path",
"previewExtension": "Extension",
"previewDimensions": "Dimensions",
"previewDimensionsUnknown": "Loading…",
"previewUploadSource": "Upload source",
"uploadSourceUnknown": "Unknown",
"previewLinks": "Links & embed",
"previewCopyLink": "Copy link",
"previewDownload": "Download",
"previewOpen": "Open in new tab",
"previewClose": "Close",
"uploader": "Uploader: {name}", "uploader": "Uploader: {name}",
"storageBackend": "Storage: {name}" "storageBackend": "Storage: {name}"
}, },
@@ -373,6 +522,11 @@
"confirm": "Delete" "confirm": "Delete"
}, },
"pagination": { "pagination": {
"totalCount": "{total} {unit}",
"pageStatus": "Page {page} / {totalPages}",
"perPage": "{size} / page",
"pageSize": "Page size",
"pageNumber": "Page {page}",
"pageOf": "Page {page} / {totalPages} · {total} {unit}", "pageOf": "Page {page} / {totalPages} · {total} {unit}",
"totalOnly": "{total} {unit}", "totalOnly": "{total} {unit}",
"first": "First page", "first": "First page",
@@ -380,6 +534,8 @@
"next": "Next page", "next": "Next page",
"last": "Last page", "last": "Last page",
"goTo": "Go", "goTo": "Go",
"goToPrefix": "Go to",
"goToSuffix": "",
"pagePlaceholder": "Page" "pagePlaceholder": "Page"
}, },
"api": { "api": {
@@ -408,6 +564,74 @@
"newTokenDesc": "Copy and save it now. You can copy again from the field above after closing.", "newTokenDesc": "Copy and save it now. You can copy again from the field above after closing.",
"copyToken": "Copy token", "copyToken": "Copy token",
"saved": "Saved", "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": { "docs": {
"upload": { "upload": {
"title": "Upload images", "title": "Upload images",
@@ -432,6 +656,14 @@
"twikoo": { "twikoo": {
"title": "Twikoo-compatible upload", "title": "Twikoo-compatible upload",
"desc": "Twikoo / EasyImage 2.0 protocol; stored under images/. Fields: image + token." "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."
} }
} }
}, },
+239 -7
View File
@@ -23,6 +23,7 @@
}, },
"nav": { "nav": {
"api": "API", "api": "API",
"gallery": "图库",
"stats": "统计", "stats": "统计",
"logs": "操作日志", "logs": "操作日志",
"settings": "设置", "settings": "设置",
@@ -66,6 +67,11 @@
"loginFailed": "登录失败,请检查用户名和密码", "loginFailed": "登录失败,请检查用户名和密码",
"captchaHint": "拖动滑块对齐缺口", "captchaHint": "拖动滑块对齐缺口",
"captchaSuccess": "验证通过", "captchaSuccess": "验证通过",
"verificationMisconfigured": "人机验证未正确配置,请联系管理员",
"capInitialState": "验证你是人类",
"capVerifying": "验证中…",
"capSolved": "验证通过",
"capError": "验证失败",
"registerFailed": "注册失败,请检查输入", "registerFailed": "注册失败,请检查输入",
"setupFailed": "初始化失败,请检查输入", "setupFailed": "初始化失败,请检查输入",
"migrateFailed": "迁移失败,请检查输入", "migrateFailed": "迁移失败,请检查输入",
@@ -78,6 +84,11 @@
"invalidPassword": "密码至少 8 位" "invalidPassword": "密码至少 8 位"
} }
}, },
"domainSeparationConfirm": {
"title": "确认保存双域名配置?",
"description": "保存后,仅网站域名可访问管理后台与 API,仅图片域名可提供图片直链。若通过 IP、未配置的 Host,或反代未正确传递 Host 访问,可能无法打开后台。\n\n若发生锁死,可执行 docker exec pichost clear-domains(本地开发:npm run clear-domains)清除域名配置,或在能访问时于设置中关闭「域名分离」。\n\n确定仍要保存吗?",
"confirm": "确认保存"
},
"setup": { "setup": {
"migrateTitle": "迁移到账号密码登录", "migrateTitle": "迁移到账号密码登录",
"initTitle": "首次使用,创建管理员账号", "initTitle": "首次使用,创建管理员账号",
@@ -148,11 +159,13 @@
"url": "直链", "url": "直链",
"markdown": "Markdown", "markdown": "Markdown",
"html": "HTML", "html": "HTML",
"bbcode": "BBCode",
"copied": "已复制到剪贴板", "copied": "已复制到剪贴板",
"copiedLabel": "已复制 {label}", "copiedLabel": "已复制 {label}",
"copiedUrl": "已复制直链", "copiedUrl": "已复制直链",
"copiedMarkdown": "已复制 Markdown", "copiedMarkdown": "已复制 Markdown",
"copiedHtml": "已复制 HTML", "copiedHtml": "已复制 HTML",
"copiedBbcode": "已复制 BBCode",
"copiedFormat": "已复制 {format}", "copiedFormat": "已复制 {format}",
"failed": "复制失败", "failed": "复制失败",
"failedManual": "复制失败,请手动选中链接复制", "failedManual": "复制失败,请手动选中链接复制",
@@ -180,12 +193,55 @@
}, },
"settings": { "settings": {
"title": "系统设置", "title": "系统设置",
"pageTitle": "设置与偏好",
"pageSubtitle": "管理系统配置与操作日志",
"pageSubtitleBasic": "管理系统配置与上传偏好",
"navBasic": "基础设置",
"navDomains": "域名与路径",
"navAccess": "访问控制",
"navPreferences": "偏好设置",
"navLogs": "操作日志",
"systemVersion": "系统版本",
"checkUpdate": "检查更新",
"saveSettings": "保存设置",
"subtitle": "保存后写入数据库;环境变量优先级更高", "subtitle": "保存后写入数据库;环境变量优先级更高",
"featureToggles": "功能开关", "featureToggles": "功能开关",
"featureTogglesHint": "控制注册与系统行为",
"pathAndLink": "路径与链接",
"pathAndLinkHint": "控制图片直链格式与上传目录结构",
"domainSeparationSection": "域名分离",
"allowRegistration": "开放用户注册", "allowRegistration": "开放用户注册",
"allowRegistrationHint": "允许新用户自行注册(普通用户仅可见自己的图片)", "allowRegistrationHint": "允许新用户自行注册(普通用户仅可见自己的图片)",
"accessControl": "访问控制", "accessControl": "访问控制",
"refererHint": "Referer 防盗链,逗号分隔允许引用的域名,留空不限制", "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", "refererPlaceholder": "example.com, www.example.com",
"domainSettings": "域名配置", "domainSettings": "域名配置",
"domainSeparationActive": "已启用域名分离:图片域仅出图,管理域提供后台与 API", "domainSeparationActive": "已启用域名分离:图片域仅出图,管理域提供后台与 API",
@@ -198,20 +254,30 @@
"imageBaseUrlSingleHint": "末尾不加 /;留空则使用当前访问域名;单域名部署无需填写网站域名", "imageBaseUrlSingleHint": "末尾不加 /;留空则使用当前访问域名;单域名部署无需填写网站域名",
"imageBaseUrlPlaceholder": "https://pic.example.com", "imageBaseUrlPlaceholder": "https://pic.example.com",
"imageBaseUrlActive": "当前生效:{url}", "imageBaseUrlActive": "当前生效:{url}",
"hideFolderInUrl": "隐藏直链目录前缀", "runtimeDetected": "检测到当前访问:{url}(不会自动写入配置)",
"hideFolderInUrlHint": "开启后直链为 /xxx.webp,不含 images/ 或日期路径;旧完整路径仍可用。子路径下若存在同名文件,短链可能冲突", "fillDetectedOrigin": "填入检测地址",
"hostRoleUnknown": "当前访问 Host 与配置不一致,可能存在反代绕过风险",
"disableDomainSeparationTitle": "关闭域名分离",
"disableDomainSeparationDesc": "将清除管理域名配置,仅保留图片域名。确定继续?",
"disableDomainSeparationConfirm": "确认关闭",
"domainSeparationRequired": "启用域名分离时需同时填写网站域名与图片域名",
"hideFolderInUrl": "使用简短图片链接",
"hideFolderInUrlHint": "开启后链接仅含域名与文件名,例如 img.example.com/abc.webp;关闭后保留日期或自定义目录,例如 img.example.com/2026/08/abc.webp",
"storageUseDatePath": "上传目录按年/月分组", "storageUseDatePath": "上传目录按年/月分组",
"storageUseDatePathHint": "开启后保存为 images/2026/08/xxx.webp;关闭则为 images/xxx.webp。仅影响启用后的新上传", "storageUseDatePathHint": "开启后保存为 images/2026/08/xxx.webp;关闭则为 images/xxx.webp。仅影响启用后的新上传",
"badgeEnv": ".env", "badgeEnv": ".env",
"badgeSaved": "已保存", "badgeSaved": "已保存",
"badgeDefault": "默认", "badgeDefault": "默认",
"badgeUnset": "未设置", "badgeUnset": "未设置",
"badgeOptional": "可选",
"tokenEnv": "环境变量", "tokenEnv": "环境变量",
"tokenDb": "后台生成", "tokenDb": "后台生成",
"tokenNone": "未配置", "tokenNone": "未配置",
"apiTokenLine": "API Token · {source} ·", "apiTokenLine": "来源:{source}",
"viewReleases": "查看发行版", "viewReleases": "查看发行版",
"updateAvailable": "有新版本 {version}", "updateAvailable": "有新版本 {version}",
"upToDate": "当前已是最新版本",
"checkUpdateFailed": "检查更新失败,请稍后重试",
"unsavedChanges": "有未保存的更改", "unsavedChanges": "有未保存的更改",
"manageToken": "管理 Token", "manageToken": "管理 Token",
"envOverride": "该项已由环境变量覆盖,无法在后台修改", "envOverride": "该项已由环境变量覆盖,无法在后台修改",
@@ -270,11 +336,36 @@
"servingPublicShort": "公开", "servingPublicShort": "公开",
"backendName": "显示名称", "backendName": "显示名称",
"badgeDefault": "默认", "badgeDefault": "默认",
"badgeDefaultStorage": "默认存储",
"badgeDisabled": "已停用", "badgeDisabled": "已停用",
"badgeEnabled": "已启用", "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": "总量", "statTotal": "总量",
"statUsed": "已用", "statUsed": "已用",
"statFree": "剩余", "statFree": "剩余",
"statFileCount": "文件数量",
"statQuota": "配额",
"usageRate": "使用率", "usageRate": "使用率",
"indexImages": "PicHost 图片 {count} 张 · {size}", "indexImages": "PicHost 图片 {count} 张 · {size}",
"setDefault": "设为默认", "setDefault": "设为默认",
@@ -300,12 +391,21 @@
"manageStorageHint": "配置 R2 / S3 / COS 等多后端与直链策略" "manageStorageHint": "配置 R2 / S3 / COS 等多后端与直链策略"
}, },
"stats": { "stats": {
"title": "统计", "title": "图库",
"subtitle": "数据概览与图库记录", "subtitle": "浏览、搜索与管理已上传图片",
"uploadToday": "今日上传", "uploadToday": "今日上传",
"uploadMonth": "本月上传", "uploadMonth": "本月上传",
"uploadTotal": "累计上传", "uploadTotal": "累计上传",
"storedCount": "当前库存", "storedCount": "当前存储",
"totalFiles": "总文件数",
"totalOccupied": "共占用 {size}",
"storageUsage": "存储使用率",
"noQuota": "未配置容量上限",
"vsYesterday": "较昨日",
"vsLastMonth": "较上月",
"trendUp": "↑ {p}%",
"trendDown": "↓ {p}%",
"trendFlat": "持平",
"deleteToday": "今日删除", "deleteToday": "今日删除",
"deleteMonth": "本月删除", "deleteMonth": "本月删除",
"deleteTotal": "累计删除", "deleteTotal": "累计删除",
@@ -314,14 +414,42 @@
"sourceDistribution": "上传来源分布", "sourceDistribution": "上传来源分布",
"sourceWeb": "网页", "sourceWeb": "网页",
"sourceApi": "API", "sourceApi": "API",
"tagWeb": "网页",
"tagApi": "API",
"noData": "暂无数据", "noData": "暂无数据",
"gallery": "图库记录", "gallery": "图库记录",
"imagesSection": "全部图片",
"filterStorageAll": "全部存储", "filterStorageAll": "全部存储",
"storage": "存储", "storage": "存储",
"searchPlaceholder": "搜索文件名", "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}", "selected": "已选 {n}",
"batchDelete": "批量删除", "batchDelete": "批量删除",
"batchSelect": "批量选择",
"viewMode": "视图模式",
"viewGrid": "网格视图",
"viewList": "列表视图",
"selectAll": "全选",
"invertSelection": "反选",
"clearSelection": "取消选择",
"scrollTop": "回到顶部", "scrollTop": "回到顶部",
"loadFailed": "加载统计失败", "loadFailed": "加载统计失败",
"selectFirst": "请先选择图片", "selectFirst": "请先选择图片",
@@ -364,6 +492,27 @@
"image": { "image": {
"empty": "暂无图片", "empty": "暂无图片",
"previewFailed": "预览失败", "previewFailed": "预览失败",
"openPreview": "查看大图",
"previewTitle": "图片详情",
"previewSubtitle": "查看图片信息与链接",
"previewOriginalName": "文件名",
"previewUploadedAt": "上传时间",
"previewSize": "大小",
"previewSizeDetail": "{size}({bytes} 字节)",
"previewContentType": "文件类型",
"previewOwner": "上传用户",
"previewStorage": "存储位置",
"previewKey": "图片路径",
"previewExtension": "扩展名",
"previewDimensions": "尺寸",
"previewDimensionsUnknown": "加载中…",
"previewUploadSource": "上传方式",
"uploadSourceUnknown": "未知",
"previewLinks": "链接与嵌入",
"previewCopyLink": "复制链接",
"previewDownload": "下载原图",
"previewOpen": "新窗口打开",
"previewClose": "关闭",
"uploader": "上传者:{name}", "uploader": "上传者:{name}",
"storageBackend": "存储:{name}" "storageBackend": "存储:{name}"
}, },
@@ -373,6 +522,11 @@
"confirm": "确认删除" "confirm": "确认删除"
}, },
"pagination": { "pagination": {
"totalCount": "共 {total} {unit}",
"pageStatus": "第 {page} / {totalPages} 页",
"perPage": "{size} 条/页",
"pageSize": "每页条数",
"pageNumber": "第 {page} 页",
"pageOf": "第 {page} / {totalPages} 页 · 共 {total} {unit}", "pageOf": "第 {page} / {totalPages} 页 · 共 {total} {unit}",
"totalOnly": "共 {total} {unit}", "totalOnly": "共 {total} {unit}",
"first": "第一页", "first": "第一页",
@@ -380,6 +534,8 @@
"next": "下一页", "next": "下一页",
"last": "最后一页", "last": "最后一页",
"goTo": "跳转", "goTo": "跳转",
"goToPrefix": "前往",
"goToSuffix": "页",
"pagePlaceholder": "页码" "pagePlaceholder": "页码"
}, },
"api": { "api": {
@@ -408,6 +564,74 @@
"newTokenDesc": "请立即复制保存。关闭弹窗后仍可在上方输入框复制,但请尽快更新到你的脚本配置中。", "newTokenDesc": "请立即复制保存。关闭弹窗后仍可在上方输入框复制,但请尽快更新到你的脚本配置中。",
"copyToken": "复制 Token", "copyToken": "复制 Token",
"saved": "我已保存", "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": { "docs": {
"upload": { "upload": {
"title": "上传图片", "title": "上传图片",
@@ -432,6 +656,14 @@
"twikoo": { "twikoo": {
"title": "twikoo 兼容上传", "title": "twikoo 兼容上传",
"desc": "兼容 Twikoo / EasyImage 2.0 协议,图片存入 images/ 目录;字段 image + token。" "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'], css: ['~/assets/css/main.css'],
vue: {
compilerOptions: {
isCustomElement: tag => tag.startsWith('cap-')
}
},
colorMode: { colorMode: {
preference: 'system', preference: 'system',
fallback: 'light' fallback: 'light'
+1221 -2
View File
File diff suppressed because it is too large. Load diff
+6 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "pichost", "name": "pichost",
"version": "1.2.1", "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.", "description": "Self-hosted image hosting for your NAS / home server — Nuxt admin UI, local disk or S3-compatible storage, server-side WebP compression, referer protection, Twikoo/EasyImage compatible.",
"homepage": "https://github.com/O96u/PicHost#readme", "homepage": "https://github.com/O96u/PicHost#readme",
"repository": { "repository": {
@@ -35,6 +35,8 @@
"start": "node .output/server/index.mjs", "start": "node .output/server/index.mjs",
"reset-password": "node server/cli/reset-password.mjs", "reset-password": "node server/cli/reset-password.mjs",
"migrate": "node server/cli/migrate-to-single-images.mjs", "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:prepare": "node docs-site/copy-screenshots.mjs",
"docs:dev": "npm run docs:prepare && vitepress dev docs-site", "docs:dev": "npm run docs:prepare && vitepress dev docs-site",
"docs:build": "npm run docs:prepare && vitepress build docs-site", "docs:build": "npm run docs:prepare && vitepress build docs-site",
@@ -45,6 +47,7 @@
"@iconify-json/lucide": "^1.2.114", "@iconify-json/lucide": "^1.2.114",
"@nuxt/ui": "^4.9.0", "@nuxt/ui": "^4.9.0",
"@nuxtjs/i18n": "^10.6.0", "@nuxtjs/i18n": "^10.6.0",
"cap-widget": "^0.1.57",
"nuxt": "^4.4.8", "nuxt": "^4.4.8",
"sharp": "^0.35.3", "sharp": "^0.35.3",
"tailwindcss": "^4.3.1" "tailwindcss": "^4.3.1"
@@ -53,8 +56,10 @@
"@nuxt/eslint": "^1.16.0", "@nuxt/eslint": "^1.16.0",
"@types/node": "^22.15.0", "@types/node": "^22.15.0",
"eslint": "^10.6.0", "eslint": "^10.6.0",
"mermaid": "^11.17.2",
"typescript": "^6.0.3", "typescript": "^6.0.3",
"vitepress": "^1.6.4", "vitepress": "^1.6.4",
"vitepress-plugin-mermaid": "^2.0.17",
"vitest": "^3.2.4", "vitest": "^3.2.4",
"vue-tsc": "^3.3.5" "vue-tsc": "^3.3.5"
} }
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more