7 Commits
Author SHA1 Message Date
O96u 7c45a78572 release: v1.0.4
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
Add PasswordInput with show/hide toggle, align legacy setup/register
routing, merge duplicate i18n keys, and remove unused jose dependency.
2026-08-25 16:11:50 +08:00
O96u 661146ce20 docs: add Linux.do friend link and align README tables 2026-08-24 10:41:52 +08:00
O96u 9d2ee96af0 fix: CI typecheck and native ARM Docker builds for v1.0.3
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
Fix TypeScript errors blocking CI, split Docker publish into
native amd64/arm64 jobs with manifest merge, and add npm cache mounts.
2026-08-23 18:26:13 +08:00
O96u 22cb2ca8bc release: v1.0.2
Publish Docker image / build-and-push (push) Canceled after 0s
GitHub Release / release (push) Canceled after 0s
ci / ci (22, ubuntu-latest) (push) Canceled after 0s
Add i18n (zh-CN/en), mobile navigation menus, stats and upload UI
improvements, and Docker reset-password CLI for emergency recovery.
2026-08-23 17:43:42 +08:00
O96u 074e4502c2 ci: auto-create GitHub Release from CHANGELOG on version tags
Add workflow_dispatch to backfill releases for existing tags.
2026-08-22 19:14:25 +08:00
O96u 1096fa8635 docs: use docker run for quick start in README
Users can pull muxui/pichost from Docker Hub without cloning the repo.
2026-08-22 18:55:16 +08:00
O96u 80d2bca4e0 ci: build Docker image only on version tags
Stop publishing on main push and remove GHCR; images go to Docker Hub only.
2026-08-22 18:50:33 +08:00
52 changed files with 4094 additions and 804 deletions

No files matched your search

+60 -44
View File
@@ -2,22 +2,30 @@ name: Publish Docker image
on:
push:
branches: [main]
tags:
- 'v*'
workflow_dispatch:
permissions:
contents: read
packages: write
env:
IMAGE_NAME: pichost
jobs:
build-and-push:
build:
if: ${{ !contains(github.event.head_commit.message, '[skip docker]') }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- platform: linux/amd64
runner: ubuntu-latest
suffix: amd64
- platform: linux/arm64
runner: ubuntu-24.04-arm
suffix: arm64
runs-on: ${{ matrix.runner }}
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
@@ -25,59 +33,67 @@ jobs:
- name: Checkout
uses: actions/checkout@v7
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to GitHub Container Registry
uses: docker/login-action@v3
with:
registry: ghcr.io
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Log in to Docker Hub
if: env.DOCKERHUB_USERNAME != '' && env.DOCKERHUB_TOKEN != ''
uses: docker/login-action@v3
with:
username: ${{ env.DOCKERHUB_USERNAME }}
password: ${{ env.DOCKERHUB_TOKEN }}
- name: Resolve image names
id: images
- name: Resolve version
id: version
run: |
names="ghcr.io/${OWNER}/${IMAGE_NAME}"
if [ -n "${DOCKERHUB_USERNAME}" ]; then
names="${names}
${DOCKERHUB_USERNAME}/${IMAGE_NAME}"
if [ "${{ github.ref_type }}" = "tag" ]; then
echo "value=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_OUTPUT"
else
echo "value=dev" >> "$GITHUB_OUTPUT"
fi
{
echo "list<<EOF"
echo "${names}"
echo "EOF"
} >> "$GITHUB_OUTPUT"
env:
OWNER: ${{ github.repository_owner }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
# Same tags for ghcr.io and Docker Hub: latest + 1.0.0 (no v prefix)
images: ${{ steps.images.outputs.list }}
tags: |
type=raw,value=latest,enable=${{ github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v') }}
type=semver,pattern={{version}}
- name: Build and push
- name: Build and push platform image
uses: docker/build-push-action@v6
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
platforms: ${{ matrix.platform }}
tags: |
${{ env.DOCKERHUB_USERNAME }}/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.value }}-${{ matrix.suffix }}
cache-from: type=gha,scope=${{ matrix.suffix }}
cache-to: type=gha,mode=max,scope=${{ matrix.suffix }}
merge:
if: ${{ !contains(github.event.head_commit.message, '[skip docker]') }}
needs: build
runs-on: ubuntu-latest
env:
DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }}
DOCKERHUB_TOKEN: ${{ secrets.DOCKERHUB_TOKEN }}
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Docker Hub
uses: docker/login-action@v3
with:
username: ${{ env.DOCKERHUB_USERNAME }}
password: ${{ env.DOCKERHUB_TOKEN }}
- name: Resolve version
id: version
run: |
if [ "${{ github.ref_type }}" = "tag" ]; then
echo "value=${GITHUB_REF#refs/tags/v}" >> "$GITHUB_OUTPUT"
else
echo "value=dev" >> "$GITHUB_OUTPUT"
fi
- name: Create multi-arch manifest
run: |
IMAGE="${DOCKERHUB_USERNAME}/${IMAGE_NAME}"
VERSION="${{ steps.version.outputs.value }}"
docker buildx imagetools create \
-t "${IMAGE}:${VERSION}" \
-t "${IMAGE}:latest" \
"${IMAGE}:${VERSION}-amd64" \
"${IMAGE}:${VERSION}-arm64"
+71
View File
@@ -0,0 +1,71 @@
name: GitHub Release
on:
push:
tags:
- 'v*'
workflow_dispatch:
inputs:
tag:
description: '要发布 Release 的标签(如 v1.0.1)'
required: true
type: string
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v7
with:
ref: ${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref }}
- name: Setup Node
uses: actions/setup-node@v6
with:
node-version: 22
cache: npm
- name: Install npm 11
run: npm install -g npm@11.12.1
- name: Install dependencies
run: npm ci
- name: Extract release notes from CHANGELOG
id: notes
run: |
if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then
TAG="${{ inputs.tag }}"
else
TAG="${GITHUB_REF#refs/tags/}"
fi
VERSION="${TAG#v}"
BODY_FILE="${RUNNER_TEMP}/release-notes.md"
awk -v ver="$VERSION" '
/^## \[/ {
if (found) exit
if ($0 ~ "\\[" ver "\\]") found = 1
next
}
found { print }
' CHANGELOG.md > "$BODY_FILE"
if [ ! -s "$BODY_FILE" ]; then
echo "未在 CHANGELOG.md 找到版本 ${VERSION},使用自动生成说明。" >&2
echo "## PicHost ${TAG}" > "$BODY_FILE"
fi
echo "tag=${TAG}" >> "$GITHUB_OUTPUT"
echo "body_path=${BODY_FILE}" >> "$GITHUB_OUTPUT"
- name: Create GitHub Release
uses: softprops/action-gh-release@v2
with:
tag_name: ${{ steps.notes.outputs.tag }}
name: PicHost ${{ steps.notes.outputs.tag }}
body_path: ${{ steps.notes.outputs.body_path }}
draft: false
prerelease: false
make_latest: true
+4
View File
@@ -36,3 +36,7 @@ data
# 本地 Git hooks 模板(仅安装在 .git/hooks/,不进仓库)
git-hooks/
# 飞牛 fpk 工程与产物(仅本地维护,不进仓库)
scripts/fpk/
dist-fpk/
+39
View File
@@ -2,6 +2,43 @@
本仓库自 **v1.0.0** 起作为正式版维护;此前历史提交已归档重置。
## [1.0.4] - 2026-08-25
### 新增
- 密码输入框支持显示/隐藏切换(`PasswordInput` 组件,含无障碍文案)
### 改进
- 遗留 `ADMIN_SECRET` 部署:`/setup`、`/register` 路由与 `needsMigration` 检测对齐
- 合并重复的密码不一致 i18n 文案;移除未使用的 `jose` 依赖
### 修复
- 修复 `PasswordInput` 导致 CI typecheck 失败
## [1.0.3] - 2026-08-23
### 修复
- 修复 CI typecheck 失败(移动端菜单、i18n、统计页图库刷新)
- Docker 构建:arm64 改用原生 ARM Runner,避免 QEMU 下 `npm ci` 极慢
- Docker 构建:启用 npm 缓存挂载,加快依赖安装
## [1.0.2] - 2026-08-23
### 新增
- 中英文界面(`@nuxtjs/i18n`),语言切换与主题切换独立菜单
- 移动端导航:汉堡菜单 + 分组用户菜单(语言 / 外观 / 账户)
- Docker 忘记密码:`docker exec pichost reset-password`(随机密码,见 `server/cli/`)
### 改进
- 统计页工具栏与图库布局(桌面单行、移动端适配)
- 上传卡片视觉优化(背景图、插图、悬停边框动效)
- Logo 与上传区图片压缩,减小体积
## [1.0.1] - 2026-08-22
### 修复
@@ -33,5 +70,7 @@
- **v1.1.0**(计划中):S3、Cloudflare R2 及更多对象存储后端
[1.0.3]: https://github.com/O96u/PicHost/releases/tag/v1.0.3
[1.0.2]: https://github.com/O96u/PicHost/releases/tag/v1.0.2
[1.0.1]: https://github.com/O96u/PicHost/releases/tag/v1.0.1
[1.0.0]: https://github.com/O96u/PicHost/releases/tag/v1.0.0
+8 -2
View File
@@ -1,3 +1,5 @@
# syntax=docker/dockerfile:1
FROM node:22-alpine AS build
WORKDIR /app
@@ -6,7 +8,8 @@ WORKDIR /app
RUN npm install -g npm@11.12.1
COPY package.json package-lock.json ./
RUN npm ci
RUN --mount=type=cache,target=/root/.npm \
npm ci
COPY . .
RUN npm run build
@@ -20,8 +23,11 @@ ENV NODE_ENV=production \
DATA_DIR=/data
COPY --from=build /app/.output ./.output
COPY server/cli/reset-password.mjs ./server/cli/reset-password.mjs
COPY docker-entrypoint.sh /docker-entrypoint.sh
RUN chmod +x /docker-entrypoint.sh
EXPOSE 6892
VOLUME /data
CMD ["node", ".output/server/index.mjs"]
ENTRYPOINT ["/docker-entrypoint.sh"]
+74 -54
View File
@@ -29,17 +29,17 @@
## Screenshots
| Login | Upload |
|:---:|:---:|
| Login | Upload |
| :----------------------------------: | :------------------------------------: |
| ![Login](docs/screenshots/login.png) | ![Upload](docs/screenshots/upload.png) |
| Upload preferences | Stats & gallery |
|:---:|:---:|
| Upload preferences | Stats & gallery |
| :----------------------------------------------: | :----------------------------------: |
| ![Preferences](docs/screenshots/preferences.png) | ![Stats](docs/screenshots/stats.png) |
| Settings | |
|:---:|:---:|
| ![Settings](docs/screenshots/settings.png) | |
| Settings | |
| :----------------------------------------: | :-: |
| ![Settings](docs/screenshots/settings.png) | |
## Features
@@ -58,12 +58,26 @@
### Docker (recommended)
```bash
git clone https://github.com/O96u/PicHost.git
cd PicHost
docker compose up -d
docker run -d \
--name pichost \
-p 6892:6892 \
-v ./data:/data \
--restart unless-stopped \
muxui/pichost:latest
```
Default port: **6892**. Complete the setup wizard in the browser. Image: `muxui/pichost:latest` (fallback: `ghcr.io/o96u/pichost:latest`).
Default port: **6892**. Open `http://<host>:6892` in your browser and complete the setup wizard.
**Forgot password** (requires `docker exec` / server access):
```bash
docker exec pichost reset-password # admin only, when there is exactly one
docker exec pichost reset-password <username> # admin or regular user
```
A random password is printed. Fails if the user does not exist.
If you cloned the repo, you can also use `docker compose up -d` (see `docker-compose.yml`).
### Local development
@@ -81,41 +95,41 @@ If you only had `ADMIN_SECRET` and no user table, log in with the secret once an
## Tech Stack
| Layer | Technology |
|-------|------------|
| Frontend | Nuxt 4, Vue 3, Nuxt UI 4, Tailwind CSS 4 |
| Backend | Nitro (Node.js), SQLite |
| Images | sharp (WebP transcoding & compression) |
| Auth | Session cookie, scrypt password hashing, API tokens |
| Storage | Local disk (`DATA_DIR`) |
| Deploy | Docker (amd64 / arm64), docker compose |
| Tests | Vitest |
| Layer | Technology |
| -------- | --------------------------------------------------- |
| Frontend | Nuxt 4, Vue 3, Nuxt UI 4, Tailwind CSS 4 |
| Backend | Nitro (Node.js), SQLite |
| Images | sharp (WebP transcoding & compression) |
| Auth | Session cookie, scrypt password hashing, API tokens |
| Storage | Local disk (`DATA_DIR`) |
| Deploy | Docker (amd64 / arm64), docker compose |
| Tests | Vitest |
## Environment variables
| Variable | Description |
|----------|-------------|
| `API_UPLOAD_TOKEN` | Global upload token (`Auth-Token` header); can be generated in the API page |
| `ALLOWED_REFERER_HOSTS` | Hotlink allowlist (comma-separated hostnames) |
| `IMAGE_BASE_URL` | Public base URL for image links |
| `WEBP_QUALITY` | Server WebP quality 1–100, default 80 |
| `AUTO_DELETE_DAYS` | Global auto-delete days (0 = off); admin + orphan images only |
| `DATA_DIR` | Data directory, default `/data` (container) or `./data` (local) |
| `ADMIN_SECRET` | Legacy v1.0 migration only |
| `DEV_BYPASS_ACCESS` | Dev only — bypass auth (never in production) |
| Variable | Description |
| ----------------------- | --------------------------------------------------------------------------- |
| `API_UPLOAD_TOKEN` | Global upload token (`Auth-Token` header); can be generated in the API page |
| `ALLOWED_REFERER_HOSTS` | Hotlink allowlist (comma-separated hostnames) |
| `IMAGE_BASE_URL` | Public base URL for image links |
| `WEBP_QUALITY` | Server WebP quality 1–100, default 80 |
| `AUTO_DELETE_DAYS` | Global auto-delete days (0 = off); admin + orphan images only |
| `DATA_DIR` | Data directory, default `/data` (container) or `./data` (local) |
| `ADMIN_SECRET` | Legacy v1.0 migration only |
| `DEV_BYPASS_ACCESS` | Dev only — bypass auth (never in production) |
Environment variables override database settings. See [`.env.example`](.env.example).
## Users & permissions
| Scenario | Auth | Ownership / visibility |
|----------|------|------------------------|
| Web upload | Session | Current user |
| API upload + **user token** | `Auth-Token` | Token owner |
| API upload + **global token** | `Auth-Token` | Admin (`userId` null) |
| Twikoo `/api/index.php` | form `token` | Same as global token |
| Gallery list / search / delete | Session or token | Users: own only; admin: all |
| Direct link `GET /images/...` | None (Referer rules) | Public if URL is known |
| Scenario | Auth | Ownership / visibility |
| ------------------------------ | -------------------- | --------------------------- |
| Web upload | Session | Current user |
| API upload + **user token** | `Auth-Token` | Token owner |
| API upload + **global token** | `Auth-Token` | Admin (`userId` null) |
| Twikoo `/api/index.php` | form `token` | Same as global token |
| Gallery list / search / delete | Session or token | Users: own only; admin: all |
| Direct link `GET /images/...` | None (Referer rules) | Public if URL is known |
Regular users are limited to the `images/` folder; custom `folder` requires admin or global token.
@@ -133,12 +147,12 @@ Pattern: `folder/YYYY/MM/randomId.webp` + `.meta.json`. Back up the entire `/dat
## API overview
| Method | Path | Description |
|--------|------|-------------|
| POST | `/api/images/upload` | Upload image |
| GET | `/api/images` | Paginated list |
| DELETE | `/api/images` | Delete one (`key`) |
| POST | `/api/index.php` | Twikoo / EasyImage 2.0 |
| Method | Path | Description |
| ------ | -------------------- | ---------------------- |
| POST | `/api/images/upload` | Upload image |
| GET | `/api/images` | Paginated list |
| DELETE | `/api/images` | Delete one (`key`) |
| POST | `/api/index.php` | Twikoo / EasyImage 2.0 |
Upload example:
@@ -153,11 +167,11 @@ Full docs and copyable cURL snippets are on the **API** page after deployment.
## Twikoo
| Setting | Value |
|---------|-------|
| `IMAGE_CDN` | `easyimage` |
| `IMAGE_CDN_URL` | `https://your-domain/api/index.php` |
| `IMAGE_CDN_TOKEN` | Same as `API_UPLOAD_TOKEN` |
| Setting | Value |
| ----------------- | ----------------------------------- |
| `IMAGE_CDN` | `easyimage` |
| `IMAGE_CDN_URL` | `https://your-domain/api/index.php` |
| `IMAGE_CDN_TOKEN` | Same as `API_UPLOAD_TOKEN` |
## Reverse proxy
@@ -178,12 +192,18 @@ npm test # Unit tests
## Roadmap
| Version | Plan |
|---------|------|
| **v1.0.1** | Settings version display, mobile upload preferences layout fix (current) |
| **v1.0.0** | Local storage, multi-user, API, Twikoo |
| **v1.1.0** | S3, Cloudflare R2, and more object storage backends |
| Version | Plan |
| ---------- | -------------------------------------------------------------- |
| **v1.0.3** | CI and Docker multi-arch build fixes (current) |
| **v1.0.2** | i18n, mobile menus, stats/upload UI, Docker password reset |
| **v1.0.1** | Settings version display, mobile upload preferences layout fix |
| **v1.0.0** | Local storage, multi-user, API, Twikoo |
| **v1.1.0** | S3, Cloudflare R2, and more object storage backends |
## License
[MIT](LICENSE)
## Friend links
[LINUX DO](https://linux.do/)
+79 -54
View File
@@ -29,17 +29,17 @@
## 界面预览
| 登录 | 上传 |
|:---:|:---:|
| 登录 | 上传 |
| :---------------------------------: | :----------------------------------: |
| ![登录](docs/screenshots/login.png) | ![上传](docs/screenshots/upload.png) |
| 上传偏好 | 统计与图库 |
|:---:|:---:|
| 上传偏好 | 统计与图库 |
| :-------------------------------------------: | :---------------------------------: |
| ![上传偏好](docs/screenshots/preferences.png) | ![统计](docs/screenshots/stats.png) |
| 系统设置 | |
|:---:|:---:|
| ![设置](docs/screenshots/settings.png) | |
| 系统设置 | |
| :------------------------------------: | :-: |
| ![设置](docs/screenshots/settings.png) | |
## 特性
@@ -58,12 +58,31 @@
### Docker(推荐)
```bash
git clone https://github.com/O96u/PicHost.git
cd PicHost
docker compose up -d
docker run -d \
--name pichost \
-p 6892:6892 \
-v ./data:/data \
--restart unless-stopped \
muxui/pichost:latest
```
默认端口 **6892**。浏览器打开后按引导创建管理员即可。镜像:`muxui/pichost:latest`(备用 `ghcr.io/o96u/pichost:latest`)。
默认端口 **6892**。浏览器打开 `http://<主机IP>:6892`,按引导创建管理员即可。
**忘记密码**(需能执行 `docker exec`,相当于服务器权限):
```bash
# 无参数:重置管理员(仅当系统中只有一个管理员时)
docker exec pichost reset-password
# 指定用户名:可重置管理员或普通用户
docker exec pichost reset-password 用户名
```
终端会打印随机新密码;用户不存在时会报错。登录后请到「修改密码」更换。
本地:`npm run reset-password` 或 `npm run reset-password -- 用户名`
已克隆仓库时也可用 `docker compose up -d`(见仓库内 `docker-compose.yml`)。
### 本地开发
@@ -81,41 +100,41 @@ npm run dev
## 技术栈
| 层级 | 技术 |
|------|------|
| 前端 | Nuxt 4、Vue 3、Nuxt UI 4、Tailwind CSS 4 |
| 后端 | Nitro(Node.js)、SQLite |
| 图片处理 | sharp(WebP 转码与压缩) |
| 鉴权 | Session Cookie、scrypt 密码哈希、API Token |
| 存储 | 本地磁盘(`DATA_DIR`) |
| 部署 | Docker(amd64 / arm64)、docker compose |
| 测试 | Vitest |
| 层级 | 技术 |
| -------- | ------------------------------------------ |
| 前端 | Nuxt 4、Vue 3、Nuxt UI 4、Tailwind CSS 4 |
| 后端 | Nitro(Node.js)、SQLite |
| 图片处理 | sharp(WebP 转码与压缩) |
| 鉴权 | Session Cookie、scrypt 密码哈希、API Token |
| 存储 | 本地磁盘(`DATA_DIR`) |
| 部署 | Docker(amd64 / arm64)、docker compose |
| 测试 | Vitest |
## 环境变量
| 变量 | 说明 |
|------|------|
| `API_UPLOAD_TOKEN` | 全局上传 Token(`Auth-Token` 头);未配置可在后台 API 页生成 |
| `ALLOWED_REFERER_HOSTS` | 防盗链白名单(逗号分隔 hostname) |
| `IMAGE_BASE_URL` | 图片直链公网域名(反代时建议填写) |
| `WEBP_QUALITY` | 服务端 WebP 质量 1–100,默认 80 |
| `AUTO_DELETE_DAYS` | 全局自动删除天数(0 关闭);仅影响管理员及无归属历史图 |
| `DATA_DIR` | 数据目录,默认 `/data`(容器)或 `./data`(本地) |
| `ADMIN_SECRET` | 仅遗留 v1.0 迁移,新安装不需要 |
| `DEV_BYPASS_ACCESS` | 开发用,跳过登录(生产勿开) |
| 变量 | 说明 |
| ----------------------- | ------------------------------------------------------------ |
| `API_UPLOAD_TOKEN` | 全局上传 Token(`Auth-Token` 头);未配置可在后台 API 页生成 |
| `ALLOWED_REFERER_HOSTS` | 防盗链白名单(逗号分隔 hostname) |
| `IMAGE_BASE_URL` | 图片直链公网域名(反代时建议填写) |
| `WEBP_QUALITY` | 服务端 WebP 质量 1–100,默认 80 |
| `AUTO_DELETE_DAYS` | 全局自动删除天数(0 关闭);仅影响管理员及无归属历史图 |
| `DATA_DIR` | 数据目录,默认 `/data`(容器)或 `./data`(本地) |
| `ADMIN_SECRET` | 仅遗留 v1.0 迁移,新安装不需要 |
| `DEV_BYPASS_ACCESS` | 开发用,跳过登录(生产勿开) |
环境变量优先级高于后台设置。详见 [`.env.example`](.env.example)。
## 用户与权限
| 场景 | 鉴权 | 图片归属 / 可见范围 |
|------|------|---------------------|
| 网页上传 | Session | 当前登录用户 |
| API 上传 + **个人 Token** | `Auth-Token` | 该 Token 所属用户 |
| API 上传 + **全局 Token** | `Auth-Token` | 管理员(`userId` 为空) |
| Twikoo `/api/index.php` | 表单 `token` | 与全局 Token 相同 |
| 图库列表 / 搜索 / 删除 | Session 或 Token | 普通用户仅自己;管理员全部 |
| 图片直链 `GET /images/...` | 无(Referer 防盗链) | 知道 URL 即可访问 |
| 场景 | 鉴权 | 图片归属 / 可见范围 |
| -------------------------- | -------------------- | -------------------------- |
| 网页上传 | Session | 当前登录用户 |
| API 上传 + **个人 Token** | `Auth-Token` | 该 Token 所属用户 |
| API 上传 + **全局 Token** | `Auth-Token` | 管理员(`userId` 为空) |
| Twikoo `/api/index.php` | 表单 `token` | 与全局 Token 相同 |
| 图库列表 / 搜索 / 删除 | Session 或 Token | 普通用户仅自己;管理员全部 |
| 图片直链 `GET /images/...` | 无(Referer 防盗链) | 知道 URL 即可访问 |
普通用户上传目录固定为 `images/`;自定义 `folder` 仅管理员或全局 Token 可用。
@@ -133,12 +152,12 @@ npm run dev
## API 概览
| 方法 | 路径 | 说明 |
|------|------|------|
| POST | `/api/images/upload` | 上传图片 |
| GET | `/api/images` | 分页列表 |
| DELETE | `/api/images` | 删除单张(`key`) |
| POST | `/api/index.php` | Twikoo / EasyImage 2.0 |
| 方法 | 路径 | 说明 |
| ------ | -------------------- | ---------------------- |
| POST | `/api/images/upload` | 上传图片 |
| GET | `/api/images` | 分页列表 |
| DELETE | `/api/images` | 删除单张(`key`) |
| POST | `/api/index.php` | Twikoo / EasyImage 2.0 |
上传示例:
@@ -153,11 +172,11 @@ curl -X POST "https://pic.example.com/api/images/upload" \
## Twikoo
| 配置项 | 值 |
|--------|-----|
| `IMAGE_CDN` | `easyimage` |
| `IMAGE_CDN_URL` | `https://你的域名/api/index.php` |
| `IMAGE_CDN_TOKEN` | 与 `API_UPLOAD_TOKEN` 相同 |
| 配置项 | 值 |
| ----------------- | -------------------------------- |
| `IMAGE_CDN` | `easyimage` |
| `IMAGE_CDN_URL` | `https://你的域名/api/index.php` |
| `IMAGE_CDN_TOKEN` | 与 `API_UPLOAD_TOKEN` 相同 |
## 反向代理
@@ -178,12 +197,18 @@ npm test # 单元测试
## 路线图
| 版本 | 计划 |
|------|------|
| **v1.0.1** | 设置页版本展示、移动端上传偏好布局修复(当前) |
| **v1.0.0** | 本地存储、多用户、API、Twikoo |
| **v1.1.0** | S3、Cloudflare R2 等对象存储后端 |
| 版本 | 计划 |
| ---------- | ------------------------------------------------- |
| **v1.0.3** | CI 与 Docker 多架构构建修复(当前) |
| **v1.0.2** | 中英文、移动端菜单、统计/上传 UI、Docker 重置密码 |
| **v1.0.1** | 设置页版本展示、移动端上传偏好布局修复 |
| **v1.0.0** | 本地存储、多用户、API、Twikoo |
| **v1.1.0** | S3、Cloudflare R2 等对象存储后端 |
## License
[MIT](LICENSE)
## 友链
[LINUX DO](https://linux.do/)
+4 -2
View File
@@ -1,8 +1,10 @@
<script setup lang="ts">
const { t } = useI18n()
useHead({
title: 'PicHost - 个人图床',
title: () => t('app.title'),
meta: [
{ name: 'description', content: '个人自用的轻量图床系统' }
{ name: 'description', content: () => t('app.description') }
]
})
</script>
+19 -2
View File
@@ -59,14 +59,31 @@
border-radius: 1rem;
border-width: 2px;
border-style: dashed;
border-color: var(--ui-border);
background-color: color-mix(in oklab, var(--ui-bg-elevated) 50%, transparent);
background-color: color-mix(in oklab, var(--ui-bg-elevated) 72%, transparent);
padding: 2.5rem;
transition:
border-color 0.2s cubic-bezier(0.4, 0, 0.2, 1),
background-color 0.2s cubic-bezier(0.4, 0, 0.2, 1),
box-shadow 0.2s cubic-bezier(0.4, 0, 0.2, 1);
}
.upload-card-surface:not(.upload-card-surface--panel) {
border-color: var(--ui-border);
}
.upload-card-surface:not(.upload-card-surface--panel):hover,
.upload-card-surface:not(.upload-card-surface--panel).upload-card-surface--active {
border-color: var(--ui-primary);
background-color: color-mix(in oklab, var(--ui-primary) 10%, var(--ui-bg-elevated) 72%);
box-shadow: 0 0 0 1px color-mix(in oklab, var(--ui-primary) 25%, transparent),
0 8px 24px color-mix(in oklab, var(--ui-primary) 18%, transparent);
}
.upload-card-surface--panel {
border-style: solid;
border-color: var(--ui-border);
background-color: var(--ui-bg-elevated);
background-image: none;
box-shadow: var(--ui-shadow-sm);
padding: 0;
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 506 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 546 KiB

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

+21 -30
View File
@@ -2,13 +2,10 @@
import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png'
const emit = defineEmits<{
success: []
}>()
const router = useRouter()
const { login, fetchStatus, authStatus } = useAuth()
const toast = useToast()
const { t } = useI18n()
const username = ref('')
const password = ref('')
@@ -46,11 +43,10 @@ async function submit() {
username.value = ''
password.value = ''
secret.value = ''
emit('success')
toast.add({ title: '登录成功', color: 'success' })
toast.add({ title: t('auth.loginSuccess'), color: 'success' })
} else {
toast.add({
title: result.error ?? (legacyMode.value ? '登录失败,请检查密钥' : '用户名或密码错误'),
title: result.error ?? (legacyMode.value ? t('auth.loginFailedSecret') : t('auth.loginFailedCredentials')),
color: 'error'
})
}
@@ -61,7 +57,10 @@ async function submit() {
</script>
<template>
<div class="flex min-h-screen items-center justify-center bg-muted/30 p-4 sm:p-6">
<div class="relative flex min-h-screen items-center justify-center bg-muted/30 p-4 sm:p-6">
<div class="absolute top-4 right-4">
<AuthPagePreferences />
</div>
<div class="w-full max-w-sm rounded-2xl border border-default bg-elevated p-6 shadow-lg sm:p-8">
<div class="mb-8 space-y-3 text-center">
<div class="mx-auto inline-flex items-center justify-center">
@@ -87,7 +86,7 @@ async function submit() {
<span class="text-highlighted">Pic</span><span class="text-primary">Host</span>
</h1>
<p class="text-sm text-muted">
个人轻量图床
{{ t('app.tagline') }}
</p>
</div>
</div>
@@ -102,21 +101,17 @@ async function submit() {
for="admin-secret"
class="block text-sm font-medium text-default"
>
管理密钥
{{ t('auth.adminSecret') }}
</label>
<UInput
<PasswordInput
id="admin-secret"
v-model="secret"
type="password"
placeholder="输入 ADMIN_SECRET"
:placeholder="t('auth.adminSecretPlaceholder')"
autocomplete="current-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
@keyup.enter="submit"
/>
<p class="text-xs leading-relaxed text-muted">
遗留部署:使用密钥登录后将引导创建账号
{{ t('auth.legacyHint') }}
</p>
</div>
</template>
@@ -127,12 +122,12 @@ async function submit() {
for="login-username"
class="block text-sm font-medium text-default"
>
用户名
{{ t('auth.username') }}
</label>
<UInput
id="login-username"
v-model="username"
placeholder="用户名"
:placeholder="t('auth.username')"
autocomplete="username"
size="lg"
class="w-full"
@@ -145,17 +140,13 @@ async function submit() {
for="login-password"
class="block text-sm font-medium text-default"
>
密码
{{ t('auth.password') }}
</label>
<UInput
<PasswordInput
id="login-password"
v-model="password"
type="password"
placeholder="密码"
:placeholder="t('auth.password')"
autocomplete="current-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
@keyup.enter="submit"
/>
</div>
@@ -163,7 +154,7 @@ async function submit() {
<UButton
type="submit"
label="登录"
:label="t('auth.login')"
icon="i-lucide-log-in"
size="lg"
block
@@ -176,18 +167,18 @@ async function submit() {
v-if="allowRegistration"
class="text-center text-sm text-muted"
>
没有账号?
{{ t('auth.noAccount') }}
<NuxtLink
to="/register"
class="text-primary hover:underline"
>
注册
{{ t('auth.register') }}
</NuxtLink>
</p>
</form>
<p class="mt-6 text-center text-xs leading-relaxed text-dimmed">
未登录时无法访问上传和管理功能
{{ t('auth.loginFooter') }}
</p>
</div>
</div>
+107 -116
View File
@@ -4,59 +4,27 @@ import logoLight from '~/assets/image/logo-light.png'
import logoDark from '~/assets/image/logo-dark.png'
const route = useRoute()
const colorMode = useColorMode()
const { logout, user, isAdmin } = useAuth()
const { t } = useI18n()
const mobileNavOpen = ref(false)
const mobileUserOpen = ref(false)
const navItems = computed(() => {
const items = [
{ label: 'API', to: '/api', icon: 'i-lucide-code-2' },
{ label: '统计', to: '/stats', icon: 'i-lucide-chart-column' }
{ label: t('nav.api'), to: '/api', icon: 'i-lucide-code-2' },
{ label: t('nav.stats'), to: '/stats', icon: 'i-lucide-chart-column' }
]
if (isAdmin.value) {
items.push({ label: '设置', to: '/settings', icon: 'i-lucide-settings' })
items.push({ label: t('nav.settings'), to: '/settings', icon: 'i-lucide-settings' })
}
return items
})
const themeIcon = computed(() => {
if (colorMode.preference === 'system') return 'i-lucide-monitor'
return colorMode.preference === 'dark' ? 'i-lucide-moon' : 'i-lucide-sun'
})
const themeItems = computed<DropdownMenuItem[][]>(() => [[
{
label: '浅色',
icon: 'i-lucide-sun',
type: 'checkbox',
checked: colorMode.preference === 'light',
onUpdateChecked(checked: boolean) {
if (checked) colorMode.preference = 'light'
}
},
{
label: '深色',
icon: 'i-lucide-moon',
type: 'checkbox',
checked: colorMode.preference === 'dark',
onUpdateChecked(checked: boolean) {
if (checked) colorMode.preference = 'dark'
}
},
{
label: '跟随系统',
icon: 'i-lucide-monitor',
type: 'checkbox',
checked: colorMode.preference === 'system',
onUpdateChecked(checked: boolean) {
if (checked) colorMode.preference = 'system'
}
}
]])
const userMenuItems = computed<DropdownMenuItem[][]>(() => {
const accountMenuItems = computed<DropdownMenuItem[]>(() => {
const items: DropdownMenuItem[] = [
{
label: '修改密码',
label: t('nav.changePassword'),
icon: 'i-lucide-key-round',
to: '/account/password'
}
@@ -64,27 +32,39 @@ const userMenuItems = computed<DropdownMenuItem[][]>(() => {
if (isAdmin.value) {
items.push({
label: '系统设置',
label: t('nav.systemSettings'),
icon: 'i-lucide-settings',
to: '/settings'
})
}
items.push({
label: '退出登录',
label: t('nav.logout'),
icon: 'i-lucide-log-out',
onSelect() {
void handleLogout()
}
})
return [items]
return items
})
const desktopUserMenuItems = computed<DropdownMenuItem[][]>(() => [
accountMenuItems.value
])
function isNavActive(to: string) {
return route.path.startsWith(to)
}
watch(mobileNavOpen, (open) => {
if (open) mobileUserOpen.value = false
})
watch(mobileUserOpen, (open) => {
if (open) mobileNavOpen.value = false
})
async function handleLogout() {
await logout()
}
@@ -93,83 +73,94 @@ async function handleLogout() {
<template>
<div class="flex min-h-screen flex-col">
<header class="sticky top-0 z-40 border-b border-default bg-default/80 backdrop-blur">
<div class="mx-auto flex max-w-7xl flex-col gap-3 px-4 py-2.5 sm:flex-row sm:items-center sm:justify-between sm:px-6">
<NuxtLink
to="/"
title="返回上传"
class="group flex shrink-0 items-center gap-2.5 transition-opacity hover:opacity-90 sm:gap-3"
>
<img
:src="logoLight"
alt="PicHost"
class="h-10 w-auto shrink-0 object-contain sm:h-11 dark:hidden"
decoding="async"
draggable="false"
<div class="mx-auto max-w-7xl px-4 py-2.5 sm:px-6">
<div class="flex items-center justify-between gap-3">
<NuxtLink
to="/"
:title="t('nav.backToUpload')"
class="group flex min-w-0 shrink items-center gap-2.5 transition-opacity hover:opacity-90 sm:gap-3"
>
<img
:src="logoDark"
alt="PicHost"
class="hidden h-10 w-auto shrink-0 object-contain sm:h-11 dark:block"
decoding="async"
draggable="false"
>
<div class="min-w-0 leading-tight">
<p class="text-[15px] font-bold tracking-tight sm:text-base">
<span class="text-highlighted">Pic</span><span class="text-primary">Host</span>
</p>
<p class="mt-0.5 text-[11px] text-muted sm:text-xs">
个人轻量图床
</p>
</div>
</NuxtLink>
<div class="flex flex-wrap items-center justify-end gap-1 sm:gap-2">
<nav class="flex flex-wrap items-center gap-1">
<UButton
v-for="item in navItems"
:key="item.to"
:to="item.to"
size="sm"
:variant="isNavActive(item.to) ? 'soft' : 'ghost'"
:color="isNavActive(item.to) ? 'primary' : 'neutral'"
:icon="item.icon"
:label="item.label"
/>
</nav>
<div class="mx-1 hidden h-5 w-px bg-muted sm:block" />
<img
:src="logoLight"
alt="PicHost"
class="h-9 w-auto shrink-0 object-contain sm:h-11 dark:hidden"
decoding="async"
draggable="false"
>
<img
:src="logoDark"
alt="PicHost"
class="hidden h-9 w-auto shrink-0 object-contain sm:h-11 dark:block"
decoding="async"
draggable="false"
>
<div class="min-w-0 leading-tight">
<p class="text-[15px] font-bold tracking-tight sm:text-base">
<span class="text-highlighted">Pic</span><span class="text-primary">Host</span>
</p>
<p class="mt-0.5 hidden text-[11px] text-muted min-[380px]:block sm:text-xs">
{{ t('app.tagline') }}
</p>
</div>
</NuxtLink>
<ClientOnly>
<UDropdownMenu
v-if="user"
:items="userMenuItems"
>
<UButton
variant="ghost"
color="neutral"
size="sm"
class="max-w-[10rem] gap-1.5"
>
<UIcon
name="i-lucide-user"
class="size-4 shrink-0"
<div class="flex shrink-0 items-center gap-0.5 sm:gap-1">
<nav class="hidden items-center gap-1 sm:flex">
<UButton
v-for="item in navItems"
:key="item.to"
:to="item.to"
size="sm"
:variant="isNavActive(item.to) ? 'soft' : 'ghost'"
:color="isNavActive(item.to) ? 'primary' : 'neutral'"
:icon="item.icon"
:label="item.label"
/>
<span class="truncate">{{ user.username }}</span>
<UIcon
name="i-lucide-chevron-down"
class="size-3.5 shrink-0 opacity-60"
</nav>
<div class="mx-1 hidden h-5 w-px bg-muted sm:block" />
<div class="hidden items-center gap-0.5 sm:flex">
<LocaleMenu />
<ThemeMenu />
</div>
<div class="flex items-center gap-0.5 sm:hidden">
<MobileUserMenu
v-if="user"
v-model:open="mobileUserOpen"
/>
</UButton>
</UDropdownMenu>
<UDropdownMenu :items="themeItems">
<UButton
:icon="themeIcon"
variant="ghost"
color="neutral"
size="sm"
aria-label="切换主题"
/>
</UDropdownMenu>
<MobileNavMenu
v-model:open="mobileNavOpen"
:items="navItems"
/>
</div>
<div class="hidden sm:block">
<UDropdownMenu
v-if="user"
:items="desktopUserMenuItems"
>
<UButton
variant="ghost"
color="neutral"
size="sm"
class="max-w-[10rem] gap-1.5"
>
<UIcon
name="i-lucide-user"
class="size-4 shrink-0"
/>
<span class="truncate">{{ user.username }}</span>
<UIcon
name="i-lucide-chevron-down"
class="size-3.5 shrink-0 opacity-60"
/>
</UButton>
</UDropdownMenu>
</div>
</div>
<template #fallback>
<div class="size-8" />
</template>
+6
View File
@@ -0,0 +1,6 @@
<template>
<div class="flex items-center gap-1">
<LocaleMenu />
<ThemeMenu />
</div>
</template>
+3 -2
View File
@@ -13,6 +13,7 @@ const emit = defineEmits<{
}>()
const toast = useToast()
const { t } = useI18n()
const copying = ref(false)
function copyWithFallback(text: string): boolean {
@@ -40,7 +41,7 @@ function copyWithFallback(text: string): boolean {
function notifySuccess() {
toast.add({
title: props.successTitle ?? (props.label ? `已复制 ${props.label}` : '已复制到剪贴板'),
title: props.successTitle ?? (props.label ? t('copy.copiedLabel', { label: props.label }) : t('copy.copied')),
color: 'success'
})
emit('copied')
@@ -64,7 +65,7 @@ async function copy() {
if (copyWithFallback(props.value)) {
notifySuccess()
} else {
toast.add({ title: '复制失败,请手动选中链接复制', color: 'error' })
toast.add({ title: t('copy.failedManual'), color: 'error' })
}
} finally {
copying.value = false
+9 -5
View File
@@ -1,5 +1,5 @@
<script setup lang="ts">
defineProps<{
const props = defineProps<{
open: boolean
count: number
loading?: boolean
@@ -10,6 +10,10 @@ const emit = defineEmits<{
'confirm': []
}>()
const { t } = useI18n()
const description = computed(() => t('delete.confirmDesc', { count: props.count }))
function close() {
emit('update:open', false)
}
@@ -22,20 +26,20 @@ function confirm() {
<template>
<UModal
:open="open"
title="确认删除"
:description="`确定要删除选中的 ${count} 张图片吗?此操作不可恢复。`"
:title="t('delete.confirmTitle')"
:description="description"
@update:open="emit('update:open', $event)"
>
<template #footer>
<div class="flex justify-end gap-2">
<UButton
label="取消"
:label="t('common.cancel')"
color="neutral"
variant="outline"
@click="close"
/>
<UButton
label="确认删除"
:label="t('delete.confirm')"
color="error"
:loading="loading"
@click="confirm"
+45 -15
View File
@@ -9,9 +9,11 @@ const props = withDefaults(defineProps<{
deleting?: boolean
selectable?: boolean
showKey?: boolean
compact?: boolean
}>(), {
selectable: true,
showKey: true
showKey: true,
compact: false
})
const emit = defineEmits<{
@@ -20,18 +22,19 @@ const emit = defineEmits<{
}>()
const { formatFileSize } = useFileSize()
const { t, locale } = useI18n()
const imageError = ref(false)
const copyFormat = ref<CopyFormat>('url')
const copyFormatItems = [
{ label: '直链', value: 'url' as const },
{ label: 'Markdown', value: 'markdown' as const },
{ label: 'HTML', value: 'html' as const }
]
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 uploadedLabel = computed(() => {
try {
return new Date(props.image.uploadedAt).toLocaleString('zh-CN', { hour12: false })
return new Date(props.image.uploadedAt).toLocaleString(locale.value, { hour12: false })
} catch {
return props.image.uploadedAt
}
@@ -51,11 +54,11 @@ const previewValue = computed(() => {
const copySuccessTitle = computed(() => {
switch (copyFormat.value) {
case 'markdown':
return '已复制 Markdown'
return t('copy.copiedMarkdown')
case 'html':
return '已复制 HTML'
return t('copy.copiedHtml')
default:
return '已复制直链'
return t('copy.copiedUrl')
}
})
@@ -79,7 +82,7 @@ function toggleSelected(value: boolean | 'indeterminate') {
v-else
class="flex h-full items-center justify-center text-sm text-muted"
>
预览失败
{{ t('image.previewFailed') }}
</div>
<div
v-if="selectable"
@@ -96,7 +99,7 @@ function toggleSelected(value: boolean | 'indeterminate') {
color="error"
variant="solid"
icon="i-lucide-trash-2"
aria-label="删除"
:aria-label="t('common.delete')"
:loading="deleting"
@click="emit('delete')"
/>
@@ -107,7 +110,7 @@ function toggleSelected(value: boolean | 'indeterminate') {
>
<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"
:title="`上传者:${image.owner.username}`"
:title="t('image.uploader', { name: image.owner.username })"
>
<UIcon
name="i-lucide-user"
@@ -118,7 +121,34 @@ function toggleSelected(value: boolean | 'indeterminate') {
</div>
</div>
<div class="flex flex-1 flex-col gap-2 p-3">
<div
v-if="compact"
class="flex items-center gap-1.5 p-2 sm:hidden"
>
<div class="min-w-0 flex-1">
<p
class="truncate text-xs font-medium"
:title="image.originalName"
>
{{ image.originalName }}
</p>
<p class="text-[11px] text-muted">
{{ formatFileSize(image.size) }}
</p>
</div>
<CopyButton
icon="i-lucide-copy"
icon-only
:label="t('common.copy')"
:value="image.url"
:success-title="t('copy.copiedUrl')"
/>
</div>
<div
class="flex flex-1 flex-col gap-2 p-3"
:class="{ 'hidden sm:flex': compact }"
>
<p
class="truncate text-sm font-medium"
:title="image.originalName"
@@ -151,7 +181,7 @@ function toggleSelected(value: boolean | 'indeterminate') {
/>
<CopyButton
icon="i-lucide-copy"
label="复制"
:label="t('common.copy')"
:value="previewValue"
:success-title="copySuccessTitle"
/>
+12 -3
View File
@@ -8,10 +8,13 @@ const props = withDefaults(defineProps<{
selectable?: boolean
showKey?: boolean
emptyText?: string
dense?: boolean
compact?: boolean
}>(), {
selectable: true,
showKey: true,
emptyText: '暂无图片'
dense: false,
compact: false
})
const emit = defineEmits<{
@@ -19,6 +22,10 @@ const emit = defineEmits<{
'delete': [key: string]
}>()
const { t } = useI18n()
const displayEmptyText = computed(() => props.emptyText ?? t('image.empty'))
function updateSelection(key: string, selected: boolean) {
const next = new Set(props.selectedKeys)
if (selected) next.add(key)
@@ -30,7 +37,8 @@ function updateSelection(key: string, selected: boolean) {
<template>
<div
v-if="items.length"
class="grid grid-cols-1 items-start gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
class="grid items-start sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"
:class="dense ? 'grid-cols-2 gap-3' : 'grid-cols-1 gap-4'"
>
<ImageCard
v-for="image in items"
@@ -40,6 +48,7 @@ function updateSelection(key: string, selected: boolean) {
:deleting="deletingKeys.has(image.key)"
:selectable="selectable"
:show-key="showKey"
:compact="compact"
@update:selected="updateSelection(image.key, $event)"
@delete="emit('delete', image.key)"
/>
@@ -48,6 +57,6 @@ function updateSelection(key: string, selected: boolean) {
v-else
class="rounded-xl border border-dashed border-default py-16 text-center text-sm text-muted"
>
{{ emptyText }}
{{ displayEmptyText }}
</div>
</template>
+56 -52
View File
@@ -1,4 +1,7 @@
<script setup lang="ts">
import uploadCardBg from '~/assets/image/upload-card-bg.webp'
import uploadCardHero from '~/assets/image/upload-card-hero.webp'
const props = defineProps<{
disabled?: boolean
}>()
@@ -10,12 +13,10 @@ const emit = defineEmits<{
const fileInput = ref<HTMLInputElement | null>(null)
const dragging = ref(false)
const hovering = ref(false)
const { t } = useI18n()
const { bindPaste } = useClipboardImage(ref(null))
const isActive = computed(() => dragging.value || hovering.value)
bindPaste((files) => {
if (!props.disabled) emit('upload', files)
})
@@ -51,31 +52,33 @@ function onDragLeave() {
dragging.value = false
}
function onMouseEnter() {
if (!props.disabled) hovering.value = true
}
function onMouseLeave() {
hovering.value = false
}
function openSettings() {
function openSettings(event: Event) {
event.stopPropagation()
if (props.disabled) return
emit('open-settings')
}
function onKeydown(event: KeyboardEvent) {
if (props.disabled) return
if (event.key === 'Enter' || event.key === ' ') {
event.preventDefault()
openFilePicker()
}
}
</script>
<template>
<div
class="upload-card-surface group/upload relative text-center transition-all duration-300 ease-out"
:class="isActive
? 'scale-[1.01] border-primary bg-primary/5 shadow-md shadow-primary/10'
: 'hover:border-primary/50 hover:bg-primary/[0.04] hover:shadow-sm'"
role="button"
tabindex="0"
class="upload-card-surface group/upload relative cursor-pointer overflow-hidden text-center outline-none focus-visible:ring-2 focus-visible:ring-primary/40"
:class="{ 'upload-card-surface--active': dragging }"
:aria-disabled="disabled"
@click="openFilePicker"
@keydown="onKeydown"
@drop="onDrop"
@dragover="onDragOver"
@dragleave="onDragLeave"
@mouseenter="onMouseEnter"
@mouseleave="onMouseLeave"
>
<input
ref="fileInput"
@@ -87,11 +90,20 @@ function openSettings() {
@change="onFileChange"
>
<div class="absolute top-3 right-3 z-10">
<img
:src="uploadCardBg"
alt=""
aria-hidden="true"
class="pointer-events-none absolute inset-0 size-full object-cover opacity-100 dark:opacity-[0.12]"
decoding="async"
draggable="false"
>
<div class="absolute top-3 right-3 z-20">
<button
type="button"
class="upload-settings-btn inline-flex size-8 items-center justify-center rounded-md text-muted transition-colors hover:bg-elevated hover:text-highlighted disabled:pointer-events-none disabled:opacity-40"
aria-label="上传设置"
class="upload-settings-btn inline-flex size-8 items-center justify-center rounded-md bg-default/70 text-muted backdrop-blur-sm transition-colors hover:bg-elevated hover:text-highlighted disabled:pointer-events-none disabled:opacity-40"
:aria-label="t('upload.settings')"
:disabled="disabled"
@click="openSettings"
>
@@ -102,39 +114,31 @@ function openSettings() {
</button>
</div>
<div class="mx-auto max-w-lg space-y-4">
<div
class="mx-auto flex size-16 items-center justify-center rounded-2xl bg-primary/10 transition-transform duration-300 ease-out"
:class="isActive ? 'scale-110' : 'group-hover/upload:scale-105'"
>
<UIcon
name="i-lucide-cloud-upload"
class="size-8 text-primary transition-transform duration-300"
:class="isActive ? '-translate-y-0.5' : ''"
/>
<div class="relative z-10 mx-auto flex max-w-lg flex-col items-center">
<div class="flex flex-col items-center">
<img
:src="uploadCardHero"
alt=""
aria-hidden="true"
class="h-24 w-auto -mb-3 select-none transition-transform duration-200 ease-[cubic-bezier(0.4,0,0.2,1)] sm:-mb-4 sm:h-28 md:h-32"
:class="dragging ? 'scale-105' : 'group-hover/upload:scale-[1.02]'"
decoding="async"
draggable="false"
>
<div class="space-y-2">
<p class="text-xl font-semibold tracking-tight text-highlighted sm:text-2xl">
{{ t('upload.title') }}
</p>
<p class="text-sm text-muted sm:text-base">
{{ t('upload.hint', { ctrl: 'Ctrl', v: 'V' }) }}
</p>
</div>
</div>
<div class="space-y-2">
<p class="text-xl font-semibold tracking-tight">
拖拽图片到此处上传
</p>
<p class="text-sm text-muted">
或点击选择文件,按
<kbd class="mx-1 rounded border border-default bg-muted/50 px-1.5 py-0.5 font-mono text-xs">Ctrl</kbd>
+
<kbd class="mx-1 rounded border border-default bg-muted/50 px-1.5 py-0.5 font-mono text-xs">V</kbd>
粘贴图片
</p>
</div>
<p class="text-xs text-dimmed">
支持 JPEG / PNG / WebP / GIF / SVG / ICO,单张最大 10 MB,每次最多 10 张
<p class="mt-4 max-w-md text-xs leading-relaxed text-dimmed sm:text-sm">
{{ t('upload.formats') }}
</p>
<UButton
label="选择图片"
icon="i-lucide-upload"
size="lg"
:disabled="disabled"
@click="openFilePicker"
/>
</div>
</div>
</template>
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
const { localeMenuItems } = useAppearanceMenus()
const { t } = useI18n()
</script>
<template>
<UDropdownMenu :items="localeMenuItems">
<UButton
icon="i-lucide-languages"
variant="ghost"
color="neutral"
size="sm"
:aria-label="t('locale.switch')"
/>
</UDropdownMenu>
</template>
+85
View File
@@ -0,0 +1,85 @@
<script setup lang="ts">
defineProps<{
items: Array<{ label: string, to: string, icon: string }>
}>()
const open = defineModel<boolean>('open', { default: false })
const route = useRoute()
const { t } = useI18n()
const menuRef = ref<HTMLElement | null>(null)
function isActive(to: string) {
return route.path.startsWith(to)
}
function onDocumentClick(event: MouseEvent) {
if (!open.value || !menuRef.value) return
const target = event.target
if (target instanceof Node && !menuRef.value.contains(target)) {
open.value = false
}
}
watch(() => route.path, () => {
open.value = false
})
watch(open, (isOpen) => {
if (isOpen) {
document.addEventListener('click', onDocumentClick, true)
} else {
document.removeEventListener('click', onDocumentClick, true)
}
})
onUnmounted(() => {
document.removeEventListener('click', onDocumentClick, true)
})
function toggleOpen() {
open.value = !open.value
}
</script>
<template>
<div
ref="menuRef"
class="relative sm:hidden"
>
<UButton
variant="outline"
color="neutral"
size="sm"
icon="i-lucide-menu"
:aria-label="t('nav.menu')"
:aria-expanded="open"
@click.stop="toggleOpen"
/>
<div
v-show="open"
class="absolute top-full right-0 z-50 mt-2 w-52 rounded-xl border border-default bg-default p-1.5 shadow-lg"
@click.stop
>
<nav class="space-y-0.5">
<NuxtLink
v-for="item in items"
:key="item.to"
:to="item.to"
class="flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors"
:class="isActive(item.to)
? 'bg-primary/10 text-primary'
: 'text-highlighted hover:bg-elevated'"
@click="open = false"
>
<UIcon
:name="item.icon"
class="size-4 shrink-0 opacity-70"
/>
{{ item.label }}
</NuxtLink>
</nav>
</div>
</div>
</template>
+197
View File
@@ -0,0 +1,197 @@
<script setup lang="ts">
const open = defineModel<boolean>('open', { default: false })
const { logout, isAdmin } = useAuth()
const { t, locale } = useI18n()
const colorMode = useColorMode()
const {
localeOptions,
themeOptions,
setLocalePreference,
setThemePreference
} = useAppearanceMenus()
const menuRef = ref<HTMLElement | null>(null)
async function handleLogout() {
open.value = false
await logout()
}
function onDocumentClick(event: MouseEvent) {
if (!open.value || !menuRef.value) return
const target = event.target
if (target instanceof Node && !menuRef.value.contains(target)) {
open.value = false
}
}
watch(open, (isOpen) => {
if (isOpen) {
document.addEventListener('click', onDocumentClick, true)
} else {
document.removeEventListener('click', onDocumentClick, true)
}
})
onUnmounted(() => {
document.removeEventListener('click', onDocumentClick, true)
})
function toggleOpen() {
open.value = !open.value
}
</script>
<template>
<div
ref="menuRef"
class="relative sm:hidden"
>
<UButton
variant="ghost"
color="neutral"
size="sm"
icon="i-lucide-user"
:aria-label="t('nav.account')"
:aria-expanded="open"
@click.stop="toggleOpen"
/>
<div
v-show="open"
class="absolute top-full right-0 z-50 mt-2 w-[min(20rem,calc(100vw-2rem))] rounded-xl border border-default bg-default p-4 shadow-lg"
@click.stop
>
<section class="space-y-2">
<h3 class="flex items-center gap-2 px-1 text-sm font-medium text-muted">
<UIcon
name="i-lucide-globe"
class="size-4"
/>
{{ t('nav.language') }}
</h3>
<div class="space-y-2">
<button
v-for="item in localeOptions"
:key="item.code"
type="button"
class="flex w-full items-center justify-between rounded-lg border px-3.5 py-2.5 text-sm transition-colors"
:class="locale === item.code
? 'border-primary text-highlighted'
: 'border-default text-highlighted hover:bg-elevated'"
@click="setLocalePreference(item.code)"
>
<span>{{ item.label }}</span>
<UIcon
v-if="locale === item.code"
name="i-lucide-check"
class="size-4 text-primary"
/>
</button>
</div>
</section>
<section class="mt-5 space-y-2">
<h3 class="flex items-center gap-2 px-1 text-sm font-medium text-muted">
<UIcon
name="i-lucide-sun"
class="size-4"
/>
{{ t('nav.appearance') }}
</h3>
<div class="space-y-2">
<button
v-for="item in themeOptions"
:key="item.value"
type="button"
class="flex w-full items-center justify-between rounded-lg border px-3.5 py-2.5 text-sm transition-colors"
:class="colorMode.preference === item.value
? 'border-primary text-highlighted'
: 'border-default text-highlighted hover:bg-elevated'"
@click="setThemePreference(item.value)"
>
<span class="flex items-center gap-2.5">
<UIcon
:name="item.icon"
class="size-4 opacity-70"
/>
{{ item.label }}
</span>
<UIcon
v-if="colorMode.preference === item.value"
name="i-lucide-check"
class="size-4 text-primary"
/>
</button>
</div>
</section>
<section class="mt-5 space-y-2">
<h3 class="flex items-center gap-2 px-1 text-sm font-medium text-muted">
<UIcon
name="i-lucide-user"
class="size-4"
/>
{{ t('nav.account') }}
</h3>
<div class="space-y-2">
<NuxtLink
to="/account/password"
class="flex items-center justify-between rounded-lg border border-default px-3.5 py-2.5 text-sm text-highlighted transition-colors hover:bg-elevated"
@click="open = false"
>
<span class="flex items-center gap-2.5">
<UIcon
name="i-lucide-lock"
class="size-4 opacity-70"
/>
{{ t('nav.changePassword') }}
</span>
<UIcon
name="i-lucide-chevron-right"
class="size-4 text-muted"
/>
</NuxtLink>
<NuxtLink
v-if="isAdmin"
to="/settings"
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-settings"
class="size-4 opacity-70"
/>
{{ t('nav.systemSettings') }}
</span>
<UIcon
name="i-lucide-chevron-right"
class="size-4 text-muted"
/>
</NuxtLink>
<button
type="button"
class="flex w-full items-center justify-between rounded-lg border border-default px-3.5 py-2.5 text-sm text-error transition-colors hover:bg-error/5"
@click="handleLogout"
>
<span class="flex items-center gap-2.5">
<UIcon
name="i-lucide-log-out"
class="size-4"
/>
{{ t('nav.logout') }}
</span>
<UIcon
name="i-lucide-chevron-right"
class="size-4 opacity-60"
/>
</button>
</div>
</section>
</div>
</div>
</template>
+9 -7
View File
@@ -11,7 +11,9 @@ const emit = defineEmits<{
'update:page': [page: number]
}>()
const unitLabel = computed(() => props.unit ?? '条')
const { t } = useI18n()
const unitLabel = computed(() => props.unit ?? t('common.itemsUnit'))
function goTo(target: number) {
if (target < 1 || target > props.totalPages || target === props.page || props.loading) {
@@ -30,13 +32,13 @@ function goTo(target: number) {
v-if="totalPages > 1"
class="text-sm text-muted"
>
第 {{ page }} / {{ totalPages }} 页 · 共 {{ total }} {{ unitLabel }}
{{ t('pagination.pageOf', { page, totalPages, total, unit: unitLabel }) }}
</p>
<p
v-else
class="text-sm text-muted"
>
共 {{ total }} {{ unitLabel }}
{{ t('pagination.totalOnly', { total, unit: unitLabel }) }}
</p>
<div
@@ -47,7 +49,7 @@ function goTo(target: number) {
icon="i-lucide-chevrons-left"
variant="outline"
size="sm"
aria-label="第一页"
:aria-label="t('pagination.first')"
:disabled="page <= 1 || loading"
@click="goTo(1)"
/>
@@ -55,7 +57,7 @@ function goTo(target: number) {
icon="i-lucide-chevron-left"
variant="outline"
size="sm"
aria-label="上一页"
:aria-label="t('pagination.prev')"
:disabled="page <= 1 || loading"
@click="goTo(page - 1)"
/>
@@ -63,7 +65,7 @@ function goTo(target: number) {
icon="i-lucide-chevron-right"
variant="outline"
size="sm"
aria-label="下一页"
:aria-label="t('pagination.next')"
:disabled="page >= totalPages || loading"
@click="goTo(page + 1)"
/>
@@ -71,7 +73,7 @@ function goTo(target: number) {
icon="i-lucide-chevrons-right"
variant="outline"
size="sm"
aria-label="最后一页"
:aria-label="t('pagination.last')"
:disabled="page >= totalPages || loading"
@click="goTo(totalPages)"
/>
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
defineOptions({
inheritAttrs: false
})
const model = defineModel<string>({ default: '' })
defineProps<{
id?: string
placeholder?: string
autocomplete?: string
}>()
const show = ref(false)
const { t } = useI18n()
</script>
<template>
<UInput
:id="id"
v-model="model"
:type="show ? 'text' : 'password'"
:placeholder="placeholder"
:autocomplete="autocomplete"
size="lg"
class="w-full"
:ui="{ root: 'w-full', trailing: 'pe-1' }"
v-bind="$attrs"
>
<template #trailing>
<UButton
color="neutral"
variant="link"
size="sm"
:icon="show ? 'i-lucide-eye-off' : 'i-lucide-eye'"
:aria-label="show ? t('auth.hidePassword') : t('auth.showPassword')"
:aria-pressed="show"
:aria-controls="id"
type="button"
@click="() => { show = !show }"
/>
</template>
</UInput>
</template>
<style scoped>
:deep(::-ms-reveal) {
display: none;
}
</style>
+12 -10
View File
@@ -5,15 +5,17 @@ const props = defineProps<{
password: string
}>()
const { t } = useI18n()
const analysis = computed(() => analyzePassword(props.password))
const show = computed(() => props.password.length > 0)
const labelColor = computed(() => {
switch (analysis.value.label) {
case '强':
case 'strong':
return 'text-success'
case '中':
case 'medium':
return 'text-warning'
default:
return 'text-error'
@@ -22,9 +24,9 @@ const labelColor = computed(() => {
const barColor = computed(() => {
switch (analysis.value.label) {
case '强':
case 'strong':
return 'bg-success'
case '中':
case 'medium':
return 'bg-warning'
default:
return 'bg-error/80'
@@ -32,10 +34,10 @@ const barColor = computed(() => {
})
const rules = computed(() => [
{ key: 'minLength', label: `至少 ${PASSWORD_MIN_LENGTH} 个字符` },
{ key: 'mixedCase', label: '包含大小写字母' },
{ key: 'hasNumber', label: '包含数字' },
{ key: 'hasSpecial', label: '包含特殊字符' }
{ key: 'minLength', label: t('password.ruleMinLength', { n: PASSWORD_MIN_LENGTH }) },
{ key: 'mixedCase', label: t('password.ruleMixedCase') },
{ key: 'hasNumber', label: t('password.ruleNumber') },
{ key: 'hasSpecial', label: t('password.ruleSpecial') }
] as const)
</script>
@@ -45,12 +47,12 @@ const rules = computed(() => [
class="space-y-3 rounded-lg border border-default bg-muted/20 px-3 py-3"
>
<div class="flex items-center justify-between text-sm">
<span class="text-muted">密码强度</span>
<span class="text-muted">{{ t('password.strength') }}</span>
<span
class="font-medium"
:class="labelColor"
>
{{ analysis.label }}
{{ t(`password.${analysis.label}`) }}
</span>
</div>
+16
View File
@@ -0,0 +1,16 @@
<script setup lang="ts">
const { themeIcon, themeMenuItems } = useAppearanceMenus()
const { t } = useI18n()
</script>
<template>
<UDropdownMenu :items="themeMenuItems">
<UButton
:icon="themeIcon"
variant="ghost"
color="neutral"
size="sm"
:aria-label="t('theme.switch')"
/>
</UDropdownMenu>
</template>
+26 -24
View File
@@ -20,6 +20,8 @@ const {
loadPreferences
} = useUploadPreferences()
const { t } = useI18n()
const {
userSettings,
enabled: userAutoDeleteEnabled,
@@ -27,16 +29,16 @@ const {
load: loadUserSettings
} = useUserAutoDeleteSettings()
const copyFormatItems = [
{ label: '直链', value: 'url' as const },
{ label: 'Markdown', value: 'markdown' as const },
{ label: 'HTML', value: 'html' as const }
]
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 '高质量'
if (clientWebpQuality.value >= 60) return '中等质量'
return '有损压缩'
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') {
@@ -73,22 +75,22 @@ onMounted(() => {
/>
<div class="min-w-0">
<h2 class="text-base font-semibold">
上传偏好
{{ t('preferences.title') }}
</h2>
<p class="mt-0.5 text-xs text-muted">
浏览器本地与账号设置,仅影响您的上传体验
{{ t('preferences.subtitle') }}
</p>
</div>
</div>
<UButton
v-if="!embedded"
label="返回"
:label="t('common.back')"
icon="i-lucide-arrow-left"
variant="ghost"
color="neutral"
size="sm"
class="shrink-0"
aria-label="返回上传"
:aria-label="t('preferences.back')"
@click="emit('back')"
/>
</div>
@@ -100,7 +102,7 @@ onMounted(() => {
<div class="grid gap-5 sm:grid-cols-3 sm:gap-6">
<div class="space-y-4">
<h3 class="text-sm font-semibold">
图片处理
{{ t('preferences.processing') }}
</h3>
<label class="flex cursor-pointer items-start gap-2.5">
@@ -109,9 +111,9 @@ onMounted(() => {
class="mt-0.5"
/>
<span>
<span class="block text-sm">客户端预压缩</span>
<span class="block text-sm">{{ t('preferences.clientCompress') }}</span>
<span class="mt-1 block text-xs leading-relaxed text-muted">
上传前在浏览器端压缩(服务端仍会转 WebP)
{{ t('preferences.clientCompressHint') }}
</span>
</span>
</label>
@@ -129,7 +131,7 @@ onMounted(() => {
<span
class="flex flex-wrap items-center gap-x-1.5 gap-y-1 text-sm"
>
<span>自动删除超过</span>
<span>{{ t('preferences.autoDeletePrefix') }}</span>
<UInput
v-model.number="userAutoDeleteDaysDraft"
type="number"
@@ -143,10 +145,10 @@ onMounted(() => {
: 'pointer-events-none opacity-40'
"
/>
<span>天的图片</span>
<span>{{ t('preferences.autoDeleteSuffix') }}</span>
</span>
<span class="mt-1 block text-xs leading-relaxed text-muted">
仅清理开启后上传的图片,不影响此前已存的图片
{{ t('preferences.autoDeleteHint') }}
</span>
</span>
</label>
@@ -164,15 +166,15 @@ onMounted(() => {
<div class="space-y-4">
<h3 class="text-sm font-semibold">
WebP 压缩质量
{{ t('preferences.webpQuality') }}
</h3>
<p class="text-xs leading-relaxed text-muted">
客户端预压缩质量(1–100),需开启「客户端预压缩」
{{ t('preferences.webpQualityHint') }}
</p>
<div
class="flex items-center justify-between gap-2 text-sm text-muted"
>
<span>当前:{{ clientWebpQuality }}</span>
<span>{{ t('preferences.current', { n: clientWebpQuality }) }}</span>
<span>{{ clientQualityLevel }}</span>
</div>
<input
@@ -187,7 +189,7 @@ onMounted(() => {
<div class="space-y-4">
<h3 class="text-sm font-semibold">
便捷功能
{{ t('preferences.convenience') }}
</h3>
<label class="flex cursor-pointer items-start gap-2.5">
<UCheckbox
@@ -195,9 +197,9 @@ onMounted(() => {
class="mt-0.5"
/>
<span>
<span class="block text-sm">上传成功自动复制链接</span>
<span class="block text-sm">{{ t('preferences.autoCopy') }}</span>
<span class="mt-1 block text-xs leading-relaxed text-muted">
按所选格式复制到剪贴板
{{ t('preferences.autoCopyHint') }}
</span>
</span>
</label>
+17 -2
View File
@@ -4,6 +4,21 @@ import type { UploadProgressItem } from '~/types/image'
defineProps<{
items: UploadProgressItem[]
}>()
const { t } = useI18n()
function statusLabel(status: UploadProgressItem['status']) {
switch (status) {
case 'pending':
return t('upload.statusPending')
case 'uploading':
return t('upload.statusUploading')
case 'success':
return t('upload.statusSuccess')
default:
return t('upload.statusError')
}
}
</script>
<template>
@@ -12,7 +27,7 @@ defineProps<{
class="space-y-2 rounded-lg border border-default p-4"
>
<p class="text-sm font-medium text-muted">
上传进度
{{ t('upload.progress') }}
</p>
<div
v-for="item in items"
@@ -26,7 +41,7 @@ defineProps<{
variant="subtle"
size="xs"
>
{{ item.status === 'pending' ? '等待' : item.status === 'uploading' ? '上传中' : item.status === 'success' ? '成功' : '失败' }}
{{ statusLabel(item.status) }}
</UBadge>
</div>
<UProgress
+100
View File
@@ -0,0 +1,100 @@
import type { DropdownMenuItem } from '@nuxt/ui'
export function useAppearanceMenus() {
const colorMode = useColorMode()
const { locale, locales, setLocale, t } = useI18n()
const themeIcon = computed(() => {
if (colorMode.preference === 'system') return 'i-lucide-monitor'
return colorMode.preference === 'dark' ? 'i-lucide-moon' : 'i-lucide-sun'
})
const localeMenuItems = computed<DropdownMenuItem[][]>(() => [[
...locales.value.map(loc => ({
label: t(`locale.${loc.code}`),
icon: 'i-lucide-languages',
type: 'checkbox' as const,
checked: locale.value === loc.code,
onUpdateChecked(checked: boolean) {
if (checked && typeof loc.code === 'string') {
void setLocale(loc.code)
}
}
}))
]])
const themeMenuItems = computed<DropdownMenuItem[][]>(() => [[
{
label: t('theme.light'),
icon: 'i-lucide-sun',
type: 'checkbox',
checked: colorMode.preference === 'light',
onUpdateChecked(checked: boolean) {
if (checked) colorMode.preference = 'light'
}
},
{
label: t('theme.dark'),
icon: 'i-lucide-moon',
type: 'checkbox',
checked: colorMode.preference === 'dark',
onUpdateChecked(checked: boolean) {
if (checked) colorMode.preference = 'dark'
}
},
{
label: t('theme.system'),
icon: 'i-lucide-monitor',
type: 'checkbox',
checked: colorMode.preference === 'system',
onUpdateChecked(checked: boolean) {
if (checked) colorMode.preference = 'system'
}
}
]])
const themeOptions = computed(() => [
{
value: 'light' as const,
label: t('theme.light'),
icon: 'i-lucide-sun'
},
{
value: 'dark' as const,
label: t('theme.dark'),
icon: 'i-lucide-moon'
},
{
value: 'system' as const,
label: t('theme.system'),
icon: 'i-lucide-monitor'
}
])
const localeOptions = computed(() =>
locales.value.map(loc => ({
code: String(loc.code),
label: t(`locale.${loc.code}`)
}))
)
function setThemePreference(value: 'light' | 'dark' | 'system') {
colorMode.preference = value
}
async function setLocalePreference(code: string) {
if (code === 'zh-CN' || code === 'en') {
await setLocale(code)
}
}
return {
themeIcon,
localeMenuItems,
themeMenuItems,
localeOptions,
themeOptions,
setThemePreference,
setLocalePreference
}
}
+15 -12
View File
@@ -26,13 +26,15 @@ export function isUnauthorizedError(error: unknown): boolean {
export const AUTH_USERNAME_PATTERN = /^[a-zA-Z0-9_]{3,32}$/
export const AUTH_MIN_PASSWORD_LENGTH = 8
export function validateAuthInput(username: string, password: string): string | null {
export type AuthValidationErrorKey = 'invalidUsername' | 'invalidPassword'
export function validateAuthInput(username: string, password: string): AuthValidationErrorKey | null {
const trimmed = username.trim()
if (!AUTH_USERNAME_PATTERN.test(trimmed)) {
return '用户名需为 3–32 位字母、数字或下划线'
return 'invalidUsername'
}
if (password.length < AUTH_MIN_PASSWORD_LENGTH) {
return '密码至少 8 位'
return 'invalidPassword'
}
return null
}
@@ -65,6 +67,7 @@ export function getFetchErrorMessage(error: unknown, fallback: string): string {
export type AuthActionResult = { ok: true } | { ok: false, error: string }
export function useAuth() {
const { t } = useI18n()
const status = useState<AuthStatus>('auth-status', () => 'checking')
const user = useState<AuthUser | null>('auth-user', () => null)
const authStatus = useState<AuthStatusResponse | null>('auth-status-response', () => null)
@@ -131,7 +134,7 @@ export function useAuth() {
} catch (error: unknown) {
return {
ok: false,
error: getFetchErrorMessage(error, '登录失败,请检查用户名和密码')
error: getFetchErrorMessage(error, t('auth.loginFailed'))
}
}
}
@@ -142,7 +145,7 @@ export function useAuth() {
): Promise<AuthActionResult> {
const validationError = validateAuthInput(username, password)
if (validationError) {
return { ok: false, error: validationError }
return { ok: false, error: t(`auth.errors.${validationError}`) }
}
try {
@@ -161,7 +164,7 @@ export function useAuth() {
} catch (error: unknown) {
return {
ok: false,
error: getFetchErrorMessage(error, '注册失败,请检查输入')
error: getFetchErrorMessage(error, t('auth.registerFailed'))
}
}
}
@@ -173,7 +176,7 @@ export function useAuth() {
}): Promise<AuthActionResult> {
const validationError = validateAuthInput(input.username, input.password)
if (validationError) {
return { ok: false, error: validationError }
return { ok: false, error: t(`auth.errors.${validationError}`) }
}
try {
@@ -196,7 +199,7 @@ export function useAuth() {
} catch (error: unknown) {
return {
ok: false,
error: getFetchErrorMessage(error, '初始化失败,请检查输入')
error: getFetchErrorMessage(error, t('auth.setupFailed'))
}
}
}
@@ -208,7 +211,7 @@ export function useAuth() {
}): Promise<AuthActionResult> {
const validationError = validateAuthInput(input.username, input.password)
if (validationError) {
return { ok: false, error: validationError }
return { ok: false, error: t(`auth.errors.${validationError}`) }
}
try {
@@ -231,7 +234,7 @@ export function useAuth() {
} catch (error: unknown) {
return {
ok: false,
error: getFetchErrorMessage(error, '迁移失败,请检查输入')
error: getFetchErrorMessage(error, t('auth.migrateFailed'))
}
}
}
@@ -241,7 +244,7 @@ export function useAuth() {
newPassword: string
): Promise<AuthActionResult> {
if (newPassword.length < AUTH_MIN_PASSWORD_LENGTH) {
return { ok: false, error: '新密码至少 8 位' }
return { ok: false, error: t('password.tooShort') }
}
try {
@@ -254,7 +257,7 @@ export function useAuth() {
} catch (error: unknown) {
return {
ok: false,
error: getFetchErrorMessage(error, '修改密码失败')
error: getFetchErrorMessage(error, t('password.changeFailed'))
}
}
}
+7 -7
View File
@@ -6,6 +6,7 @@ import type {
const PAGE_SIZE = 12
export function useImageList() {
const { t } = useI18n()
const items = ref<ImageItem[]>([])
const page = ref(1)
const totalPages = ref(1)
@@ -165,17 +166,15 @@ export function useImageList() {
const listSummary = computed(() => {
const folder = activeFolder.value.trim() || 'all'
const folderLabel = folder === 'all' ? '全部' : folder
const folderLabel = folder === 'all' ? t('stats.allFolders') : folder
if (loadingTotal.value && folderTotal.value === null) {
return `${folderLabel} · 统计中…`
return `${folderLabel} · ${t('stats.counting')}`
}
if (activeSearch.value) {
return `${folderLabel} · 搜索「${activeSearch.value}」· 共 ${total.value} 张`
return t('stats.summarySearch', { folder: folderLabel, q: activeSearch.value, total: total.value })
}
if (folderTotal.value === null) {
return `${folderLabel} · 共 ${total.value} 张`
}
return `${folderLabel} · 共 ${folderTotal.value} 张`
const count = folderTotal.value === null ? total.value : folderTotal.value
return t('stats.summaryTotal', { folder: folderLabel, total: count })
})
return {
@@ -189,6 +188,7 @@ export function useImageList() {
activeSearch,
listSummary,
fetchList,
fetchSearch,
fetchTotal,
refreshList,
initializeList,
+6 -5
View File
@@ -9,6 +9,7 @@ const MAX_FILES = 10
export function useImageUpload() {
const toast = useToast()
const { t } = useI18n()
const { compressEnabled, clientWebpQuality } = useUploadPreferences()
const uploading = ref(false)
const progressItems = ref<UploadProgressItem[]>([])
@@ -22,13 +23,13 @@ export function useImageUpload() {
if (uploading.value) return
if (!files.length) {
toast.add({ title: '请选择图片', color: 'warning' })
toast.add({ title: t('upload.selectImages'), color: 'warning' })
return
}
if (files.length > MAX_FILES) {
toast.add({
title: `每次最多上传 ${MAX_FILES} 张图片`,
title: t('upload.maxFiles', { n: MAX_FILES }),
color: 'warning'
})
return
@@ -80,14 +81,14 @@ export function useImageUpload() {
if (response.items.length && options?.notify !== false) {
toast.add({
title: `成功上传 ${response.items.length} 张图片`,
title: t('upload.uploadSuccess', { n: response.items.length }),
color: 'success'
})
}
if (response.errors.length) {
toast.add({
title: `${response.errors.length} 张图片上传失败`,
title: t('upload.uploadPartialFail', { n: response.errors.length }),
color: 'warning'
})
}
@@ -97,7 +98,7 @@ export function useImageUpload() {
if (isUnauthorizedError(error)) {
throw error
}
const message = error instanceof Error ? error.message : '上传失败'
const message = error instanceof Error ? error.message : t('upload.uploadFailed')
progressItems.value = progressItems.value.map(item => ({
...item,
status: 'error',
+3 -2
View File
@@ -1,6 +1,7 @@
export function useUserAutoDeleteSettings() {
const { isAuthenticated, handleAuthError } = useAuth()
const toast = useToast()
const { t } = useI18n()
const userSettings = ref<{ autoDeleteDays: number } | null>(null)
const enabled = ref(false)
@@ -29,7 +30,7 @@ export function useUserAutoDeleteSettings() {
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: '加载设置失败', color: 'error' })
toast.add({ title: t('userSettings.loadFailed'), color: 'error' })
}
}
}
@@ -51,7 +52,7 @@ export function useUserAutoDeleteSettings() {
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: '保存设置失败', color: 'error' })
toast.add({ title: t('userSettings.saveFailed'), color: 'error' })
}
} finally {
saving.value = false
+15 -26
View File
@@ -10,6 +10,7 @@ const {
changePassword
} = useAuth()
const toast = useToast()
const { t } = useI18n()
const currentPassword = ref('')
const newPassword = ref('')
@@ -37,7 +38,7 @@ async function submit() {
if (!canSubmit.value || loading.value) return
if (newPassword.value !== confirmPassword.value) {
toast.add({ title: '两次输入的新密码不一致', color: 'error' })
toast.add({ title: t('auth.passwordMismatch'), color: 'error' })
return
}
@@ -48,7 +49,7 @@ async function submit() {
currentPassword.value = ''
newPassword.value = ''
confirmPassword.value = ''
toast.add({ title: '密码已修改', color: 'success' })
toast.add({ title: t('password.changed'), color: 'success' })
await router.replace('/')
} else {
toast.add({ title: result.error, color: 'error' })
@@ -71,7 +72,7 @@ async function submit() {
class="size-8 animate-spin"
/>
<p class="text-sm">
正在验证登录状态…
{{ t('common.loadingSession') }}
</p>
</div>
</div>
@@ -82,10 +83,10 @@ async function submit() {
<section class="mx-auto max-w-md overflow-hidden rounded-2xl border border-default bg-elevated shadow-sm">
<div class="border-b border-default px-5 py-4 sm:px-6">
<h1 class="text-lg font-semibold tracking-tight">
修改密码
{{ t('password.title') }}
</h1>
<p class="mt-1 text-sm text-muted">
修改您的登录密码
{{ t('password.subtitle') }}
</p>
</div>
@@ -98,16 +99,12 @@ async function submit() {
for="current-password"
class="block text-sm font-medium"
>
当前密码
{{ t('password.current') }}
</label>
<UInput
<PasswordInput
id="current-password"
v-model="currentPassword"
type="password"
autocomplete="current-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
/>
</div>
@@ -116,17 +113,13 @@ async function submit() {
for="new-password"
class="block text-sm font-medium"
>
新密码
{{ t('password.new') }}
</label>
<UInput
<PasswordInput
id="new-password"
v-model="newPassword"
type="password"
placeholder="设置新密码"
:placeholder="t('password.newPlaceholder')"
autocomplete="new-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
/>
<PasswordStrength :password="newPassword" />
</div>
@@ -136,29 +129,25 @@ async function submit() {
for="confirm-new-password"
class="block text-sm font-medium"
>
确认新密码
{{ t('password.confirmNew') }}
</label>
<UInput
<PasswordInput
id="confirm-new-password"
v-model="confirmPassword"
type="password"
autocomplete="new-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
/>
</div>
<div class="flex gap-2 pt-1">
<UButton
type="submit"
label="保存"
:label="t('common.save')"
icon="i-lucide-save"
:loading="loading"
:disabled="!canSubmit"
/>
<UButton
label="取消"
:label="t('common.cancel')"
variant="ghost"
color="neutral"
to="/"
+49 -48
View File
@@ -22,6 +22,7 @@ interface ApiDocItem {
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const toast = useToast()
const { t } = useI18n()
const settings = ref<SettingsResponse | null>(null)
const loading = ref(false)
@@ -49,8 +50,8 @@ const authHeaderFlag = computed(() => `-H 'Auth-Token: ${authHeader.value}'`)
const apiDocs = computed<ApiDocItem[]>(() => {
const uploadDescription = isAdmin.value
? '上传单张或多张图片。字段 image 传图片,folder 指定目录(不存在则自动创建);仍兼容 file、files、type。'
: '上传单张或多张图片。字段 image 传图片;仍兼容 file、files。图片固定存入 images/ 目录。'
? t('api.docs.upload.descAdmin')
: t('api.docs.upload.descUser')
const uploadCurl = isAdmin.value
? `curl -X POST "${baseUrl.value}/api/images/upload" \\
${authHeaderFlag.value} \\
@@ -66,8 +67,8 @@ curl -X POST "${baseUrl.value}/api/images/upload" \\
-F "image=@./demo.png"`
const listDescription = isAdmin.value
? '分页列出图库,folder 可筛选目录,limit 默认 20、最大 100。'
: '分页列出您的图库,limit 默认 20、最大 100。'
? t('api.docs.list.descAdmin')
: t('api.docs.list.descUser')
const listCurl = isAdmin.value
? `curl "${baseUrl.value}/api/images?limit=20&page=1" \\
${authHeaderFlag.value}
@@ -83,7 +84,7 @@ curl "${baseUrl.value}/api/images?folder=blog&limit=20&page=1" \\
index: 1,
method: 'POST',
path: '/api/images/upload',
title: '上传图片',
title: t('api.docs.upload.title'),
description: uploadDescription,
curl: uploadCurl
},
@@ -91,7 +92,7 @@ curl "${baseUrl.value}/api/images?folder=blog&limit=20&page=1" \\
index: 2,
method: 'GET',
path: '/api/images',
title: '获取图片列表',
title: t('api.docs.list.title'),
description: listDescription,
curl: listCurl
},
@@ -99,8 +100,8 @@ curl "${baseUrl.value}/api/images?folder=blog&limit=20&page=1" \\
index: 3,
method: 'GET',
path: '/api/images/search',
title: '搜索图片',
description: '按文件名或路径关键词搜索,参数 q 必填。',
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}`
},
@@ -108,8 +109,8 @@ curl "${baseUrl.value}/api/images?folder=blog&limit=20&page=1" \\
index: 4,
method: 'DELETE',
path: '/api/images',
title: '删除图片',
description: '通过 key 删除单张图片,key 为存储路径(如 images/2026/08/xxx.webp)。',
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}`
},
@@ -117,8 +118,8 @@ curl "${baseUrl.value}/api/images?folder=blog&limit=20&page=1" \\
index: 5,
method: 'POST',
path: '/api/images/batch-delete',
title: '批量删除',
description: '一次删除多张图片,请求体为 keys 数组。',
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" \\
@@ -130,8 +131,8 @@ curl "${baseUrl.value}/api/images?folder=blog&limit=20&page=1" \\
const twikooDoc = computed(() => ({
method: 'POST' as const,
path: '/api/index.php',
title: 'twikoo 兼容上传',
description: '兼容 Twikoo / EasyImage 2.0 协议,图片存入 twikoo/ 目录;字段 image + token。',
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"`
@@ -140,11 +141,11 @@ const twikooDoc = computed(() => ({
function tokenSourceLabel(source: SettingsResponse['tokenSource']) {
switch (source) {
case 'env':
return '来源:环境变量 API_UPLOAD_TOKEN'
return t('api.tokenSourceEnv')
case 'db':
return '来源:后台生成(可重新生成)'
return t('api.tokenSourceDb')
default:
return '来源:未配置'
return t('api.tokenSourceNone')
}
}
@@ -169,7 +170,7 @@ async function loadSettings() {
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: '加载 API 设置失败', color: 'error' })
toast.add({ title: t('api.loadFailed'), color: 'error' })
}
} finally {
loading.value = false
@@ -203,11 +204,11 @@ async function confirmRegenerate() {
: 0
if (status === 409) {
toast.add({
title: '环境变量已配置 Token,无法在后台重新生成',
title: t('api.regenerateEnvBlocked'),
color: 'warning'
})
} else {
toast.add({ title: '重新生成 Token 失败', color: 'error' })
toast.add({ title: t('api.regenerateFailed'), color: 'error' })
}
}
} finally {
@@ -218,9 +219,9 @@ async function confirmRegenerate() {
async function copyCurl(text: string) {
try {
await navigator.clipboard.writeText(text)
toast.add({ title: '已复制 cURL 示例', color: 'success' })
toast.add({ title: t('copy.curl'), color: 'success' })
} catch {
toast.add({ title: '复制失败', color: 'error' })
toast.add({ title: t('copy.failed'), color: 'error' })
}
}
@@ -263,7 +264,7 @@ watch(isAuthenticated, async (authed) => {
class="size-8 animate-spin"
/>
<p class="text-sm">
正在验证登录状态…
{{ t('common.loadingSession') }}
</p>
</div>
</div>
@@ -278,7 +279,7 @@ watch(isAuthenticated, async (authed) => {
class="size-5 text-primary"
/>
<h2 class="text-base font-semibold">
API Token
{{ t('api.tokenTitle') }}
</h2>
</div>
@@ -288,8 +289,8 @@ watch(isAuthenticated, async (authed) => {
color="warning"
variant="subtle"
icon="i-lucide-triangle-alert"
title="Token 由环境变量覆盖"
description="修改 API_UPLOAD_TOKEN 后需重启服务;后台无法重新生成。"
:title="t('api.envOverrideTitle')"
:description="t('api.envOverrideDesc')"
/>
<UAlert
@@ -297,8 +298,8 @@ watch(isAuthenticated, async (authed) => {
color="info"
variant="subtle"
icon="i-lucide-info"
title="个人 API Token"
description="此 Token 仅用于您自己的脚本上传,上传的图片归属您的账号。"
:title="t('api.personalTitle')"
:description="t('api.personalDesc')"
/>
<UAlert
@@ -306,25 +307,25 @@ watch(isAuthenticated, async (authed) => {
color="info"
variant="subtle"
icon="i-lucide-info"
title="尚未配置 Token"
description="点击「重新生成」创建 Token,用于下方所有接口的 Auth-Token 鉴权。"
: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 : '(未配置)'"
:model-value="hasToken ? tokenDisplay : t('common.notConfigured')"
readonly
class="min-w-0 flex-1 font-mono text-xs sm:text-sm"
:loading="loading"
/>
<div class="flex gap-2">
<CopyButton
label="复制"
:label="t('common.copy')"
:value="tokenDisplay"
/>
<UButton
icon="i-lucide-refresh-cw"
label="重新生成"
:label="t('api.regenerate')"
color="warning"
variant="soft"
:loading="regenerating"
@@ -339,10 +340,10 @@ watch(isAuthenticated, async (authed) => {
class="text-xs text-muted"
>
{{ tokenSourceLabel(settings.tokenSource) }}
· 请求头:
· {{ t('api.tokenHeader') }}
<code class="font-mono">Auth-Token: &lt;token&gt;</code>
<template v-if="hasToken && !settings.envTokenOverride">
· 重新生成后旧 Token 立即失效
· {{ t('api.tokenInvalidate') }}
</template>
</p>
</div>
@@ -355,7 +356,7 @@ watch(isAuthenticated, async (authed) => {
class="size-5 text-primary"
/>
<h2 class="text-base font-semibold">
API 文档
{{ t('api.docsTitle') }}
</h2>
</div>
@@ -395,12 +396,12 @@ watch(isAuthenticated, async (authed) => {
<div>
<p class="mb-2 text-xs font-medium text-muted">
cURL 示例
{{ t('api.curlExample') }}
</p>
<div class="relative overflow-hidden rounded-xl bg-neutral-950">
<UButton
icon="i-lucide-copy"
label="复制"
:label="t('common.copy')"
size="xs"
variant="ghost"
color="neutral"
@@ -445,12 +446,12 @@ watch(isAuthenticated, async (authed) => {
<div>
<p class="mb-2 text-xs font-medium text-muted">
cURL 示例
{{ t('api.curlExample') }}
</p>
<div class="relative overflow-hidden rounded-xl bg-neutral-950">
<UButton
icon="i-lucide-copy"
label="复制"
:label="t('common.copy')"
size="xs"
variant="ghost"
color="neutral"
@@ -466,20 +467,20 @@ watch(isAuthenticated, async (authed) => {
<UModal
:open="confirmRegenerateOpen"
title="确认重新生成 Token?"
description="旧 Token 将立即失效,使用旧 Token 的脚本与自动化任务将无法继续调用接口,直到你更新为新 Token。"
:title="t('api.confirmRegenerateTitle')"
:description="t('api.confirmRegenerateDesc')"
@update:open="confirmRegenerateOpen = $event"
>
<template #footer>
<div class="flex justify-end gap-2">
<UButton
label="取消"
:label="t('common.cancel')"
color="neutral"
variant="outline"
@click="closeConfirmRegenerate"
/>
<UButton
label="确认重新生成"
:label="t('api.confirmRegenerate')"
color="warning"
:loading="regenerating"
@click="confirmRegenerate"
@@ -490,8 +491,8 @@ watch(isAuthenticated, async (authed) => {
<UModal
:open="regenerateResultOpen"
title="新 Token 已生成"
description="请立即复制保存。关闭弹窗后仍可在上方输入框复制,但请尽快更新到你的脚本配置中。"
:title="t('api.newTokenTitle')"
:description="t('api.newTokenDesc')"
@update:open="regenerateResultOpen = $event"
>
<template #body>
@@ -504,11 +505,11 @@ watch(isAuthenticated, async (authed) => {
<template #footer>
<div class="flex w-full flex-wrap justify-end gap-2">
<CopyButton
label="复制 Token"
:label="t('api.copyToken')"
:value="newToken"
/>
<UButton
label="我已保存"
:label="t('api.saved')"
@click="closeRegenerateResult"
/>
</div>
+12 -11
View File
@@ -13,6 +13,7 @@ const {
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin }
= useAuth()
const toast = useToast()
const { t } = useI18n()
const folderOptions = ref<string[]>(['images'])
const sessionItems = ref<ImageItem[]>([])
const deletingKeys = ref<Set<string>>(new Set())
@@ -76,11 +77,11 @@ watch(isAuthenticated, async (authed, prev) => {
function copyFormatLabel() {
switch (copyFormat.value) {
case 'url':
return '直链'
return t('copy.url')
case 'html':
return 'HTML'
return t('copy.html')
default:
return 'Markdown'
return t('copy.markdown')
}
}
@@ -98,15 +99,15 @@ async function copyUploadLink(text: string) {
document.execCommand('copy')
document.body.removeChild(textarea)
}
toast.add({ title: `已复制 ${copyFormatLabel()}`, color: 'success' })
toast.add({ title: t('copy.copiedFormat', { format: copyFormatLabel() }), color: 'success' })
} catch {
toast.add({ title: '复制失败', color: 'error' })
toast.add({ title: t('copy.failed'), color: 'error' })
}
}
async function handleUpload(files: File[]) {
if (!isAuthenticated.value) {
toast.add({ title: '请先登录', color: 'warning' })
toast.add({ title: t('upload.loginRequired'), color: 'warning' })
return
}
@@ -149,10 +150,10 @@ async function handleDelete(key: string) {
query: { key }
})
sessionItems.value = sessionItems.value.filter(item => item.key !== key)
toast.add({ title: '已删除', color: 'success' })
toast.add({ title: t('stats.deletedSingle'), color: 'success' })
} catch (error: unknown) {
handleAuthError(error)
toast.add({ title: '删除失败', color: 'error' })
toast.add({ title: t('stats.deleteFailed'), color: 'error' })
} finally {
deletingKeys.value.delete(key)
deletingKeys.value = new Set(deletingKeys.value)
@@ -172,7 +173,7 @@ async function handleDelete(key: string) {
class="size-8 animate-spin"
/>
<p class="text-sm">
正在验证登录状态…
{{ t('common.loadingSession') }}
</p>
</div>
</div>
@@ -196,7 +197,7 @@ async function handleDelete(key: string) {
>
<div class="flex items-center justify-between gap-2">
<h2 class="text-lg font-medium">
本次上传
{{ t('upload.sessionTitle') }}
<span class="ml-1 text-sm font-normal text-muted">({{ sessionItems.length }})</span>
</h2>
</div>
@@ -207,7 +208,7 @@ async function handleDelete(key: string) {
:deleting-keys="deletingKeys"
:selectable="false"
:show-key="false"
empty-text="暂无本次上传"
:empty-text="t('upload.sessionEmpty')"
@update:selected-keys="() => {}"
@delete="handleDelete"
/>
+21 -25
View File
@@ -6,6 +6,7 @@ import { isPasswordValid } from '~/utils/password-strength'
const router = useRouter()
const { register, fetchStatus } = useAuth()
const toast = useToast()
const { t } = useI18n()
const username = ref('')
const password = ref('')
@@ -21,7 +22,7 @@ const canSubmit = computed(() =>
onMounted(async () => {
const status = await fetchStatus()
if (!status.initialized) {
if (!status.initialized && !status.legacyMode) {
await router.replace('/setup')
return
}
@@ -34,7 +35,7 @@ async function submit() {
if (!canSubmit.value || loading.value) return
if (password.value !== confirmPassword.value) {
toast.add({ title: '两次输入的密码不一致', color: 'error' })
toast.add({ title: t('auth.passwordMismatch'), color: 'error' })
return
}
@@ -42,7 +43,7 @@ async function submit() {
try {
const result = await register(username.value.trim(), password.value)
if (result.ok) {
toast.add({ title: '注册成功', color: 'success' })
toast.add({ title: t('auth.registerSuccess'), color: 'success' })
await router.replace('/')
} else {
toast.add({ title: result.error, color: 'error' })
@@ -54,7 +55,10 @@ async function submit() {
</script>
<template>
<div class="flex min-h-screen items-center justify-center bg-muted/30 p-4 sm:p-6">
<div class="relative flex min-h-screen items-center justify-center bg-muted/30 p-4 sm:p-6">
<div class="absolute top-4 right-4">
<AuthPagePreferences />
</div>
<div class="w-full max-w-sm rounded-2xl border border-default bg-elevated p-6 shadow-lg sm:p-8">
<div class="mb-8 space-y-3 text-center">
<div class="mx-auto inline-flex items-center justify-center">
@@ -77,10 +81,10 @@ async function submit() {
</div>
<div class="space-y-1">
<h1 class="text-xl font-bold tracking-tight sm:text-2xl">
注册账号
{{ t('register.title') }}
</h1>
<p class="text-sm text-muted">
创建 PicHost 用户账号
{{ t('register.subtitle') }}
</p>
</div>
</div>
@@ -94,12 +98,12 @@ async function submit() {
for="register-username"
class="block text-sm font-medium text-default"
>
用户名
{{ t('auth.username') }}
</label>
<UInput
id="register-username"
v-model="username"
placeholder="3–32 位字母、数字或下划线"
:placeholder="t('setup.usernamePlaceholder')"
autocomplete="username"
size="lg"
class="w-full"
@@ -112,17 +116,13 @@ async function submit() {
for="register-password"
class="block text-sm font-medium text-default"
>
密码
{{ t('auth.password') }}
</label>
<UInput
<PasswordInput
id="register-password"
v-model="password"
type="password"
placeholder="设置登录密码"
:placeholder="t('setup.passwordPlaceholder')"
autocomplete="new-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
/>
<PasswordStrength :password="password" />
</div>
@@ -132,23 +132,19 @@ async function submit() {
for="register-confirm"
class="block text-sm font-medium text-default"
>
确认密码
{{ t('auth.confirmPassword') }}
</label>
<UInput
<PasswordInput
id="register-confirm"
v-model="confirmPassword"
type="password"
placeholder="再次输入密码"
:placeholder="t('setup.confirmPlaceholder')"
autocomplete="new-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
/>
</div>
<UButton
type="submit"
label="注册"
:label="t('auth.register')"
icon="i-lucide-user-plus"
size="lg"
block
@@ -158,12 +154,12 @@ async function submit() {
/>
<p class="text-center text-sm text-muted">
已有账号?
{{ t('auth.hasAccount') }}
<NuxtLink
to="/"
class="text-primary hover:underline"
>
返回登录
{{ t('auth.backToLogin') }}
</NuxtLink>
</p>
</form>
+31 -31
View File
@@ -21,6 +21,7 @@ interface SettingsResponse {
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const { defaultFolder, loadPreferences } = useUploadPreferences()
const toast = useToast()
const { t } = useI18n()
const settings = ref<SettingsResponse | null>(null)
const folderOptions = ref<string[]>(['images'])
@@ -44,24 +45,24 @@ const hasServerChanges = computed(() => {
function sourceBadge(source: SettingSource | WebpQualitySource) {
switch (source) {
case 'env':
return { label: '.env', color: 'warning' as const }
return { label: t('settings.badgeEnv'), color: 'warning' as const }
case 'db':
return { label: '已保存', color: 'success' as const }
return { label: t('settings.badgeSaved'), color: 'success' as const }
case 'default':
return { label: '默认', color: 'neutral' as const }
return { label: t('settings.badgeDefault'), color: 'neutral' as const }
default:
return { label: '未设置', color: 'neutral' as const }
return { label: t('settings.badgeUnset'), color: 'neutral' as const }
}
}
function tokenSourceText(source: SettingSource) {
switch (source) {
case 'env':
return '环境变量'
return t('settings.tokenEnv')
case 'db':
return '后台生成'
return t('settings.tokenDb')
default:
return '未配置'
return t('settings.tokenNone')
}
}
@@ -93,7 +94,7 @@ function handlePatchError(error: unknown, fallback: string) {
handleAuthError(error)
if (!isAuthenticated.value) return
if (errorStatus(error) === 409) {
toast.add({ title: '该项已由环境变量覆盖,无法在后台修改', color: 'warning' })
toast.add({ title: t('settings.envOverride'), color: 'warning' })
void loadSettings()
return
}
@@ -110,9 +111,9 @@ async function saveServerSettings() {
imageBaseUrl: imageBaseUrlDraft.value,
allowRegistration: allowRegistrationDraft.value
})
toast.add({ title: '服务器配置已保存', color: 'success' })
toast.add({ title: t('settings.saved'), color: 'success' })
} catch (error: unknown) {
handlePatchError(error, '保存服务器配置失败')
handlePatchError(error, t('settings.saveFailed'))
} finally {
savingServer.value = false
}
@@ -137,7 +138,7 @@ async function loadSettings() {
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: '加载设置失败', color: 'error' })
toast.add({ title: t('settings.loadFailed'), color: 'error' })
}
}
}
@@ -189,7 +190,7 @@ watch(isAuthenticated, async (authed) => {
class="size-8 animate-spin"
/>
<p class="text-sm">
正在验证登录状态…
{{ t('common.loadingSession') }}
</p>
</div>
</div>
@@ -209,10 +210,10 @@ watch(isAuthenticated, async (authed) => {
/>
<div class="min-w-0">
<h1 class="text-base font-semibold">
系统设置
{{ t('settings.title') }}
</h1>
<p class="mt-0.5 text-xs text-muted">
保存后写入数据库;环境变量优先级更高
{{ t('settings.subtitle') }}
</p>
</div>
</div>
@@ -224,13 +225,13 @@ watch(isAuthenticated, async (authed) => {
<div class="grid gap-5 sm:grid-cols-3 sm:gap-6">
<div class="space-y-4">
<h3 class="text-sm font-semibold">
上传与账号
{{ t('settings.uploadAccount') }}
</h3>
<div class="space-y-2">
<label class="text-sm">默认上传目录</label>
<label class="text-sm">{{ t('settings.defaultFolder') }}</label>
<p class="text-xs leading-relaxed text-muted">
保存在本机浏览器,仅影响您的上传目标目录
{{ t('settings.defaultFolderHint') }}
</p>
<USelect
v-model="defaultFolder"
@@ -245,9 +246,9 @@ watch(isAuthenticated, async (authed) => {
class="mt-0.5"
/>
<span>
<span class="block text-sm">开放用户注册</span>
<span class="block text-sm">{{ t('settings.allowRegistration') }}</span>
<span class="mt-1 block text-xs leading-relaxed text-muted">
允许新用户自行注册(普通用户仅可见自己的图片)
{{ t('settings.allowRegistrationHint') }}
</span>
</span>
</label>
@@ -256,7 +257,7 @@ watch(isAuthenticated, async (authed) => {
<div class="space-y-4">
<div class="flex items-center justify-between gap-2">
<h3 class="text-sm font-semibold">
访问控制
{{ t('settings.accessControl') }}
</h3>
<UBadge
:color="sourceBadge(settings.refererSource).color"
@@ -267,11 +268,11 @@ watch(isAuthenticated, async (authed) => {
</UBadge>
</div>
<p class="text-xs leading-relaxed text-muted">
Referer 防盗链,逗号分隔允许引用的域名,留空不限制
{{ t('settings.refererHint') }}
</p>
<UTextarea
v-model="refererDraft"
placeholder="example.com, www.example.com"
:placeholder="t('settings.refererPlaceholder')"
:rows="4"
class="w-full font-mono text-sm"
/>
@@ -280,7 +281,7 @@ watch(isAuthenticated, async (authed) => {
<div class="space-y-4">
<div class="flex items-center justify-between gap-2">
<h3 class="text-sm font-semibold">
链接生成
{{ t('settings.linkGeneration') }}
</h3>
<UBadge
:color="sourceBadge(settings.imageBaseUrlSource).color"
@@ -291,18 +292,18 @@ watch(isAuthenticated, async (authed) => {
</UBadge>
</div>
<p class="text-xs leading-relaxed text-muted">
生成图片链接的 URL 前缀,内网访问建议填公网域名
{{ t('settings.imageBaseUrlHint') }}
</p>
<UInput
v-model="imageBaseUrlDraft"
placeholder="https://pic.example.com"
:placeholder="t('settings.imageBaseUrlPlaceholder')"
class="w-full font-mono text-sm"
/>
<p
v-if="settings.imageBaseUrl"
class="text-xs text-muted"
>
当前生效:<span class="font-mono break-all">{{ settings.imageBaseUrl }}</span>
{{ t('settings.imageBaseUrlActive', { url: settings.imageBaseUrl }) }}
</p>
</div>
</div>
@@ -328,16 +329,15 @@ watch(isAuthenticated, async (authed) => {
class="size-3.5 shrink-0"
/>
<span>
API Token · {{ tokenSourceText(settings.tokenSource) }}
<span class="text-dimmed">· v{{ settings.appVersion }}</span>
{{ t('settings.apiTokenLine', { source: tokenSourceText(settings.tokenSource), version: settings.appVersion }) }}
<template v-if="hasServerChanges">
· <span class="text-warning">有未保存的更改</span>
· <span class="text-warning">{{ t('settings.unsavedChanges') }}</span>
</template>
</span>
</div>
<div class="flex flex-wrap items-center gap-2">
<UButton
label="管理 Token"
:label="t('settings.manageToken')"
icon="i-lucide-external-link"
variant="outline"
color="neutral"
@@ -345,7 +345,7 @@ watch(isAuthenticated, async (authed) => {
to="/api"
/>
<UButton
label="保存"
:label="t('common.save')"
icon="i-lucide-save"
size="sm"
:loading="savingServer"
+25 -23
View File
@@ -7,8 +7,10 @@ const route = useRoute()
const router = useRouter()
const { setup, migrate, fetchStatus } = useAuth()
const toast = useToast()
const { t } = useI18n()
const isMigrate = computed(() => route.query.migrate === '1')
const needsMigration = ref(false)
const isMigrate = computed(() => needsMigration.value || route.query.migrate === '1')
const username = ref('')
const password = ref('')
@@ -25,6 +27,11 @@ const canSubmit = computed(() =>
onMounted(async () => {
const status = await fetchStatus()
needsMigration.value = status.needsMigration
if (status.legacyMode && !status.needsMigration) {
await router.replace('/')
return
}
if (status.initialized && !status.needsMigration) {
await router.replace('/')
}
@@ -34,7 +41,7 @@ async function submit() {
if (!canSubmit.value || loading.value) return
if (password.value !== confirmPassword.value) {
toast.add({ title: '两次输入的密码不一致', color: 'error' })
toast.add({ title: t('auth.passwordMismatch'), color: 'error' })
return
}
@@ -51,7 +58,7 @@ async function submit() {
if (result.ok) {
toast.add({
title: isMigrate.value ? '账号迁移完成' : '初始化完成',
title: isMigrate.value ? t('setup.migrateSuccess') : t('setup.initSuccess'),
color: 'success'
})
await router.replace('/')
@@ -65,7 +72,10 @@ async function submit() {
</script>
<template>
<div class="flex min-h-screen items-center justify-center bg-muted/30 p-4 sm:p-6">
<div class="relative flex min-h-screen items-center justify-center bg-muted/30 p-4 sm:p-6">
<div class="absolute top-4 right-4">
<AuthPagePreferences />
</div>
<div class="w-full max-w-sm rounded-2xl border border-default bg-elevated p-6 shadow-lg sm:p-8">
<div class="mb-8 space-y-3 text-center">
<div class="mx-auto inline-flex items-center justify-center">
@@ -91,7 +101,7 @@ async function submit() {
<span class="text-highlighted">Pic</span><span class="text-primary">Host</span>
</h1>
<p class="text-sm text-muted">
{{ isMigrate ? '迁移到账号密码登录' : '首次使用,创建管理员账号' }}
{{ isMigrate ? t('setup.migrateTitle') : t('setup.initTitle') }}
</p>
</div>
</div>
@@ -105,12 +115,12 @@ async function submit() {
for="setup-username"
class="block text-sm font-medium text-default"
>
用户名
{{ t('auth.username') }}
</label>
<UInput
id="setup-username"
v-model="username"
placeholder="3–32 位字母、数字或下划线"
:placeholder="t('setup.usernamePlaceholder')"
autocomplete="username"
size="lg"
class="w-full"
@@ -123,17 +133,13 @@ async function submit() {
for="setup-password"
class="block text-sm font-medium text-default"
>
密码
{{ t('auth.password') }}
</label>
<UInput
<PasswordInput
id="setup-password"
v-model="password"
type="password"
placeholder="设置登录密码"
:placeholder="t('setup.passwordPlaceholder')"
autocomplete="new-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
/>
<PasswordStrength :password="password" />
</div>
@@ -143,28 +149,24 @@ async function submit() {
for="setup-confirm"
class="block text-sm font-medium text-default"
>
确认密码
{{ t('auth.confirmPassword') }}
</label>
<UInput
<PasswordInput
id="setup-confirm"
v-model="confirmPassword"
type="password"
placeholder="再次输入密码"
:placeholder="t('setup.confirmPlaceholder')"
autocomplete="new-password"
size="lg"
class="w-full"
:ui="{ root: 'w-full' }"
/>
</div>
<label class="flex cursor-pointer items-center gap-2 text-sm text-default">
<UCheckbox v-model="allowRegistration" />
允许其他用户注册
{{ t('setup.allowRegistration') }}
</label>
<UButton
type="submit"
:label="isMigrate ? '完成迁移' : '创建并进入'"
:label="isMigrate ? t('setup.migrateSubmit') : t('setup.initSubmit')"
icon="i-lucide-user-plus"
size="lg"
block
+120 -93
View File
@@ -35,7 +35,9 @@ const {
activeSearch,
listSummary,
refreshList,
initializeList,
fetchList,
fetchSearch,
fetchTotal,
setActiveFolder,
submitSearch,
goToPage,
@@ -45,9 +47,11 @@ const {
const { formatFileSize } = useFileSize()
const { isChecking, isAuthenticated, checkSession, handleAuthError, fetchStatus, isAdmin } = useAuth()
const toast = useToast()
const { t } = useI18n()
const stats = ref<StatsResponse | null>(null)
const statsLoading = ref(false)
const pageRefreshing = computed(() => statsLoading.value || galleryLoading.value)
const selectedKeys = ref<Set<string>>(new Set())
const deletingKeys = ref<Set<string>>(new Set())
@@ -59,7 +63,7 @@ const currentFolder = ref('all')
const folderOptions = ref<string[]>(['images'])
const folderSelectItems = computed(() => [
{ label: '全部', value: 'all' },
{ label: t('stats.allFolders'), value: 'all' },
...folderOptions.value.map(folder => ({ label: folder, value: folder }))
])
@@ -104,16 +108,16 @@ const uploadChartTotal = computed(() =>
const statCards = computed(() => {
const s = stats.value
const base = [
{ label: '今日上传', value: s?.uploadToday ?? '—' },
{ label: '本月上传', value: s?.uploadMonth ?? '—' },
{ label: '累计上传', value: s?.uploadTotal ?? '—' },
{ label: '当前库存', value: s?.storedCount ?? '—' },
{ label: '今日删除', value: s?.deleteToday ?? '—' },
{ label: '本月删除', value: s?.deleteMonth ?? '—' },
{ 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: '注册用户数量', value: s?.userCount ?? '—' }
: { label: '累计删除', value: s?.deleteTotal ?? '—' },
{ label: '累计上传体积', value: s ? formatFileSize(s.uploadBytesTotal) : '—' }
? { 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
})
@@ -150,7 +154,7 @@ async function refreshStats() {
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: '加载统计失败', color: 'error' })
toast.add({ title: t('stats.loadFailed'), color: 'error' })
}
} finally {
statsLoading.value = false
@@ -167,13 +171,33 @@ async function refreshGallery() {
}
}
async function reloadGallery() {
if (activeSearch.value) {
await fetchSearch(galleryPage.value)
} else {
await fetchList(galleryPage.value)
}
await fetchTotal()
}
async function refreshAll() {
if (!isAuthenticated.value) return
currentFolder.value = 'all'
await Promise.all([
refreshStats(),
initializeList('all').then(() => loadFolders())
])
selectedKeys.value = new Set()
statsLoading.value = true
try {
await Promise.all([
fetchStats(),
reloadGallery(),
loadFolders()
])
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: t('stats.loadFailed'), color: 'error' })
}
} finally {
statsLoading.value = false
}
}
async function handleFolderChange(folder: string) {
@@ -212,7 +236,7 @@ function requestDelete(key: string) {
function requestBatchDelete() {
if (!isAuthenticated.value) return
if (!selectedCount.value) {
toast.add({ title: '请先选择图片', color: 'warning' })
toast.add({ title: t('stats.selectFirst'), color: 'warning' })
return
}
deleteTargetKeys.value = Array.from(selectedKeys.value)
@@ -249,7 +273,7 @@ async function confirmDelete() {
}
selectedKeys.value = new Set(selectedKeys.value)
toast.add({
title: `已删除 ${deleted.length} 张图片`,
title: t('stats.deleted', { n: deleted.length }),
color: 'success'
})
await refreshStats()
@@ -257,7 +281,7 @@ async function confirmDelete() {
if (failed.length) {
toast.add({
title: `${failed.length} 张图片删除失败`,
title: t('stats.deletePartialFail', { n: failed.length }),
color: 'error'
})
}
@@ -267,7 +291,7 @@ async function confirmDelete() {
} catch (error: unknown) {
handleAuthError(error)
if (isAuthenticated.value) {
toast.add({ title: '删除失败', color: 'error' })
toast.add({ title: t('stats.deleteFailed'), color: 'error' })
}
} finally {
batchDeleting.value = false
@@ -322,7 +346,7 @@ watch(isAuthenticated, async (authed, prev) => {
class="size-8 animate-spin"
/>
<p class="text-sm">
正在验证登录状态…
{{ t('common.loadingSession') }}
</p>
</div>
</div>
@@ -330,21 +354,24 @@ watch(isAuthenticated, async (authed, prev) => {
<AdminLoginGate v-else-if="!isAuthenticated" />
<AppShell v-else>
<div class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<div class="flex items-start justify-between gap-3">
<div class="min-w-0">
<h1 class="text-2xl font-semibold tracking-tight">
统计
{{ t('stats.title') }}
</h1>
<p class="text-sm text-muted">
数据概览与图库记录
{{ t('stats.subtitle') }}
</p>
</div>
<UButton
icon="i-lucide-refresh-cw"
label="刷新"
variant="outline"
:loading="statsLoading || galleryLoading"
variant="ghost"
color="neutral"
size="sm"
class="mt-0.5 shrink-0"
:aria-label="t('common.refresh')"
:loading="pageRefreshing"
@click="refreshAll"
/>
</div>
@@ -367,13 +394,13 @@ watch(isAuthenticated, async (authed, prev) => {
<section class="grid gap-4 lg:grid-cols-2">
<div class="rounded-xl border border-default bg-elevated p-4">
<h2 class="mb-3 text-sm font-medium text-muted">
上传目录分布
{{ t('stats.folderDistribution') }}
</h2>
<div
v-if="!uploadChartTotal"
class="py-6 text-center text-xs text-muted"
>
暂无数据
{{ t('stats.noData') }}
</div>
<StatsDonut
v-else
@@ -384,13 +411,13 @@ watch(isAuthenticated, async (authed, prev) => {
<div class="rounded-xl border border-default bg-elevated p-4">
<h2 class="mb-3 text-sm font-medium text-muted">
目录占用
{{ t('stats.folderUsage') }}
</h2>
<div
v-if="!folderStats.length"
class="py-6 text-center text-xs text-muted"
>
暂无数据
{{ t('stats.noData') }}
</div>
<ul
v-else
@@ -403,7 +430,7 @@ watch(isAuthenticated, async (authed, prev) => {
<div class="mb-1 flex items-center justify-between gap-2 text-xs">
<span class="font-medium">{{ item.folder }}</span>
<span class="tabular-nums text-muted">
{{ item.count }} 张 · {{ formatFileSize(item.bytes) }}
{{ t('stats.folderCount', { count: item.count, size: formatFileSize(item.bytes) }) }}
</span>
</div>
<div class="h-1.5 overflow-hidden rounded-full bg-muted/50">
@@ -418,86 +445,85 @@ watch(isAuthenticated, async (authed, prev) => {
</section>
<section class="space-y-4">
<form
class="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between"
@submit.prevent="handleSearch"
>
<div class="min-w-0 shrink-0">
<div class="flex flex-wrap items-center justify-between gap-x-4 gap-y-3">
<div class="min-w-0">
<h2 class="text-lg font-medium">
图库记录
{{ t('stats.gallery') }}
</h2>
<p
v-if="!galleryLoading"
class="text-sm text-muted"
class="mt-0.5 text-sm text-muted"
>
{{ listSummary }}
</p>
</div>
<div class="flex flex-wrap items-center justify-end gap-2">
<div class="flex items-center gap-1.5">
<span class="text-xs text-muted shrink-0">目录</span>
<USelect
v-model="currentFolder"
:items="folderSelectItems"
class="w-28"
@update:model-value="handleFolderChange"
/>
</div>
<UInput
v-model="searchQuery"
icon="i-lucide-search"
placeholder="搜索文件名"
class="w-40 sm:w-48"
size="sm"
:disabled="galleryLoading"
/>
<UButton
type="submit"
label="搜索"
size="sm"
:loading="galleryLoading"
/>
<UButton
v-if="activeSearch"
type="button"
label="清除"
size="sm"
variant="ghost"
color="neutral"
@click="clearSearch"
/>
<UButton
type="button"
icon="i-lucide-refresh-cw"
label="刷新"
variant="outline"
size="sm"
:loading="galleryLoading"
@click="refreshGallery"
/>
<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"
>
已选 {{ selectedCount }}
{{ t('stats.selected', { n: selectedCount }) }}
</UBadge>
<USelect
v-model="currentFolder"
:items="folderSelectItems"
class="w-[5.5rem] shrink-0 sm:w-32"
size="sm"
:aria-label="t('stats.folder')"
@update:model-value="handleFolderChange"
/>
<UInput
v-model="searchQuery"
icon="i-lucide-search"
:placeholder="t('stats.searchPlaceholder')"
class="w-36 shrink-0 sm:w-44"
size="sm"
:disabled="galleryLoading"
/>
<UButton
type="submit"
icon="i-lucide-search"
size="sm"
class="shrink-0"
:aria-label="t('common.search')"
:loading="galleryLoading"
>
<span class="hidden sm:inline">{{ t('common.search') }}</span>
</UButton>
<UButton
v-if="activeSearch"
type="button"
icon="i-lucide-x"
size="sm"
variant="ghost"
color="neutral"
class="shrink-0"
:aria-label="t('stats.clear')"
@click="clearSearch"
>
<span class="hidden sm:inline">{{ t('stats.clear') }}</span>
</UButton>
<UButton
type="button"
icon="i-lucide-trash-2"
label="批量删除"
color="error"
variant="soft"
size="sm"
class="shrink-0"
:aria-label="t('stats.batchDelete')"
:disabled="!selectedCount"
@click="requestBatchDelete"
/>
</div>
</form>
>
<span class="hidden sm:inline">{{ t('stats.batchDelete') }}</span>
</UButton>
</form>
</div>
<div
v-if="galleryLoading"
@@ -512,6 +538,7 @@ watch(isAuthenticated, async (authed, prev) => {
<ImageGrid
v-else
:show-key="false"
:items="items"
:selected-keys="selectedKeys"
:deleting-keys="deletingKeys"
@@ -524,7 +551,7 @@ watch(isAuthenticated, async (authed, prev) => {
:page="galleryPage"
:total-pages="galleryTotalPages"
:total="galleryTotal"
unit="张"
:unit="t('common.imagesUnit')"
:loading="galleryLoading"
@update:page="handleGalleryPageChange"
/>
@@ -540,7 +567,7 @@ watch(isAuthenticated, async (authed, prev) => {
<UButton
v-show="showScrollTop"
icon="i-lucide-arrow-up"
aria-label="回到顶部"
:aria-label="t('stats.scrollTop')"
color="primary"
class="fixed bottom-6 right-6 z-50 shadow-lg"
size="lg"
+2 -2
View File
@@ -7,7 +7,7 @@ export interface PasswordCriteria {
hasSpecial: boolean
}
export type PasswordStrengthLabel = '弱' | '中' | '强'
export type PasswordStrengthLabel = 'weak' | 'medium' | 'strong'
export function analyzePassword(password: string): {
criteria: PasswordCriteria
@@ -24,7 +24,7 @@ export function analyzePassword(password: string): {
const score = Object.values(criteria).filter(Boolean).length
const label: PasswordStrengthLabel
= score <= 1 ? '弱' : score <= 3 ? '中' : '强'
= score <= 1 ? 'weak' : score <= 3 ? 'medium' : 'strong'
return {
criteria,
-2
View File
@@ -4,8 +4,6 @@ services:
# 飞牛 Docker 对 Docker Hub 的「更新镜像」支持更好
image: muxui/pichost:latest
pull_policy: always
# 备用:GitHub Container Registry
# image: ghcr.io/O96u/pichost:latest
container_name: pichost
restart: unless-stopped
ports:
+8
View File
@@ -0,0 +1,8 @@
#!/bin/sh
set -e
if [ "$1" = "reset-password" ]; then
exec node /app/server/cli/reset-password.mjs
fi
exec node /app/.output/server/index.mjs "$@"
+305
View File
@@ -0,0 +1,305 @@
{
"app": {
"title": "PicHost - Image Hosting",
"description": "A lightweight self-hosted image hosting system",
"tagline": "Personal lightweight image host"
},
"common": {
"loadingSession": "Verifying session…",
"save": "Save",
"cancel": "Cancel",
"copy": "Copy",
"delete": "Delete",
"search": "Search",
"refresh": "Refresh",
"back": "Back",
"all": "All",
"notConfigured": "(not configured)",
"countImages": "{count} images",
"itemsUnit": "items",
"imagesUnit": "images"
},
"nav": {
"api": "API",
"stats": "Stats",
"settings": "Settings",
"menu": "Menu",
"language": "Language",
"appearance": "Appearance",
"account": "Account",
"backToUpload": "Back to upload",
"changePassword": "Change password",
"systemSettings": "System settings",
"logout": "Log out"
},
"theme": {
"switch": "Switch theme",
"light": "Light",
"dark": "Dark",
"system": "System"
},
"locale": {
"switch": "Switch language",
"zh-CN": "简体中文",
"en": "English"
},
"auth": {
"username": "Username",
"password": "Password",
"confirmPassword": "Confirm password",
"login": "Log in",
"register": "Register",
"adminSecret": "Admin secret",
"adminSecretPlaceholder": "Enter ADMIN_SECRET",
"legacyHint": "Legacy deployment: sign in with the secret to migrate to username/password",
"noAccount": "No account?",
"hasAccount": "Already have an account?",
"backToLogin": "Back to login",
"loginFooter": "Upload and management require sign-in",
"loginSuccess": "Signed in",
"loginFailedSecret": "Sign-in failed. Check your secret",
"loginFailedCredentials": "Invalid username or password",
"loginFailed": "Sign-in failed. Check username and password",
"registerFailed": "Registration failed. Check your input",
"setupFailed": "Setup failed. Check your input",
"migrateFailed": "Migration failed. Check your input",
"passwordMismatch": "Passwords do not match",
"showPassword": "Show password",
"hidePassword": "Hide password",
"registerSuccess": "Registered successfully",
"errors": {
"invalidUsername": "Username must be 3–32 letters, numbers, or underscores",
"invalidPassword": "Password must be at least 8 characters"
}
},
"setup": {
"migrateTitle": "Migrate to username/password",
"initTitle": "First run — create admin account",
"usernamePlaceholder": "3–32 letters, numbers, or underscores",
"passwordPlaceholder": "Set login password",
"confirmPlaceholder": "Enter password again",
"allowRegistration": "Allow user registration",
"migrateSubmit": "Complete migration",
"initSubmit": "Create and continue",
"migrateSuccess": "Migration complete",
"initSuccess": "Setup complete"
},
"register": {
"title": "Register",
"subtitle": "Create a PicHost user account"
},
"password": {
"title": "Change password",
"subtitle": "Update your login password",
"current": "Current password",
"new": "New password",
"confirmNew": "Confirm new password",
"newPlaceholder": "Set new password",
"changed": "Password updated",
"tooShort": "New password must be at least 8 characters",
"changeFailed": "Failed to change password",
"strength": "Password strength",
"weak": "Weak",
"medium": "Medium",
"strong": "Strong",
"ruleMinLength": "At least {n} characters",
"ruleMixedCase": "Upper and lower case letters",
"ruleNumber": "Contains a number",
"ruleSpecial": "Contains a special character"
},
"upload": {
"title": "Drop images here to upload",
"hint": "Or click to select files, press {ctrl} + {v} to paste",
"formats": "JPEG / PNG / WebP / GIF / SVG / ICO, max 10 MB each, up to 10 files per batch",
"selectFiles": "Select images",
"settings": "Upload settings",
"progress": "Upload progress",
"statusPending": "Pending",
"statusUploading": "Uploading",
"statusSuccess": "Done",
"statusError": "Failed",
"selectImages": "Select images to upload",
"maxFiles": "Up to {n} images per upload",
"uploadSuccess": "Uploaded {n} image(s)",
"uploadPartialFail": "{n} image(s) failed to upload",
"uploadFailed": "Upload failed",
"loginRequired": "Please sign in first",
"sessionTitle": "This session",
"sessionEmpty": "No uploads in this session"
},
"copy": {
"url": "URL",
"markdown": "Markdown",
"html": "HTML",
"copied": "Copied to clipboard",
"copiedLabel": "Copied {label}",
"copiedUrl": "URL copied",
"copiedMarkdown": "Markdown copied",
"copiedHtml": "HTML copied",
"copiedFormat": "Copied {format}",
"failed": "Copy failed",
"failedManual": "Copy failed — select the link manually",
"curl": "cURL example copied"
},
"preferences": {
"title": "Upload preferences",
"subtitle": "Browser-local and account settings for your uploads only",
"back": "Back to upload",
"processing": "Image processing",
"clientCompress": "Client-side compression",
"clientCompressHint": "Compress in the browser before upload (server still converts to WebP)",
"autoDeletePrefix": "Auto-delete after",
"autoDeleteSuffix": "days",
"autoDeleteHint": "Only affects images uploaded after enabling; existing images are kept",
"webpQuality": "WebP quality",
"webpQualityHint": "Client compression quality (1–100); requires client-side compression",
"current": "Current: {n}",
"qualityHigh": "High quality",
"qualityMedium": "Medium quality",
"qualityLow": "Lossy",
"convenience": "Convenience",
"autoCopy": "Copy link after upload",
"autoCopyHint": "Copy to clipboard in the selected format"
},
"settings": {
"title": "System settings",
"subtitle": "Saved to database; environment variables take precedence",
"uploadAccount": "Upload & accounts",
"defaultFolder": "Default upload folder",
"defaultFolderHint": "Stored in this browser only; affects your upload target",
"allowRegistration": "Open registration",
"allowRegistrationHint": "Allow new users to register (regular users see only their images)",
"accessControl": "Access control",
"refererHint": "Referer hotlink protection; comma-separated hostnames, empty = no restriction",
"refererPlaceholder": "example.com, www.example.com",
"linkGeneration": "Link generation",
"imageBaseUrlHint": "Public URL prefix for generated links; use your public domain behind a reverse proxy",
"imageBaseUrlPlaceholder": "https://pic.example.com",
"imageBaseUrlActive": "Active: {url}",
"badgeEnv": ".env",
"badgeSaved": "Saved",
"badgeDefault": "Default",
"badgeUnset": "Not set",
"tokenEnv": "Environment",
"tokenDb": "Generated in app",
"tokenNone": "Not configured",
"apiTokenLine": "API Token · {source} · v{version}",
"unsavedChanges": "Unsaved changes",
"manageToken": "Manage token",
"envOverride": "Overridden by environment variable; cannot edit in UI",
"saved": "Settings saved",
"saveFailed": "Failed to save settings",
"loadFailed": "Failed to load settings"
},
"stats": {
"title": "Statistics",
"subtitle": "Overview and gallery",
"uploadToday": "Uploaded today",
"uploadMonth": "Uploaded this month",
"uploadTotal": "Total uploads",
"storedCount": "Stored images",
"deleteToday": "Deleted today",
"deleteMonth": "Deleted this month",
"deleteTotal": "Total deleted",
"userCount": "Registered users",
"uploadBytes": "Total upload size",
"folderDistribution": "Uploads by folder",
"folderUsage": "Storage by folder",
"noData": "No data",
"folderCount": "{count} · {size}",
"gallery": "Gallery",
"folder": "Folder",
"searchPlaceholder": "Search filename",
"clear": "Clear",
"selected": "{n} selected",
"batchDelete": "Delete selected",
"scrollTop": "Back to top",
"loadFailed": "Failed to load statistics",
"selectFirst": "Select images first",
"deleted": "Deleted {n} image(s)",
"deletePartialFail": "{n} image(s) failed to delete",
"deleteFailed": "Delete failed",
"deletedSingle": "Deleted",
"allFolders": "All",
"counting": "Counting…",
"summarySearch": "{folder} · Search “{q}” · {total} images",
"summaryTotal": "{folder} · {total} images"
},
"image": {
"empty": "No images",
"previewFailed": "Preview failed",
"uploader": "Uploader: {name}"
},
"delete": {
"confirmTitle": "Confirm delete",
"confirmDesc": "Delete {count} selected image(s)? This cannot be undone.",
"confirm": "Delete"
},
"pagination": {
"pageOf": "Page {page} / {totalPages} · {total} {unit}",
"totalOnly": "{total} {unit}",
"first": "First page",
"prev": "Previous page",
"next": "Next page",
"last": "Last page"
},
"api": {
"tokenTitle": "API Token",
"envOverrideTitle": "Token overridden by environment",
"envOverrideDesc": "Restart after changing API_UPLOAD_TOKEN; cannot regenerate in UI.",
"personalTitle": "Personal API token",
"personalDesc": "For your scripts only; uploads belong to your account.",
"notConfiguredTitle": "No token configured",
"notConfiguredDesc": "Click Regenerate to create a token for Auth-Token on all endpoints below.",
"regenerate": "Regenerate",
"tokenSourceEnv": "Source: API_UPLOAD_TOKEN environment variable",
"tokenSourceDb": "Source: generated in app (can regenerate)",
"tokenSourceNone": "Source: not configured",
"tokenHeader": "Header:",
"tokenInvalidate": "Old token is invalidated immediately after regenerate",
"docsTitle": "API reference",
"curlExample": "cURL example",
"loadFailed": "Failed to load API settings",
"regenerateEnvBlocked": "Token is set via environment; cannot regenerate in UI",
"regenerateFailed": "Failed to regenerate token",
"confirmRegenerateTitle": "Regenerate token?",
"confirmRegenerateDesc": "The old token stops working immediately. Update scripts and automation before continuing.",
"confirmRegenerate": "Regenerate",
"newTokenTitle": "New token generated",
"newTokenDesc": "Copy and save it now. You can copy again from the field above after closing.",
"copyToken": "Copy token",
"saved": "Saved",
"docs": {
"upload": {
"title": "Upload images",
"descAdmin": "Upload one or more images. Use image field; folder creates directory if missing. Also accepts file, files, type.",
"descUser": "Upload one or more images via image field. Also accepts file, files. Stored under images/."
},
"list": {
"title": "List images",
"descAdmin": "Paginated gallery; optional folder filter. limit default 20, max 100.",
"descUser": "Paginated list of your images. limit default 20, max 100."
},
"search": {
"title": "Search images",
"desc": "Search by filename or path; q is required."
},
"delete": {
"title": "Delete image",
"desc": "Delete by key (storage path, e.g. images/2026/08/xxx.webp)."
},
"batchDelete": {
"title": "Batch delete",
"desc": "Delete multiple images; request body is a keys array."
},
"twikoo": {
"title": "Twikoo-compatible upload",
"desc": "Twikoo / EasyImage 2.0 protocol; stored under twikoo/. Fields: image + token."
}
}
},
"userSettings": {
"loadFailed": "Failed to load settings",
"saveFailed": "Failed to save settings"
}
}
+305
View File
@@ -0,0 +1,305 @@
{
"app": {
"title": "PicHost - 个人图床",
"description": "个人自用的轻量图床系统",
"tagline": "个人轻量图床"
},
"common": {
"loadingSession": "正在验证登录状态…",
"save": "保存",
"cancel": "取消",
"copy": "复制",
"delete": "删除",
"search": "搜索",
"refresh": "刷新",
"back": "返回",
"all": "全部",
"notConfigured": "(未配置)",
"countImages": "{count} 张",
"itemsUnit": "条",
"imagesUnit": "张"
},
"nav": {
"api": "API",
"stats": "统计",
"settings": "设置",
"menu": "菜单",
"language": "语言",
"appearance": "外观",
"account": "账户",
"backToUpload": "返回上传",
"changePassword": "修改密码",
"systemSettings": "系统设置",
"logout": "退出登录"
},
"theme": {
"switch": "切换主题",
"light": "浅色",
"dark": "深色",
"system": "跟随系统"
},
"locale": {
"switch": "切换语言",
"zh-CN": "简体中文",
"en": "English"
},
"auth": {
"username": "用户名",
"password": "密码",
"confirmPassword": "确认密码",
"login": "登录",
"register": "注册",
"adminSecret": "管理密钥",
"adminSecretPlaceholder": "输入 ADMIN_SECRET",
"legacyHint": "遗留部署:使用密钥登录后将引导创建账号",
"noAccount": "没有账号?",
"hasAccount": "已有账号?",
"backToLogin": "返回登录",
"loginFooter": "未登录时无法访问上传和管理功能",
"loginSuccess": "登录成功",
"loginFailedSecret": "登录失败,请检查密钥",
"loginFailedCredentials": "用户名或密码错误",
"loginFailed": "登录失败,请检查用户名和密码",
"registerFailed": "注册失败,请检查输入",
"setupFailed": "初始化失败,请检查输入",
"migrateFailed": "迁移失败,请检查输入",
"passwordMismatch": "两次输入的密码不一致",
"showPassword": "显示密码",
"hidePassword": "隐藏密码",
"registerSuccess": "注册成功",
"errors": {
"invalidUsername": "用户名需为 3–32 位字母、数字或下划线",
"invalidPassword": "密码至少 8 位"
}
},
"setup": {
"migrateTitle": "迁移到账号密码登录",
"initTitle": "首次使用,创建管理员账号",
"usernamePlaceholder": "3–32 位字母、数字或下划线",
"passwordPlaceholder": "设置登录密码",
"confirmPlaceholder": "再次输入密码",
"allowRegistration": "允许其他用户注册",
"migrateSubmit": "完成迁移",
"initSubmit": "创建并进入",
"migrateSuccess": "账号迁移完成",
"initSuccess": "初始化完成"
},
"register": {
"title": "注册账号",
"subtitle": "创建 PicHost 用户账号"
},
"password": {
"title": "修改密码",
"subtitle": "修改您的登录密码",
"current": "当前密码",
"new": "新密码",
"confirmNew": "确认新密码",
"newPlaceholder": "设置新密码",
"changed": "密码已修改",
"tooShort": "新密码至少 8 位",
"changeFailed": "修改密码失败",
"strength": "密码强度",
"weak": "弱",
"medium": "中",
"strong": "强",
"ruleMinLength": "至少 {n} 个字符",
"ruleMixedCase": "包含大小写字母",
"ruleNumber": "包含数字",
"ruleSpecial": "包含特殊字符"
},
"upload": {
"title": "拖拽图片到此处上传",
"hint": "或点击选择文件,按 {ctrl} + {v} 粘贴图片",
"formats": "支持 JPEG / PNG / WebP / GIF / SVG / ICO,单张最大 10 MB,每次最多 10 张",
"selectFiles": "选择图片",
"settings": "上传设置",
"progress": "上传进度",
"statusPending": "等待",
"statusUploading": "上传中",
"statusSuccess": "成功",
"statusError": "失败",
"selectImages": "请选择图片",
"maxFiles": "每次最多上传 {n} 张图片",
"uploadSuccess": "成功上传 {n} 张图片",
"uploadPartialFail": "{n} 张图片上传失败",
"uploadFailed": "上传失败",
"loginRequired": "请先登录",
"sessionTitle": "本次上传",
"sessionEmpty": "暂无本次上传"
},
"copy": {
"url": "直链",
"markdown": "Markdown",
"html": "HTML",
"copied": "已复制到剪贴板",
"copiedLabel": "已复制 {label}",
"copiedUrl": "已复制直链",
"copiedMarkdown": "已复制 Markdown",
"copiedHtml": "已复制 HTML",
"copiedFormat": "已复制 {format}",
"failed": "复制失败",
"failedManual": "复制失败,请手动选中链接复制",
"curl": "已复制 cURL 示例"
},
"preferences": {
"title": "上传偏好",
"subtitle": "浏览器本地与账号设置,仅影响您的上传体验",
"back": "返回上传",
"processing": "图片处理",
"clientCompress": "客户端预压缩",
"clientCompressHint": "上传前在浏览器端压缩(服务端仍会转 WebP)",
"autoDeletePrefix": "自动删除超过",
"autoDeleteSuffix": "天的图片",
"autoDeleteHint": "仅清理开启后上传的图片,不影响此前已存的图片",
"webpQuality": "WebP 压缩质量",
"webpQualityHint": "客户端预压缩质量(1–100),需开启「客户端预压缩」",
"current": "当前:{n}",
"qualityHigh": "高质量",
"qualityMedium": "中等质量",
"qualityLow": "有损压缩",
"convenience": "便捷功能",
"autoCopy": "上传成功自动复制链接",
"autoCopyHint": "按所选格式复制到剪贴板"
},
"settings": {
"title": "系统设置",
"subtitle": "保存后写入数据库;环境变量优先级更高",
"uploadAccount": "上传与账号",
"defaultFolder": "默认上传目录",
"defaultFolderHint": "保存在本机浏览器,仅影响您的上传目标目录",
"allowRegistration": "开放用户注册",
"allowRegistrationHint": "允许新用户自行注册(普通用户仅可见自己的图片)",
"accessControl": "访问控制",
"refererHint": "Referer 防盗链,逗号分隔允许引用的域名,留空不限制",
"refererPlaceholder": "example.com, www.example.com",
"linkGeneration": "链接生成",
"imageBaseUrlHint": "生成图片链接的 URL 前缀,内网访问建议填公网域名",
"imageBaseUrlPlaceholder": "https://pic.example.com",
"imageBaseUrlActive": "当前生效:{url}",
"badgeEnv": ".env",
"badgeSaved": "已保存",
"badgeDefault": "默认",
"badgeUnset": "未设置",
"tokenEnv": "环境变量",
"tokenDb": "后台生成",
"tokenNone": "未配置",
"apiTokenLine": "API Token · {source} · v{version}",
"unsavedChanges": "有未保存的更改",
"manageToken": "管理 Token",
"envOverride": "该项已由环境变量覆盖,无法在后台修改",
"saved": "服务器配置已保存",
"saveFailed": "保存服务器配置失败",
"loadFailed": "加载设置失败"
},
"stats": {
"title": "统计",
"subtitle": "数据概览与图库记录",
"uploadToday": "今日上传",
"uploadMonth": "本月上传",
"uploadTotal": "累计上传",
"storedCount": "当前库存",
"deleteToday": "今日删除",
"deleteMonth": "本月删除",
"deleteTotal": "累计删除",
"userCount": "注册用户数量",
"uploadBytes": "累计上传体积",
"folderDistribution": "上传目录分布",
"folderUsage": "目录占用",
"noData": "暂无数据",
"folderCount": "{count} 张 · {size}",
"gallery": "图库记录",
"folder": "目录",
"searchPlaceholder": "搜索文件名",
"clear": "清除",
"selected": "已选 {n}",
"batchDelete": "批量删除",
"scrollTop": "回到顶部",
"loadFailed": "加载统计失败",
"selectFirst": "请先选择图片",
"deleted": "已删除 {n} 张图片",
"deletePartialFail": "{n} 张图片删除失败",
"deleteFailed": "删除失败",
"deletedSingle": "已删除",
"allFolders": "全部",
"counting": "统计中…",
"summarySearch": "{folder} · 搜索「{q}」· 共 {total} 张",
"summaryTotal": "{folder} · 共 {total} 张"
},
"image": {
"empty": "暂无图片",
"previewFailed": "预览失败",
"uploader": "上传者:{name}"
},
"delete": {
"confirmTitle": "确认删除",
"confirmDesc": "确定要删除选中的 {count} 张图片吗?此操作不可恢复。",
"confirm": "确认删除"
},
"pagination": {
"pageOf": "第 {page} / {totalPages} 页 · 共 {total} {unit}",
"totalOnly": "共 {total} {unit}",
"first": "第一页",
"prev": "上一页",
"next": "下一页",
"last": "最后一页"
},
"api": {
"tokenTitle": "API Token",
"envOverrideTitle": "Token 由环境变量覆盖",
"envOverrideDesc": "修改 API_UPLOAD_TOKEN 后需重启服务;后台无法重新生成。",
"personalTitle": "个人 API Token",
"personalDesc": "此 Token 仅用于您自己的脚本上传,上传的图片归属您的账号。",
"notConfiguredTitle": "尚未配置 Token",
"notConfiguredDesc": "点击「重新生成」创建 Token,用于下方所有接口的 Auth-Token 鉴权。",
"regenerate": "重新生成",
"tokenSourceEnv": "来源:环境变量 API_UPLOAD_TOKEN",
"tokenSourceDb": "来源:后台生成(可重新生成)",
"tokenSourceNone": "来源:未配置",
"tokenHeader": "请求头:",
"tokenInvalidate": "重新生成后旧 Token 立即失效",
"docsTitle": "API 文档",
"curlExample": "cURL 示例",
"loadFailed": "加载 API 设置失败",
"regenerateEnvBlocked": "环境变量已配置 Token,无法在后台重新生成",
"regenerateFailed": "重新生成 Token 失败",
"confirmRegenerateTitle": "确认重新生成 Token?",
"confirmRegenerateDesc": "旧 Token 将立即失效,使用旧 Token 的脚本与自动化任务将无法继续调用接口,直到你更新为新 Token。",
"confirmRegenerate": "确认重新生成",
"newTokenTitle": "新 Token 已生成",
"newTokenDesc": "请立即复制保存。关闭弹窗后仍可在上方输入框复制,但请尽快更新到你的脚本配置中。",
"copyToken": "复制 Token",
"saved": "我已保存",
"docs": {
"upload": {
"title": "上传图片",
"descAdmin": "上传单张或多张图片。字段 image 传图片,folder 指定目录(不存在则自动创建);仍兼容 file、files、type。",
"descUser": "上传单张或多张图片。字段 image 传图片;仍兼容 file、files。图片固定存入 images/ 目录。"
},
"list": {
"title": "获取图片列表",
"descAdmin": "分页列出图库,folder 可筛选目录,limit 默认 20、最大 100。",
"descUser": "分页列出您的图库,limit 默认 20、最大 100。"
},
"search": {
"title": "搜索图片",
"desc": "按文件名或路径关键词搜索,参数 q 必填。"
},
"delete": {
"title": "删除图片",
"desc": "通过 key 删除单张图片,key 为存储路径(如 images/2026/08/xxx.webp)。"
},
"batchDelete": {
"title": "批量删除",
"desc": "一次删除多张图片,请求体为 keys 数组。"
},
"twikoo": {
"title": "twikoo 兼容上传",
"desc": "兼容 Twikoo / EasyImage 2.0 协议,图片存入 twikoo/ 目录;字段 image + token。"
}
}
},
"userSettings": {
"loadFailed": "加载设置失败",
"saveFailed": "保存设置失败"
}
}
+16 -1
View File
@@ -11,7 +11,8 @@ const pkg = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf8')) as {
export default defineNuxtConfig({
modules: [
'@nuxt/eslint',
'@nuxt/ui'
'@nuxt/ui',
'@nuxtjs/i18n'
],
devtools: {
@@ -49,5 +50,19 @@ export default defineNuxtConfig({
braceStyle: '1tbs'
}
}
},
i18n: {
locales: [
{ code: 'zh-CN', name: '简体中文', language: 'zh-CN', file: 'zh-CN.json' },
{ code: 'en', name: 'English', language: 'en', file: 'en.json' }
],
defaultLocale: 'zh-CN',
langDir: 'locales',
strategy: 'no_prefix',
detectBrowserLanguage: {
cookieKey: 'pic_locale',
fallbackLocale: 'zh-CN'
}
}
})
+1948 -88
View File
File diff suppressed because it is too large. Load diff
+4 -3
View File
@@ -1,6 +1,6 @@
{
"name": "pichost",
"version": "1.0.1",
"version": "1.0.4",
"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.",
"homepage": "https://github.com/O96u/PicHost#readme",
"repository": {
@@ -32,12 +32,13 @@
"typecheck": "nuxt typecheck",
"test": "vitest run",
"test:watch": "vitest",
"start": "node .output/server/index.mjs"
"start": "node .output/server/index.mjs",
"reset-password": "node server/cli/reset-password.mjs"
},
"dependencies": {
"@iconify-json/lucide": "^1.2.114",
"@nuxt/ui": "^4.9.0",
"jose": "^6.0.11",
"@nuxtjs/i18n": "^10.6.0",
"nuxt": "^4.4.8",
"sharp": "^0.35.3",
"tailwindcss": "^4.3.1"
+56
View File
@@ -0,0 +1,56 @@
import { mkdirSync } from 'node:fs'
import { join } from 'node:path'
import { randomBytes, scryptSync } from 'node:crypto'
import { DatabaseSync } from 'node:sqlite'
const usernameArg = process.argv[2]?.trim() || ''
if (process.argv.length > 3) {
console.error('Usage: reset-password [username]')
process.exit(1)
}
const dataDir = process.env.DATA_DIR || join(process.cwd(), 'data')
mkdirSync(dataDir, { recursive: true })
const db = new DatabaseSync(join(dataDir, 'pichost.db'))
function fail(message) {
console.error(`Error: ${message}`)
process.exit(1)
}
let user
if (usernameArg) {
user = db.prepare(`
SELECT id, username, role
FROM users
WHERE username = ?
`).get(usernameArg)
if (!user) fail(`user "${usernameArg}" not found`)
} else {
const admins = db.prepare(`
SELECT id, username, role
FROM users
WHERE role = 'admin'
ORDER BY id ASC
`).all()
if (!admins.length) fail('no administrator account found')
if (admins.length > 1) {
const names = admins.map(row => row.username).join(', ')
fail(`multiple administrators (${names}); run: reset-password <username>`)
}
user = admins[0]
}
const password = randomBytes(9).toString('base64url')
const salt = randomBytes(16).toString('hex')
const derived = scryptSync(password, salt, 64, { N: 16384, r: 8, p: 1 })
const passwordHash = `scrypt$16384$8$1$${salt}$${derived.toString('hex')}`
db.prepare('UPDATE users SET password_hash = ? WHERE id = ?').run(passwordHash, user.id)
db.prepare('DELETE FROM sessions WHERE user_id = ?').run(user.id)
db.close()
console.log(`[PicHost] User "${user.username}" (${user.role}) password reset.`)
console.log(`[PicHost] New password: ${password}`)
console.log('[PicHost] Sign in and change it under Account.')
+1 -1
View File
@@ -3,6 +3,6 @@ import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
include: ['server/**/*.test.ts']
include: ['server/**/*.test.ts', 'scripts/**/*.test.ts']
}
})