mirror of
https://git.fightbot.fun/hxuanyu/FileRelay.git
synced 2026-02-15 07:31:44 +08:00
Initial commit
This commit is contained in:
20
.dockerignore
Normal file
20
.dockerignore
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
.git
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
bin
|
||||||
|
obj
|
||||||
|
output
|
||||||
|
logs
|
||||||
|
storage_data
|
||||||
|
*.db
|
||||||
|
*.exe
|
||||||
|
*.tar.gz
|
||||||
|
docker-compose.yaml
|
||||||
|
Dockerfile
|
||||||
|
.dockerignore
|
||||||
|
README.md
|
||||||
|
README_en.md
|
||||||
|
scripts/
|
||||||
|
webapp/node_modules
|
||||||
|
webapp/dist
|
||||||
|
web
|
||||||
37
.github/workflows/build.yml
vendored
Normal file
37
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
name: Build
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "master" ]
|
||||||
|
pull_request:
|
||||||
|
branches: [ "master" ]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build Check
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.24'
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: webapp/package-lock.json
|
||||||
|
|
||||||
|
- name: Build Frontend
|
||||||
|
run: |
|
||||||
|
cd webapp
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
- name: Build Go
|
||||||
|
run: go build -v .
|
||||||
46
.github/workflows/docker-publish.yml
vendored
Normal file
46
.github/workflows/docker-publish.yml
vendored
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
name: Docker Publish
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build-and-push:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
environment: prod
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v3
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
|
||||||
|
- name: Login to Docker Hub
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
username: ${{ secrets.DOCKER_HUB_USERNAME }}
|
||||||
|
password: ${{ secrets.DOCKER_HUB_TOKEN }}
|
||||||
|
|
||||||
|
- name: Extract metadata (tags, labels) for Docker
|
||||||
|
id: meta
|
||||||
|
uses: docker/metadata-action@v5
|
||||||
|
with:
|
||||||
|
images: ${{ secrets.DOCKER_HUB_USERNAME }}/filerelay
|
||||||
|
tags: |
|
||||||
|
type=ref,event=tag
|
||||||
|
type=raw,value=latest
|
||||||
|
|
||||||
|
- name: Build and push Docker image
|
||||||
|
uses: docker/build-push-action@v6
|
||||||
|
with:
|
||||||
|
context: .
|
||||||
|
push: true
|
||||||
|
tags: ${{ steps.meta.outputs.tags }}
|
||||||
|
labels: ${{ steps.meta.outputs.labels }}
|
||||||
|
platforms: linux/amd64,linux/arm64
|
||||||
|
cache-from: type=gha
|
||||||
|
cache-to: type=gha,mode=max
|
||||||
45
.github/workflows/release.yml
vendored
Normal file
45
.github/workflows/release.yml
vendored
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
release:
|
||||||
|
name: Build and Release
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
|
||||||
|
- name: Set up Go
|
||||||
|
uses: actions/setup-go@v5
|
||||||
|
with:
|
||||||
|
go-version: '1.24'
|
||||||
|
cache: true
|
||||||
|
|
||||||
|
- name: Set up Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: '20'
|
||||||
|
cache: 'npm'
|
||||||
|
cache-dependency-path: webapp/package-lock.json
|
||||||
|
|
||||||
|
- name: Build Multi-Platform
|
||||||
|
run: |
|
||||||
|
chmod +x scripts/build.sh
|
||||||
|
./scripts/build.sh
|
||||||
|
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
files: output/*.tar.gz
|
||||||
|
generate_release_notes: true
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
87
.gitignore
vendored
Normal file
87
.gitignore
vendored
Normal file
@@ -0,0 +1,87 @@
|
|||||||
|
# =========================
|
||||||
|
# Go 常用 .gitignore
|
||||||
|
# =========================
|
||||||
|
|
||||||
|
# 编译产物 / 可执行文件
|
||||||
|
*.exe
|
||||||
|
*.exe~
|
||||||
|
*.dll
|
||||||
|
*.so
|
||||||
|
*.dylib
|
||||||
|
*.a
|
||||||
|
*.o
|
||||||
|
*.out
|
||||||
|
*.test
|
||||||
|
*.prof
|
||||||
|
*.pprof
|
||||||
|
*.cover
|
||||||
|
*.cov
|
||||||
|
*.trace
|
||||||
|
|
||||||
|
# Go workspace / 依赖缓存(本地开发常见,不建议入库)
|
||||||
|
/bin/
|
||||||
|
/pkg/
|
||||||
|
/dist/
|
||||||
|
/build/
|
||||||
|
/out/
|
||||||
|
|
||||||
|
# Go build cache(通常不需要忽略;如你有需要可开启)
|
||||||
|
# /tmp/
|
||||||
|
# /cache/
|
||||||
|
|
||||||
|
# 调试/日志/临时文件
|
||||||
|
*.log
|
||||||
|
*.tmp
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
*.bak
|
||||||
|
*.old
|
||||||
|
*.pid
|
||||||
|
|
||||||
|
# 运行时数据/本地数据
|
||||||
|
*.db
|
||||||
|
*.sqlite
|
||||||
|
*.sqlite3
|
||||||
|
data/
|
||||||
|
tmp/
|
||||||
|
|
||||||
|
# 环境变量与配置(按需:如果你会提交示例配置,建议仅忽略真实配置文件)
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
!.env.example
|
||||||
|
config.local.*
|
||||||
|
*.local.yaml
|
||||||
|
*.local.yml
|
||||||
|
*.local.json
|
||||||
|
|
||||||
|
# Go 测试覆盖率
|
||||||
|
coverage.out
|
||||||
|
cover.out
|
||||||
|
|
||||||
|
# vendor(Go Modules 通常不提交 vendor;如你需要 vendor 则删除这一行)
|
||||||
|
/vendor/
|
||||||
|
|
||||||
|
# 工具生成文件
|
||||||
|
*.gen.go
|
||||||
|
|
||||||
|
# IDE / 编辑器
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.code-workspace
|
||||||
|
|
||||||
|
# macOS / Windows
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
desktop.ini
|
||||||
|
|
||||||
|
# Vim / Emacs
|
||||||
|
*~
|
||||||
|
\#*\#
|
||||||
|
.\#*
|
||||||
|
|
||||||
|
# GoLand/IntelliJ
|
||||||
|
*.iml
|
||||||
|
/storage_data/
|
||||||
|
/logs/
|
||||||
|
/output/
|
||||||
|
/web/
|
||||||
50
Dockerfile
Normal file
50
Dockerfile
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
# Frontend build stage
|
||||||
|
FROM node:20-alpine AS frontend-builder
|
||||||
|
ARG NPM_REGISTRY
|
||||||
|
# 如果设置了 NPM_REGISTRY,则配置 npm 镜像
|
||||||
|
RUN if [ -n "$NPM_REGISTRY" ]; then npm config set registry $NPM_REGISTRY; fi
|
||||||
|
|
||||||
|
WORKDIR /webapp
|
||||||
|
# 仅拷贝包定义文件以利用缓存
|
||||||
|
COPY webapp/package*.json ./
|
||||||
|
RUN npm ci
|
||||||
|
# 拷贝前端源码并构建
|
||||||
|
COPY webapp/ ./
|
||||||
|
RUN npm run build
|
||||||
|
|
||||||
|
# Backend build stage
|
||||||
|
FROM golang:1.24-alpine AS builder
|
||||||
|
ARG GOPROXY
|
||||||
|
ENV GOPROXY=$GOPROXY
|
||||||
|
WORKDIR /app
|
||||||
|
# 仅拷贝依赖文件以利用缓存
|
||||||
|
COPY go.mod go.sum ./
|
||||||
|
RUN go mod download
|
||||||
|
# 拷贝后端源码(不包含 webapp)
|
||||||
|
COPY internal/ ./internal/
|
||||||
|
COPY main.go .
|
||||||
|
COPY docs/ ./docs/
|
||||||
|
# 从前端构建阶段拷贝产物到 web 目录(Go embed 需要)
|
||||||
|
COPY --from=frontend-builder /web ./web
|
||||||
|
# 编译二进制,移除调试信息并进行静态链接优化
|
||||||
|
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o filerelay main.go
|
||||||
|
|
||||||
|
# Final stage
|
||||||
|
FROM alpine:3.21
|
||||||
|
WORKDIR /app
|
||||||
|
# 合并指令以减少层数,安装必要包并创建所需目录
|
||||||
|
RUN apk add --no-cache ca-certificates mailcap && \
|
||||||
|
mkdir -p config data/storage_data data/logs
|
||||||
|
# 仅拷贝编译后的二进制文件,前端资源已通过 Go embed 包含在内
|
||||||
|
COPY --from=builder /app/filerelay .
|
||||||
|
|
||||||
|
EXPOSE 8080
|
||||||
|
# 合并环境变量定义
|
||||||
|
ENV FR_SITE_PORT=8080 \
|
||||||
|
FR_STORAGE_LOCAL_PATH=data/storage_data \
|
||||||
|
FR_DB_TYPE=sqlite \
|
||||||
|
FR_DB_PATH=data/file_relay.db \
|
||||||
|
FR_LOG_LEVEL=info \
|
||||||
|
FR_LOG_FILE_PATH=data/logs/app.log
|
||||||
|
|
||||||
|
CMD ["./filerelay"]
|
||||||
167
README.md
Normal file
167
README.md
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
# FileRelay - 文件暂存柜
|
||||||
|
|
||||||
|
[](https://github.com/hanxuanyu/FileRelay/actions/workflows/build.yml)
|
||||||
|
[](https://github.com/hanxuanyu/FileRelay/actions/workflows/release.yml)
|
||||||
|
[](https://github.com/hanxuanyu/FileRelay/actions/workflows/docker-publish.yml)
|
||||||
|
|
||||||
|
中文 | [English](README_en.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
FileRelay 是一个简单高效、自托管的文件暂存柜系统,旨在为您提供便捷的临时文件分享和中转服务。
|
||||||
|
|
||||||
|
### 🚀 主要特性
|
||||||
|
|
||||||
|
- **临时分享**:上传文件或文本,生成唯一取件码,方便在不同设备间快速传输。
|
||||||
|
- **多数据库支持**:支持 SQLite, MySQL 和 PostgreSQL,默认为 SQLite 开箱即用,生产环境可无缝切换至 MySQL 或 PostgreSQL。
|
||||||
|
- **多种存储后端**:支持本地磁盘存储、Amazon S3(及兼容 S3 的服务)以及 WebDAV 存储。
|
||||||
|
- **灵活的过期策略**:支持按时间过期和按下载次数过期(需在管理后台配置或手动清理)。
|
||||||
|
- **取件保护**:支持自定义取件码长度,内置尝试次数限制防暴力破解。
|
||||||
|
- **管理后台**:内置美观的管理界面,支持:
|
||||||
|
- 动态修改系统配置。
|
||||||
|
- 实时查看和管理上传批次。
|
||||||
|
- API Token 管理(支持权限细分:上传、取件、管理)。
|
||||||
|
- **高性能**:采用 Go 语言编写,内存占用极低,支持高并发访问。
|
||||||
|
- **易于部署**:支持单一二进制文件运行,前端资源已嵌入,无需额外配置 Web 服务器。
|
||||||
|
|
||||||
|
### 🛠️ 技术栈
|
||||||
|
|
||||||
|
- **后端**: Go 1.24+ (Gin, GORM)
|
||||||
|
- **数据库**: SQLite, MySQL, PostgreSQL (支持多种数据库,灵活扩展)
|
||||||
|
- **前端**: Vue 3 + TailwindCSS (位于 `webapp` 目录),已通过 `embed` 嵌入二进制。
|
||||||
|
- **文档**: 集成 Swagger UI。
|
||||||
|
|
||||||
|
### 🏗️ 开发与构建
|
||||||
|
|
||||||
|
#### 环境要求
|
||||||
|
|
||||||
|
- **Go**: 1.24 或更高版本
|
||||||
|
- **Node.js**: 20 或更高版本 (用于前端构建)
|
||||||
|
- **npm**: 随 Node.js 安装
|
||||||
|
|
||||||
|
#### 本地开发
|
||||||
|
|
||||||
|
1. **前端开发**:
|
||||||
|
```bash
|
||||||
|
cd webapp
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
前端开发服务器默认运行在 `http://localhost:5173`。
|
||||||
|
|
||||||
|
2. **后端开发**:
|
||||||
|
```bash
|
||||||
|
# 返回项目根目录
|
||||||
|
go run main.go -config config/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 完整构建
|
||||||
|
|
||||||
|
项目提供了自动化的构建脚本,会自动完成前端构建、资源嵌入以及 Go 编译:
|
||||||
|
|
||||||
|
- **Windows (CMD)**: `scripts\build.bat`
|
||||||
|
- **Windows (PowerShell)**: `.\scripts\build.ps1`
|
||||||
|
- **Linux/macOS**: `chmod +x scripts/build.sh && ./scripts/build.sh`
|
||||||
|
|
||||||
|
构建产物将存放在 `output` 目录下。
|
||||||
|
|
||||||
|
### 📦 快速开始
|
||||||
|
|
||||||
|
#### 1. 获取程序
|
||||||
|
|
||||||
|
您可以从 Release 页面下载对应平台的二进制文件,或者按照上述“完整构建”步骤自行编译。
|
||||||
|
|
||||||
|
#### 2. 配置文件
|
||||||
|
|
||||||
|
在运行之前,请根据需求修改 `config/config.yaml`。详细配置说明请参考 [docs/config_specification.md](docs/config_specification.md)。
|
||||||
|
|
||||||
|
主要配置项包括:
|
||||||
|
- 存储类型 (`local`, `s3`, `webdav`)。
|
||||||
|
- 管理员密码哈希。
|
||||||
|
- 数据库配置 (`type`, `host`, `port`, `user`, `password`, `dbname` 等)。系统支持自动迁移,首次连接新数据库时将自动创建表结构。此外,`scripts/sql/` 目录下也提供了各数据库的初始化 SQL 脚本供参考。
|
||||||
|
|
||||||
|
#### 3. 运行
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./filerelay -config config/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🐳 Docker 部署
|
||||||
|
|
||||||
|
我们提供了 Docker 和 Docker Compose 支持,实现一键部署:
|
||||||
|
|
||||||
|
#### 使用 Docker 镜像 (推荐)
|
||||||
|
|
||||||
|
如果您不想自行构建,可以直接从 Docker Hub 拉取已构建好的镜像:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d \
|
||||||
|
--name filerelay \
|
||||||
|
-p 8080:8080 \
|
||||||
|
-v $(pwd)/data:/app/data \
|
||||||
|
-v $(pwd)/config:/app/config \
|
||||||
|
hxuanyu521/filerelay:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
**提示:**
|
||||||
|
- 如果您需要使用自定义的 Web 页面(外置前端资源),可以将资源目录挂载到容器内,并通过环境变量 `FR_WEB_PATH` 指定路径。例如:
|
||||||
|
`-v $(pwd)/my-web:/app/my-web -e FR_WEB_PATH=/app/my-web`
|
||||||
|
- 默认情况下,程序会优先寻找 `FR_WEB_PATH`(或配置文件中的 `web.path`)指定的外部资源,若找不到则使用内置的嵌入资源。
|
||||||
|
|
||||||
|
#### 使用 Docker Compose
|
||||||
|
|
||||||
|
1. 确保已安装 Docker 和 Docker Compose。
|
||||||
|
2. 在项目根目录下运行:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
程序默认会在当前目录下的 `./data` 文件夹中持久化存储数据、日志、数据库和配置。
|
||||||
|
|
||||||
|
#### 环境变量控制
|
||||||
|
|
||||||
|
支持通过环境变量覆盖配置文件中的关键项,方便在 Docker 环境下动态调整:
|
||||||
|
|
||||||
|
| 环境变量 | 说明 | 默认值 |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **站点设置** | | |
|
||||||
|
| `FR_SITE_NAME` | 站点名称 | 文件暂存柜 |
|
||||||
|
| `FR_SITE_BASE_URL` | 站点外部访问地址 (用于生成分享链接) | (空) |
|
||||||
|
| `FR_SITE_PORT` | 服务监听端口 | 8080 |
|
||||||
|
| **安全设置** | | |
|
||||||
|
| `FR_SECURITY_JWT_SECRET` | JWT 签名密钥 | file-relay-secret |
|
||||||
|
| **上传设置** | | |
|
||||||
|
| `FR_UPLOAD_MAX_SIZE` | 单个文件最大大小 (MB) | 100 |
|
||||||
|
| `FR_UPLOAD_RETENTION_DAYS` | 文件最大保留天数 | 30 |
|
||||||
|
| **数据库设置** | | |
|
||||||
|
| `FR_DB_TYPE` | 数据库类型 (sqlite, mysql, postgres) | sqlite |
|
||||||
|
| `FR_DB_PATH` | SQLite 数据库文件路径 | data/file_relay.db |
|
||||||
|
| `FR_DB_HOST` | 数据库主机地址 (MySQL/Postgres) | (空) |
|
||||||
|
| `FR_DB_PORT` | 数据库端口 (MySQL/Postgres) | (空) |
|
||||||
|
| `FR_DB_USER` | 数据库用户名 (MySQL/Postgres) | (空) |
|
||||||
|
| `FR_DB_PASSWORD` | 数据库密码 (MySQL/Postgres) | (空) |
|
||||||
|
| `FR_DB_NAME` | 数据库名称 (MySQL/Postgres) | (空) |
|
||||||
|
| **存储设置** | | |
|
||||||
|
| `FR_STORAGE_TYPE` | 存储类型 (local, s3, webdav) | local |
|
||||||
|
| `FR_STORAGE_LOCAL_PATH` | 本地存储路径 | data/storage_data |
|
||||||
|
| **日志设置** | | |
|
||||||
|
| `FR_LOG_LEVEL` | 日志级别 (debug, info, warn, error) | info |
|
||||||
|
| `FR_LOG_FILE_PATH` | 日志文件路径 | data/logs/app.log |
|
||||||
|
| **Web 设置** | | |
|
||||||
|
| `FR_WEB_PATH` | 外部 Web 静态资源路径 | web |
|
||||||
|
|
||||||
|
程序启动后,您可以通过以下地址访问(默认端口 8080):
|
||||||
|
- **Web 界面**: `http://localhost:8080`
|
||||||
|
- **管理后台**: `http://localhost:8080/admin` (前端路由)
|
||||||
|
- **API 文档**: `http://localhost:8080/swagger/index.html`
|
||||||
|
|
||||||
|
### 📖 接口说明
|
||||||
|
|
||||||
|
FileRelay 提供了丰富的 API 接口,支持通过 API Token 进行集成。
|
||||||
|
|
||||||
|
- **上传**: `POST /api/batches`
|
||||||
|
- **取件**: `GET /api/batches/:pickup_code`
|
||||||
|
- **下载**: `GET /api/files/:file_id/download`
|
||||||
|
|
||||||
|
详细接口定义请参考内置的 Swagger 文档。
|
||||||
167
README_en.md
Normal file
167
README_en.md
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
# FileRelay - File Relay Station
|
||||||
|
|
||||||
|
[](https://github.com/hanxuanyu/FileRelay/actions/workflows/build.yml)
|
||||||
|
[](https://github.com/hanxuanyu/FileRelay/actions/workflows/release.yml)
|
||||||
|
[](https://github.com/hanxuanyu/FileRelay/actions/workflows/docker-publish.yml)
|
||||||
|
|
||||||
|
[中文](README.md) | English
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
FileRelay is a simple, efficient, self-hosted file relay/temporary storage system designed to provide convenient temporary file sharing and transfer services.
|
||||||
|
|
||||||
|
### 🚀 Key Features
|
||||||
|
|
||||||
|
- **Temporary Sharing**: Upload files or text and generate a unique pickup code for quick transfer across different devices.
|
||||||
|
- **Multi-database Support**: Supports SQLite, MySQL, and PostgreSQL. Defaults to SQLite for out-of-the-box use, with seamless switching to MySQL or PostgreSQL for production.
|
||||||
|
- **Multiple Storage Backends**: Supports local disk storage, Amazon S3 (and S3-compatible services), and WebDAV.
|
||||||
|
- **Flexible Expiration**: Supports expiration by time and download counts (configurable in admin or via manual cleanup).
|
||||||
|
- **Pickup Protection**: Customizable pickup code length and built-in rate limiting to prevent brute-force attacks.
|
||||||
|
- **Admin Dashboard**: Built-in management interface for:
|
||||||
|
- Dynamic system configuration updates.
|
||||||
|
- Real-time batch management (view, delete, clean).
|
||||||
|
- API Token management with granular scopes (upload, pickup, admin).
|
||||||
|
- **High Performance**: Written in Go with low memory footprint and high concurrency support.
|
||||||
|
- **Easy Deployment**: Single binary execution with embedded frontend assets, no extra Web server needed.
|
||||||
|
|
||||||
|
### 🛠️ Tech Stack
|
||||||
|
|
||||||
|
- **Backend**: Go 1.24+ (Gin, GORM)
|
||||||
|
- **Database**: SQLite, MySQL, PostgreSQL (supports multiple databases for scalability)
|
||||||
|
- **Frontend**: Vue 3 + TailwindCSS (located in `webapp` directory), embedded into binary via `embed`.
|
||||||
|
- **Documentation**: Integrated Swagger UI.
|
||||||
|
|
||||||
|
### 🏗️ Development & Build
|
||||||
|
|
||||||
|
#### Prerequisites
|
||||||
|
|
||||||
|
- **Go**: 1.24 or higher
|
||||||
|
- **Node.js**: 20 or higher (for frontend build)
|
||||||
|
- **npm**: Installed with Node.js
|
||||||
|
|
||||||
|
#### Local Development
|
||||||
|
|
||||||
|
1. **Frontend**:
|
||||||
|
```bash
|
||||||
|
cd webapp
|
||||||
|
npm install
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
The frontend dev server runs at `http://localhost:5173` by default.
|
||||||
|
|
||||||
|
2. **Backend**:
|
||||||
|
```bash
|
||||||
|
# Go back to the project root
|
||||||
|
go run main.go -config config/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Full Build
|
||||||
|
|
||||||
|
The project provides automated build scripts that handle frontend building, asset embedding, and Go compilation:
|
||||||
|
|
||||||
|
- **Windows (CMD)**: `scripts\build.bat`
|
||||||
|
- **Windows (PowerShell)**: `.\scripts\build.ps1`
|
||||||
|
- **Linux/macOS**: `chmod +x scripts/build.sh && ./scripts/build.sh`
|
||||||
|
|
||||||
|
The build artifacts will be stored in the `output` directory.
|
||||||
|
|
||||||
|
### 📦 Quick Start
|
||||||
|
|
||||||
|
#### 1. Get the Program
|
||||||
|
|
||||||
|
Download the binary for your platform from the Release page, or build it yourself using the "Full Build" steps above.
|
||||||
|
|
||||||
|
#### 2. Configuration
|
||||||
|
|
||||||
|
Modify `config/config.yaml` before running. See [docs/config_specification.md](docs/config_specification.md) for detailed field descriptions.
|
||||||
|
|
||||||
|
Key settings:
|
||||||
|
- Storage type (`local`, `s3`, `webdav`).
|
||||||
|
- Admin password hash.
|
||||||
|
- Database configuration (`type`, `host`, `port`, `user`, `password`, `dbname`, etc.). The system supports auto-migration and will create tables automatically on the first connection. Manual SQL scripts are also available in the `scripts/sql/` directory.
|
||||||
|
|
||||||
|
#### 3. Running
|
||||||
|
|
||||||
|
```bash
|
||||||
|
./filerelay -config config/config.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🐳 Docker Deployment
|
||||||
|
|
||||||
|
We provide Docker and Docker Compose support for one-click deployment:
|
||||||
|
|
||||||
|
#### Using Docker Image (Recommended)
|
||||||
|
|
||||||
|
If you don't want to build it yourself, you can pull the pre-built image from Docker Hub:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker run -d \
|
||||||
|
--name filerelay \
|
||||||
|
-p 8080:8080 \
|
||||||
|
-v $(pwd)/data:/app/data \
|
||||||
|
-v $(pwd)/config:/app/config \
|
||||||
|
hxuanyu521/filerelay:latest
|
||||||
|
```
|
||||||
|
|
||||||
|
**Tips:**
|
||||||
|
- If you need to use custom Web pages (external frontend assets), you can mount the assets directory into the container and specify the path via the `FR_WEB_PATH` environment variable. For example:
|
||||||
|
`-v $(pwd)/my-web:/app/my-web -e FR_WEB_PATH=/app/my-web`
|
||||||
|
- By default, the program will first look for external assets specified by `FR_WEB_PATH` (or `web.path` in the config file), and fallback to embedded assets if not found.
|
||||||
|
|
||||||
|
#### Using Docker Compose
|
||||||
|
|
||||||
|
1. Ensure Docker and Docker Compose are installed.
|
||||||
|
2. Run in the project root:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker-compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, data, logs, database, and configuration will be persisted in the `./data` folder in the current directory.
|
||||||
|
|
||||||
|
#### Environment Variables
|
||||||
|
|
||||||
|
You can override key configuration items using environment variables, which is convenient for dynamic adjustments in Docker:
|
||||||
|
|
||||||
|
| Env Var | Description | Default |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **Site Settings** | | |
|
||||||
|
| `FR_SITE_NAME` | Site Name | 文件暂存柜 |
|
||||||
|
| `FR_SITE_BASE_URL` | Site Base URL (for sharing links) | (empty) |
|
||||||
|
| `FR_SITE_PORT` | Service Port | 8080 |
|
||||||
|
| **Security Settings** | | |
|
||||||
|
| `FR_SECURITY_JWT_SECRET` | JWT Secret | file-relay-secret |
|
||||||
|
| **Upload Settings** | | |
|
||||||
|
| `FR_UPLOAD_MAX_SIZE` | Max File Size (MB) | 100 |
|
||||||
|
| `FR_UPLOAD_RETENTION_DAYS` | Max Retention Days | 30 |
|
||||||
|
| **Database Settings** | | |
|
||||||
|
| `FR_DB_TYPE` | DB Type (sqlite, mysql, postgres) | sqlite |
|
||||||
|
| `FR_DB_PATH` | SQLite DB Path | data/file_relay.db |
|
||||||
|
| `FR_DB_HOST` | DB Host (MySQL/Postgres) | (empty) |
|
||||||
|
| `FR_DB_PORT` | DB Port (MySQL/Postgres) | (empty) |
|
||||||
|
| `FR_DB_USER` | DB User (MySQL/Postgres) | (empty) |
|
||||||
|
| `FR_DB_PASSWORD` | DB Password (MySQL/Postgres) | (empty) |
|
||||||
|
| `FR_DB_NAME` | DB Name (MySQL/Postgres) | (empty) |
|
||||||
|
| **Storage Settings** | | |
|
||||||
|
| `FR_STORAGE_TYPE` | Storage Type (local, s3, webdav) | local |
|
||||||
|
| `FR_STORAGE_LOCAL_PATH` | Local Storage Path | data/storage_data |
|
||||||
|
| **Log Settings** | | |
|
||||||
|
| `FR_LOG_LEVEL` | Log Level (debug, info, warn, error) | info |
|
||||||
|
| `FR_LOG_FILE_PATH` | Log File Path | data/logs/app.log |
|
||||||
|
| **Web Settings** | | |
|
||||||
|
| `FR_WEB_PATH` | External Web Assets Path | web |
|
||||||
|
|
||||||
|
Access via:
|
||||||
|
- **Web UI**: `http://localhost:8080`
|
||||||
|
- **Admin Panel**: `http://localhost:8080/admin`
|
||||||
|
- **API Docs**: `http://localhost:8080/swagger/index.html`
|
||||||
|
|
||||||
|
### 📖 API Reference
|
||||||
|
|
||||||
|
FileRelay provides a rich set of APIs for integration via API Tokens.
|
||||||
|
|
||||||
|
- **Upload**: `POST /api/batches`
|
||||||
|
- **Pickup**: `GET /api/batches/:pickup_code`
|
||||||
|
- **Download**: `GET /api/files/:file_id/download`
|
||||||
|
|
||||||
|
Refer to the built-in Swagger documentation for details.
|
||||||
60
config/config.yaml
Normal file
60
config/config.yaml
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
site:
|
||||||
|
name: 文件暂存柜
|
||||||
|
description: 临时文件中转服务
|
||||||
|
logo: /favicon.png
|
||||||
|
base_url: ""
|
||||||
|
port: 8080
|
||||||
|
security:
|
||||||
|
admin_password_hash: $2a$10$Bm0TEmU4uj.bVHYiIPFBheUkcdg6XHpsanLvmpoAtgU1UnKbo9.vy
|
||||||
|
pickup_code_length: 6
|
||||||
|
pickup_fail_limit: 5
|
||||||
|
jwt_secret: file-relay-secret
|
||||||
|
upload:
|
||||||
|
max_file_size_mb: 100
|
||||||
|
max_batch_files: 20
|
||||||
|
max_retention_days: 30
|
||||||
|
require_token: true
|
||||||
|
storage:
|
||||||
|
type: local
|
||||||
|
local:
|
||||||
|
path: data/storage_data
|
||||||
|
webdav:
|
||||||
|
url: https://dav.example.com
|
||||||
|
username: user
|
||||||
|
password: pass
|
||||||
|
root: /file-relay
|
||||||
|
s3:
|
||||||
|
endpoint: s3.amazonaws.com
|
||||||
|
region: us-east-1
|
||||||
|
access_key: your-access-key
|
||||||
|
secret_key: your-secret-key
|
||||||
|
bucket: file-relay-bucket
|
||||||
|
use_ssl: false
|
||||||
|
api_token:
|
||||||
|
enabled: true
|
||||||
|
allow_admin_api: true
|
||||||
|
max_tokens: 20
|
||||||
|
database:
|
||||||
|
type: sqlite
|
||||||
|
path: data/file_relay.db
|
||||||
|
# mysql 示例:
|
||||||
|
# type: mysql
|
||||||
|
# host: 127.0.0.1
|
||||||
|
# port: 3306
|
||||||
|
# user: root
|
||||||
|
# password: password
|
||||||
|
# dbname: file_relay
|
||||||
|
# config: charset=utf8mb4&parseTime=True&loc=Local
|
||||||
|
# postgres 示例:
|
||||||
|
# type: postgres
|
||||||
|
# host: 127.0.0.1
|
||||||
|
# port: 5432
|
||||||
|
# user: postgres
|
||||||
|
# password: password
|
||||||
|
# dbname: file_relay
|
||||||
|
# config: sslmode=disable
|
||||||
|
web:
|
||||||
|
path: web
|
||||||
|
log:
|
||||||
|
level: debug
|
||||||
|
file_path: data/logs/app.log
|
||||||
23
docker-compose.yaml
Normal file
23
docker-compose.yaml
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
services:
|
||||||
|
filerelay:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
args:
|
||||||
|
- GOPROXY=${GOPROXY:-https://proxy.golang.org,direct}
|
||||||
|
- NPM_REGISTRY=${NPM_REGISTRY:-https://registry.npmjs.org/}
|
||||||
|
image: filerelay:latest
|
||||||
|
container_name: filerelay
|
||||||
|
ports:
|
||||||
|
- "${HOST_PORT:-8080}:${FR_SITE_PORT:-8080}"
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
|
- ./data/config:/app/config
|
||||||
|
environment:
|
||||||
|
- TZ=${TZ:-Asia/Shanghai}
|
||||||
|
- FR_SITE_NAME=${FR_SITE_NAME:-文件暂存柜}
|
||||||
|
- FR_SITE_PORT=${FR_SITE_PORT:-8080}
|
||||||
|
- FR_LOG_LEVEL=${FR_LOG_LEVEL:-info}
|
||||||
|
- FR_DB_PATH=${FR_DB_PATH:-data/file_relay.db}
|
||||||
|
- FR_STORAGE_LOCAL_PATH=${FR_STORAGE_LOCAL_PATH:-data/storage_data}
|
||||||
|
- FR_LOG_FILE_PATH=${FR_LOG_FILE_PATH:-data/logs/app.log}
|
||||||
|
restart: unless-stopped
|
||||||
143
docs/config_specification.md
Normal file
143
docs/config_specification.md
Normal file
@@ -0,0 +1,143 @@
|
|||||||
|
# FileRelay 配置项详细说明文档
|
||||||
|
|
||||||
|
本文档整理了 FileRelay 系统 `config.yaml` 配置文件中各字段的含义、类型及示例,供前端配置页面开发参考。
|
||||||
|
|
||||||
|
## 1. 站点设置 (site)
|
||||||
|
用于定义前端展示的站点基本信息。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `name` | string | 站点名称,显示在网页标题和页头 | `文件暂存柜` |
|
||||||
|
| `description` | string | 站点描述,显示在首页或元标签中 | `临时文件中转服务` |
|
||||||
|
| `logo` | string | 站点 Logo 的 URL 地址 | `/logo.png` |
|
||||||
|
| `base_url` | string | 站点外部访问地址。若配置则固定使用该地址拼接直链;若留空,系统将尝试从请求头(如 `X-Forwarded-Proto`, `:scheme`, `Forwarded` 等)或 `Referer` 中自动检测协议及主机名,以确保在 HTTPS 代理环境下链接正确。 | `https://file.example.com` |
|
||||||
|
| `port` | int | 后端服务监听端口 | `8080` |
|
||||||
|
|
||||||
|
## 2. 安全设置 (security)
|
||||||
|
涉及系统鉴权、取件保护相关的核心安全配置。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `admin_password_hash` | string | 管理员密码的 bcrypt 哈希值。可以通过更新配置接口修改,修改后立即生效,且不再依赖数据库存储。 | `$2a$10$...` |
|
||||||
|
| `pickup_code_length` | int | 自动生成的取件码长度。变更后系统将自动对存量取件码进行右侧补零或截取以适配新长度。 | `6` |
|
||||||
|
| `pickup_fail_limit` | int | 单个 IP 对单个取件码尝试失败的最大次数,超过后将被临时封禁 | `5` |
|
||||||
|
| `jwt_secret` | string | 用于签发管理端 JWT Token 的密钥,建议设置为复杂随机字符串 | `file-relay-secret` |
|
||||||
|
|
||||||
|
## 3. 上传设置 (upload)
|
||||||
|
控制文件上传的限制和策略。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `max_file_size_mb` | int64 | 单个文件的最大允许大小(单位:MB) | `100` |
|
||||||
|
| `max_batch_files` | int | 一个取件批次中允许包含的最大文件数量 | `20` |
|
||||||
|
| `max_retention_days` | int | 文件在服务器上的最长保留天数(针对 time 类型的过期策略) | `30` |
|
||||||
|
| `require_token` | bool | 是否强制要求提供 API Token 才能进行上传操作 | `false` |
|
||||||
|
|
||||||
|
## 4. 存储设置 (storage)
|
||||||
|
定义文件的实际物理存储方式。系统支持多种存储后端。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `type` | string | 当前激活的存储类型。可选值:`local`, `webdav`, `s3` | `local` |
|
||||||
|
|
||||||
|
### 4.1 本地存储 (local)
|
||||||
|
当 `type` 为 `local` 时生效。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `path` | string | 文件存储在服务器本地的相对或绝对路径 | `data/storage_data` |
|
||||||
|
|
||||||
|
### 4.2 WebDAV 存储 (webdav)
|
||||||
|
当 `type` 为 `webdav` 时生效。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `url` | string | WebDAV 服务器的 API 地址 | `https://dav.example.com` |
|
||||||
|
| `username` | string | WebDAV 登录用户名 | `user` |
|
||||||
|
| `password` | string | WebDAV 登录密码 | `pass` |
|
||||||
|
| `root` | string | WebDAV 上的基础存储根目录 | `/file-relay` |
|
||||||
|
|
||||||
|
### 4.3 S3 存储 (s3)
|
||||||
|
当 `type` 为 `s3` 时生效。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `endpoint` | string | S3 服务端点 | `s3.amazonaws.com` |
|
||||||
|
| `region` | string | S3 区域 | `us-east-1` |
|
||||||
|
| `access_key` | string | S3 Access Key | `your-access-key` |
|
||||||
|
| `secret_key` | string | S3 Secret Key | `your-secret-key` |
|
||||||
|
| `bucket` | string | S3 存储桶名称 | `file-relay-bucket` |
|
||||||
|
| `use_ssl` | bool | 是否强制使用 SSL (HTTPS) 连接 | `false` |
|
||||||
|
|
||||||
|
## 5. API Token 设置 (api_token)
|
||||||
|
控制系统对外开放的 API Token 管理功能。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `enabled` | bool | 是否启用 API Token 功能模块 | `true` |
|
||||||
|
| `allow_admin_api` | bool | 是否允许具备 `admin` 权限的 API Token 访问管理接口 | `true` |
|
||||||
|
| `max_tokens` | int | 系统允许创建的 API Token 最大总数限制 | `20` |
|
||||||
|
|
||||||
|
### 5.1 API Token 权限说明 (Scopes)
|
||||||
|
在创建 API Token 时,可以通过 `scope` 字段赋予以下一种或多种权限(多个权限用逗号分隔,如 `upload,pickup`):
|
||||||
|
|
||||||
|
| 权限值 | 含义 | 说明 |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `upload` | 上传权限 | 允许调用文件和长文本上传接口 |
|
||||||
|
| `pickup` | 取件权限 | 允许获取批次详情、下载文件及查询下载次数 |
|
||||||
|
| `admin` | 管理权限 | 允许访问管理端(Admin)所有接口。需开启 `allow_admin_api` 且 Token 功能已启用 |
|
||||||
|
|
||||||
|
## 6. Web 前端设置 (web)
|
||||||
|
定义前端静态资源的加载方式。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `path` | string | 外部前端资源目录路径。若该路径存在且包含 `index.html`,系统将优先使用此目录;否则回退使用内置前端资源。 | `web` |
|
||||||
|
|
||||||
|
## 7. 数据库设置 (database)
|
||||||
|
系统元数据存储配置。支持 SQLite, MySQL 和 PostgreSQL。
|
||||||
|
|
||||||
|
**特性说明**:
|
||||||
|
- **动态切换**:通过管理接口更新数据库配置后,系统会自动尝试连接新数据库,无需重启应用。
|
||||||
|
- **自动迁移**:切换数据库时,系统会自动将原数据库中的元数据(如存量批次、文件记录、API Token 等)同步迁移至新数据库中。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `type` | string | 数据库类型。可选值:`sqlite`, `mysql`, `postgres` | `sqlite` |
|
||||||
|
| `path` | string | SQLite 数据库文件的路径 (仅在 `type` 为 `sqlite` 时生效) | `data/file_relay.db` |
|
||||||
|
| `host` | string | 数据库地址 (MySQL/PostgreSQL) | `127.0.0.1` |
|
||||||
|
| `port` | int | 数据库端口 (MySQL/PostgreSQL) | `3306` 或 `5432` |
|
||||||
|
| `user` | string | 数据库用户名 (MySQL/PostgreSQL) | `root` |
|
||||||
|
| `password` | string | 数据库密码 (MySQL/PostgreSQL) | `password` |
|
||||||
|
| `dbname` | string | 数据库名称 (MySQL/PostgreSQL) | `file_relay` |
|
||||||
|
| `config` | string | 额外 DSN 配置参数。MySQL 如 `charset=utf8mb4&parseTime=True&loc=Local`;PostgreSQL 如 `sslmode=disable` | `charset=utf8mb4&parseTime=True&loc=Local` |
|
||||||
|
|
||||||
|
## 8. 日志设置 (log)
|
||||||
|
控制系统日志的输出级别和目的地。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `level` | string | 日志级别。可选值:`debug`, `info`, `warn`, `error` | `info` |
|
||||||
|
| `file_path` | string | 日志文件路径。如果设置,日志将同时输出到控制台和该文件;若为空则仅输出到控制台。 | `data/logs/app.log` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录:公共配置接口 (/api/config)
|
||||||
|
|
||||||
|
为了方便前端展示和交互约束,系统提供了 `/api/config` 接口,该接口不需要鉴权,返回以下非敏感字段(结构与完整配置保持一致):
|
||||||
|
|
||||||
|
- **site**: 完整内容(`name`, `description`, `logo`, `base_url`)
|
||||||
|
- **security**: 仅包含 `pickup_code_length`
|
||||||
|
- **upload**: 完整内容(`max_file_size_mb`, `max_batch_files`, `max_retention_days`, `require_token`)
|
||||||
|
- **api_token**: 仅包含 `enabled` 开关
|
||||||
|
- **storage**: 仅包含 `type`(存储类型)
|
||||||
|
|
||||||
|
## 附录:其他关键接口
|
||||||
|
|
||||||
|
### 查询下载次数 (GET /api/batches/:pickup_code/count)
|
||||||
|
- **用途**:供前端实时刷新当前取件批次的下载次数。
|
||||||
|
- **特性**:支持查询已过期的文件。
|
||||||
|
|
||||||
|
### 恢复 API Token (POST /api/admin/api-tokens/:id/recover)
|
||||||
|
- **权限**:需要管理员权限。
|
||||||
|
- **用途**:将状态为“已撤销”的 Token 重新恢复为有效状态。
|
||||||
1738
docs/docs.go
Normal file
1738
docs/docs.go
Normal file
File diff suppressed because it is too large
Load Diff
1713
docs/swagger.json
Normal file
1713
docs/swagger.json
Normal file
File diff suppressed because it is too large
Load Diff
1076
docs/swagger.yaml
Normal file
1076
docs/swagger.yaml
Normal file
File diff suppressed because it is too large
Load Diff
102
go.mod
Normal file
102
go.mod
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
module FileRelay
|
||||||
|
|
||||||
|
go 1.24.0
|
||||||
|
|
||||||
|
toolchain go1.24.11
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.41.1
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.7
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.7
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.95.1
|
||||||
|
github.com/gin-contrib/cors v1.7.6
|
||||||
|
github.com/gin-gonic/gin v1.11.0
|
||||||
|
github.com/glebarez/sqlite v1.11.0
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
|
github.com/stretchr/testify v1.11.1
|
||||||
|
github.com/studio-b12/gowebdav v0.11.0
|
||||||
|
github.com/swaggo/files v1.0.1
|
||||||
|
github.com/swaggo/gin-swagger v1.6.1
|
||||||
|
github.com/swaggo/swag v1.16.6
|
||||||
|
golang.org/x/crypto v0.47.0
|
||||||
|
gopkg.in/yaml.v3 v3.0.1
|
||||||
|
gorm.io/driver/mysql v1.6.0
|
||||||
|
gorm.io/driver/postgres v1.6.0
|
||||||
|
gorm.io/gorm v1.31.1
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
filippo.io/edwards25519 v1.1.0 // indirect
|
||||||
|
github.com/KyleBanks/depth v1.2.1 // indirect
|
||||||
|
github.com/PuerkitoBio/purell v1.1.1 // indirect
|
||||||
|
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 // indirect
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 // indirect
|
||||||
|
github.com/aws/smithy-go v1.24.0 // indirect
|
||||||
|
github.com/bytedance/sonic v1.14.0 // indirect
|
||||||
|
github.com/bytedance/sonic/loader v0.3.0 // indirect
|
||||||
|
github.com/cloudwego/base64x v0.1.6 // indirect
|
||||||
|
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||||
|
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.9 // indirect
|
||||||
|
github.com/gin-contrib/sse v1.1.0 // indirect
|
||||||
|
github.com/glebarez/go-sqlite v1.21.2 // indirect
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.5 // indirect
|
||||||
|
github.com/go-openapi/jsonreference v0.19.6 // indirect
|
||||||
|
github.com/go-openapi/spec v0.20.4 // indirect
|
||||||
|
github.com/go-openapi/swag v0.19.15 // indirect
|
||||||
|
github.com/go-playground/locales v0.14.1 // indirect
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||||
|
github.com/go-playground/validator/v10 v10.27.0 // indirect
|
||||||
|
github.com/go-sql-driver/mysql v1.8.1 // indirect
|
||||||
|
github.com/goccy/go-json v0.10.5 // indirect
|
||||||
|
github.com/goccy/go-yaml v1.18.0 // indirect
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||||
|
github.com/jackc/pgx/v5 v5.6.0 // indirect
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||||
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
|
github.com/josharian/intern v1.0.0 // indirect
|
||||||
|
github.com/json-iterator/go v1.1.12 // indirect
|
||||||
|
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||||
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
|
github.com/mailru/easyjson v0.7.6 // indirect
|
||||||
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||||
|
github.com/quic-go/qpack v0.5.1 // indirect
|
||||||
|
github.com/quic-go/quic-go v0.54.0 // indirect
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||||
|
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||||
|
github.com/ugorji/go/codec v1.3.0 // indirect
|
||||||
|
go.uber.org/mock v0.5.0 // indirect
|
||||||
|
golang.org/x/arch v0.20.0 // indirect
|
||||||
|
golang.org/x/mod v0.31.0 // indirect
|
||||||
|
golang.org/x/net v0.48.0 // indirect
|
||||||
|
golang.org/x/sync v0.19.0 // indirect
|
||||||
|
golang.org/x/sys v0.40.0 // indirect
|
||||||
|
golang.org/x/text v0.33.0 // indirect
|
||||||
|
golang.org/x/tools v0.40.0 // indirect
|
||||||
|
google.golang.org/protobuf v1.36.9 // indirect
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 // indirect
|
||||||
|
modernc.org/libc v1.22.5 // indirect
|
||||||
|
modernc.org/mathutil v1.5.0 // indirect
|
||||||
|
modernc.org/memory v1.5.0 // indirect
|
||||||
|
modernc.org/sqlite v1.23.1 // indirect
|
||||||
|
)
|
||||||
257
go.sum
Normal file
257
go.sum
Normal file
@@ -0,0 +1,257 @@
|
|||||||
|
filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA=
|
||||||
|
filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4=
|
||||||
|
github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc=
|
||||||
|
github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE=
|
||||||
|
github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI=
|
||||||
|
github.com/PuerkitoBio/purell v1.1.1/go.mod h1:c11w/QuzBsJSee3cPx9rAFu61PvFxuPbtSwDGJws/X0=
|
||||||
|
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M=
|
||||||
|
github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdkoq3SwY9Y+13GIhn11/XLaGBb4BfwItxLd5jeuXE=
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.41.1 h1:ABlyEARCDLN034NhxlRUSZr4l71mh+T5KAeGh6cerhU=
|
||||||
|
github.com/aws/aws-sdk-go-v2 v1.41.1/go.mod h1:MayyLB8y+buD9hZqkCW3kX1AKq07Y5pXxtgB+rRFhz0=
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 h1:489krEF9xIGkOaaX3CE/Be2uWjiXrkCH6gUX+bZA/BU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4/go.mod h1:IOAPF6oT9KCsceNTvvYMNHy0+kMF8akOjeDvPENWxp4=
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.7 h1:vxUyWGUwmkQ2g19n7JY/9YL8MfAIl7bTesIUykECXmY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/config v1.32.7/go.mod h1:2/Qm5vKUU/r7Y+zUk/Ptt2MDAEKAfUtKc1+3U1Mo3oY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.7 h1:tHK47VqqtJxOymRrNtUXN5SP/zUTvZKeLx4tH6PGQc8=
|
||||||
|
github.com/aws/aws-sdk-go-v2/credentials v1.19.7/go.mod h1:qOZk8sPDrxhf+4Wf4oT2urYJrYt3RejHSzgAquYeppw=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17 h1:I0GyV8wiYrP8XpA70g1HBcQO1JlQxCMTW9npl5UbDHY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.17/go.mod h1:tyw7BOl5bBe/oqvoIeECFJjMdzXoa/dfVz3QQ5lgHGA=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17 h1:xOLELNKGp2vsiteLsvLPwxC+mYmO6OZ8PYgiuPJzF8U=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.17/go.mod h1:5M5CI3D12dNOtH3/mk6minaRwI2/37ifCURZISxA/IQ=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17 h1:WWLqlh79iO48yLkj1v3ISRNiv+3KdQoZ6JWyfcsyQik=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.17/go.mod h1:EhG22vHRrvF8oXSTYStZhJc1aUgKtnJe+aOiFEV90cM=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4 h1:WKuaxf++XKWlHWu9ECbMlha8WOEGm0OUEZqm4K/Gcfk=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.4/go.mod h1:ZWy7j6v1vWGmPReu0iSGvRiise4YI5SkR3OHKTZ6Wuc=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17 h1:JqcdRG//czea7Ppjb+g/n4o8i/R50aTBHkA7vu0lK+k=
|
||||||
|
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.17/go.mod h1:CO+WeGmIdj/MlPel2KwID9Gt7CNq4M65HUfBW97liM0=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4 h1:0ryTNEdJbzUCEWkVXEXoqlXV72J5keC1GvILMOuD00E=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.4/go.mod h1:HQ4qwNZh32C3CBeO6iJLQlgtMzqeG17ziAA/3KDJFow=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8 h1:Z5EiPIzXKewUQK0QTMkutjiaPVeVYXX7KIqhXu/0fXs=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.8/go.mod h1:FsTpJtvC4U1fyDXk7c71XoDv3HlRm8V3NiYLeYLh5YE=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17 h1:RuNSMoozM8oXlgLG/n6WLaFGoea7/CddrCfIiSA+xdY=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.17/go.mod h1:F2xxQ9TZz5gDWsclCtPQscGpP0VUOc8RqgFM3vDENmU=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17 h1:bGeHBsGZx0Dvu/eJC0Lh9adJa3M1xREcndxLNZlve2U=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.17/go.mod h1:dcW24lbU0CzHusTE8LLHhRLI42ejmINN8Lcr22bwh/g=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.95.1 h1:C2dUPSnEpy4voWFIq3JNd8gN0Y5vYGDo44eUE58a/p8=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/s3 v1.95.1/go.mod h1:5jggDlZ2CLQhwJBiZJb4vfk4f0GxWdEDruWKEJ1xOdo=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.0.5 h1:VrhDvQib/i0lxvr3zqlUwLwJP4fpmpyD9wYG1vfSu+Y=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/signin v1.0.5/go.mod h1:k029+U8SY30/3/ras4G/Fnv/b88N4mAfliNn08Dem4M=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.30.9 h1:v6EiMvhEYBoHABfbGB4alOYmCIrcgyPPiBE1wZAEbqk=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sso v1.30.9/go.mod h1:yifAsgBxgJWn3ggx70A3urX2AN49Y5sJTD1UQFlfqBw=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13 h1:gd84Omyu9JLriJVCbGApcLzVR3XtmC4ZDPcAI6Ftvds=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.13/go.mod h1:sTGThjphYE4Ohw8vJiRStAcu3rbjtXRsdNB0TvZ5wwo=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.41.6 h1:5fFjR/ToSOzB2OQ/XqWpZBmNvmP/pJ1jOWYlFDJTjRQ=
|
||||||
|
github.com/aws/aws-sdk-go-v2/service/sts v1.41.6/go.mod h1:qgFDZQSD/Kys7nJnVqYlWKnh0SSdMjAi0uSwON4wgYQ=
|
||||||
|
github.com/aws/smithy-go v1.24.0 h1:LpilSUItNPFr1eY85RYgTIg5eIEPtvFbskaFcmmIUnk=
|
||||||
|
github.com/aws/smithy-go v1.24.0/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=
|
||||||
|
github.com/bytedance/sonic v1.14.0 h1:/OfKt8HFw0kh2rj8N0F6C/qPGRESq0BbaNZgcNXXzQQ=
|
||||||
|
github.com/bytedance/sonic v1.14.0/go.mod h1:WoEbx8WTcFJfzCe0hbmyTGrfjt8PzNEBdxlNUO24NhA=
|
||||||
|
github.com/bytedance/sonic/loader v0.3.0 h1:dskwH8edlzNMctoruo8FPTJDF3vLtDT0sXZwvZJyqeA=
|
||||||
|
github.com/bytedance/sonic/loader v0.3.0/go.mod h1:N8A3vUdtUebEY2/VQC0MyhYeKUFosQU6FxH2JmUe6VI=
|
||||||
|
github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M=
|
||||||
|
github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU=
|
||||||
|
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||||
|
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||||
|
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.9 h1:5k+WDwEsD9eTLL8Tz3L0VnmVh9QxGjRmjBvAG7U/oYY=
|
||||||
|
github.com/gabriel-vasile/mimetype v1.4.9/go.mod h1:WnSQhFKJuBlRyLiKohA/2DtIlPFAbguNaG7QCHcyGok=
|
||||||
|
github.com/gin-contrib/cors v1.7.6 h1:3gQ8GMzs1Ylpf70y8bMw4fVpycXIeX1ZemuSQIsnQQY=
|
||||||
|
github.com/gin-contrib/cors v1.7.6/go.mod h1:Ulcl+xN4jel9t1Ry8vqph23a60FwH9xVLd+3ykmTjOk=
|
||||||
|
github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4=
|
||||||
|
github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk=
|
||||||
|
github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w=
|
||||||
|
github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM=
|
||||||
|
github.com/gin-gonic/gin v1.11.0 h1:OW/6PLjyusp2PPXtyxKHU0RbX6I/l28FTdDlae5ueWk=
|
||||||
|
github.com/gin-gonic/gin v1.11.0/go.mod h1:+iq/FyxlGzII0KHiBGjuNn4UNENUlKbGlNmc+W50Dls=
|
||||||
|
github.com/glebarez/go-sqlite v1.21.2 h1:3a6LFC4sKahUunAmynQKLZceZCOzUthkRkEAl9gAXWo=
|
||||||
|
github.com/glebarez/go-sqlite v1.21.2/go.mod h1:sfxdZyhQjTM2Wry3gVYWaW072Ri1WMdWJi0k6+3382k=
|
||||||
|
github.com/glebarez/sqlite v1.11.0 h1:wSG0irqzP6VurnMEpFGer5Li19RpIRi2qvQz++w0GMw=
|
||||||
|
github.com/glebarez/sqlite v1.11.0/go.mod h1:h8/o8j5wiAsqSPoWELDUdJXhjAhsVliSn7bWZjOhrgQ=
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.3/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.5 h1:gZr+CIYByUqjcgeLXnQu2gHYQC9o73G2XUeOFYEICuY=
|
||||||
|
github.com/go-openapi/jsonpointer v0.19.5/go.mod h1:Pl9vOtqEWErmShwVjC8pYs9cog34VGT37dQOVbmoatg=
|
||||||
|
github.com/go-openapi/jsonreference v0.19.6 h1:UBIxjkht+AWIgYzCDSv2GN+E/togfwXUJFRTWhl2Jjs=
|
||||||
|
github.com/go-openapi/jsonreference v0.19.6/go.mod h1:diGHMEHg2IqXZGKxqyvWdfWU/aim5Dprw5bqpKkTvns=
|
||||||
|
github.com/go-openapi/spec v0.20.4 h1:O8hJrt0UMnhHcluhIdUgCLRWyM2x7QkBXRvOs7m+O1M=
|
||||||
|
github.com/go-openapi/spec v0.20.4/go.mod h1:faYFR1CvsJZ0mNsmsphTMSoRrNV3TEDoAM7FOEWeq8I=
|
||||||
|
github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk=
|
||||||
|
github.com/go-openapi/swag v0.19.15 h1:D2NRCBzS9/pEY3gP9Nl8aDqGUcPFrwG2p+CNFrLyrCM=
|
||||||
|
github.com/go-openapi/swag v0.19.15/go.mod h1:QYRuS/SOXUCsnplDa677K7+DxSOj6IPNl/eQntq43wQ=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
|
||||||
|
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
|
||||||
|
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||||
|
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||||
|
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||||
|
github.com/go-playground/validator/v10 v10.27.0 h1:w8+XrWVMhGkxOaaowyKH35gFydVHOvC0/uWoy2Fzwn4=
|
||||||
|
github.com/go-playground/validator/v10 v10.27.0/go.mod h1:I5QpIEbmr8On7W0TktmJAumgzX4CA1XNl4ZmDuVHKKo=
|
||||||
|
github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y=
|
||||||
|
github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg=
|
||||||
|
github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=
|
||||||
|
github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=
|
||||||
|
github.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=
|
||||||
|
github.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
|
||||||
|
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
|
||||||
|
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||||
|
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||||
|
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||||
|
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ=
|
||||||
|
github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo=
|
||||||
|
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||||
|
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||||
|
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||||
|
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||||
|
github.com/jackc/pgx/v5 v5.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY=
|
||||||
|
github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||||
|
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||||
|
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||||
|
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||||
|
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||||
|
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||||
|
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
|
||||||
|
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
|
||||||
|
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||||
|
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||||
|
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||||
|
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
|
||||||
|
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
|
||||||
|
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||||
|
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||||
|
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||||
|
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||||
|
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||||
|
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||||
|
github.com/mailru/easyjson v0.0.0-20190614124828-94de47d64c63/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||||
|
github.com/mailru/easyjson v0.0.0-20190626092158-b2ccc519800e/go.mod h1:C1wdFJiN94OJF2b5HbByQZoLdCWB1Yqtg26g4irojpc=
|
||||||
|
github.com/mailru/easyjson v0.7.6 h1:8yTIVnZgCoiM1TgqoeTl+LfU5Jg6/xL3QhGQnimLYnA=
|
||||||
|
github.com/mailru/easyjson v0.7.6/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
|
||||||
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||||
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||||
|
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||||
|
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||||
|
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/quic-go/qpack v0.5.1 h1:giqksBPnT/HDtZ6VhtFKgoLOWmlyo9Ei6u9PqzIMbhI=
|
||||||
|
github.com/quic-go/qpack v0.5.1/go.mod h1:+PC4XFrEskIVkcLzpEkbLqq1uCoxPhQuvK5rH1ZgaEg=
|
||||||
|
github.com/quic-go/quic-go v0.54.0 h1:6s1YB9QotYI6Ospeiguknbp2Znb/jZYjZLRXn9kMQBg=
|
||||||
|
github.com/quic-go/quic-go v0.54.0/go.mod h1:e68ZEaCdyviluZmy44P6Iey98v/Wfz6HCjQEm+l8zTY=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||||
|
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||||
|
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
|
||||||
|
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
|
||||||
|
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||||
|
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||||
|
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||||
|
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||||
|
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
|
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||||
|
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||||
|
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||||
|
github.com/studio-b12/gowebdav v0.11.0 h1:qbQzq4USxY28ZYsGJUfO5jR+xkFtcnwWgitp4Zp1irU=
|
||||||
|
github.com/studio-b12/gowebdav v0.11.0/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE=
|
||||||
|
github.com/swaggo/files v1.0.1 h1:J1bVJ4XHZNq0I46UU90611i9/YzdrF7x92oX1ig5IdE=
|
||||||
|
github.com/swaggo/files v1.0.1/go.mod h1:0qXmMNH6sXNf+73t65aKeB+ApmgxdnkQzVTAj2uaMUg=
|
||||||
|
github.com/swaggo/gin-swagger v1.6.1 h1:Ri06G4gc9N4t4k8hekMigJ9zKTFSlqj/9paAQCQs7cY=
|
||||||
|
github.com/swaggo/gin-swagger v1.6.1/go.mod h1:LQ+hJStHakCWRiK/YNYtJOu4mR2FP+pxLnILT/qNiTw=
|
||||||
|
github.com/swaggo/swag v1.16.6 h1:qBNcx53ZaX+M5dxVyTrgQ0PJ/ACK+NzhwcbieTt+9yI=
|
||||||
|
github.com/swaggo/swag v1.16.6/go.mod h1:ngP2etMK5a0P3QBizic5MEwpRmluJZPHjXcMoj4Xesg=
|
||||||
|
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||||
|
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||||
|
github.com/ugorji/go/codec v1.3.0 h1:Qd2W2sQawAfG8XSvzwhBeoGq71zXOC/Q1E9y/wUcsUA=
|
||||||
|
github.com/ugorji/go/codec v1.3.0/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4=
|
||||||
|
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
||||||
|
go.uber.org/mock v0.5.0 h1:KAMbZvZPyBPWgD14IrIQ38QCyjwpvVVV6K/bHl1IwQU=
|
||||||
|
go.uber.org/mock v0.5.0/go.mod h1:ge71pBPLYDk7QIi1LupWxdAykm7KIEFchiOqd6z7qMM=
|
||||||
|
golang.org/x/arch v0.20.0 h1:dx1zTU0MAE98U+TQ8BLl7XsJbgze2WnNKF/8tGp/Q6c=
|
||||||
|
golang.org/x/arch v0.20.0/go.mod h1:bdwinDaKcfZUGpH09BB7ZmOfhalA8lQdzl62l8gGWsk=
|
||||||
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
|
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||||
|
golang.org/x/crypto v0.47.0 h1:V6e3FRj+n4dbpw86FJ8Fv7XVOql7TEwpHapKoMJ/GO8=
|
||||||
|
golang.org/x/crypto v0.47.0/go.mod h1:ff3Y9VzzKbwSSEzWqJsJVBnWmRwRSHt/6Op5n9bQc4A=
|
||||||
|
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||||
|
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||||
|
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||||
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
|
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
||||||
|
golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM=
|
||||||
|
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
||||||
|
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||||
|
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||||
|
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||||
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
|
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||||
|
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||||
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
|
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
|
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||||
|
golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
|
||||||
|
golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||||
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
||||||
|
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
|
||||||
|
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||||
|
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||||
|
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||||
|
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||||
|
golang.org/x/text v0.33.0 h1:B3njUFyqtHDUI5jMn1YIr5B0IE2U0qck04r6d4KPAxE=
|
||||||
|
golang.org/x/text v0.33.0/go.mod h1:LuMebE6+rBincTi9+xWTY8TztLzKHc/9C1uBCG27+q8=
|
||||||
|
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||||
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||||
|
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||||
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
|
google.golang.org/protobuf v1.36.9 h1:w2gp2mA27hUeUzj9Ex9FBjsBm40zfaDtEWow293U7Iw=
|
||||||
|
google.golang.org/protobuf v1.36.9/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||||
|
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||||
|
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||||
|
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||||
|
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
gorm.io/driver/mysql v1.6.0 h1:eNbLmNTpPpTOVZi8MMxCi2aaIm0ZpInbORNXDwyLGvg=
|
||||||
|
gorm.io/driver/mysql v1.6.0/go.mod h1:D/oCC2GWK3M/dqoLxnOlaNKmXz8WNTfcS9y5ovaSqKo=
|
||||||
|
gorm.io/driver/postgres v1.6.0 h1:2dxzU8xJ+ivvqTRph34QX+WrRaJlmfyPqXmoGVjMBa4=
|
||||||
|
gorm.io/driver/postgres v1.6.0/go.mod h1:vUw0mrGgrTK+uPHEhAdV4sfFELrByKVGnaVRkXDhtWo=
|
||||||
|
gorm.io/gorm v1.31.1 h1:7CA8FTFz/gRfgqgpeKIBcervUn3xSyPUmr6B2WXJ7kg=
|
||||||
|
gorm.io/gorm v1.31.1/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
|
||||||
|
modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE=
|
||||||
|
modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY=
|
||||||
|
modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ=
|
||||||
|
modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E=
|
||||||
|
modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds=
|
||||||
|
modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU=
|
||||||
|
modernc.org/sqlite v1.23.1 h1:nrSBg4aRQQwq59JpvGEQ15tNxoO5pX/kUjcRNwSAGQM=
|
||||||
|
modernc.org/sqlite v1.23.1/go.mod h1:OrDj17Mggn6MhE+iPbBNf7RGKODDE9NFT0f3EwDzJqk=
|
||||||
70
internal/api/admin/auth.go
Normal file
70
internal/api/admin/auth.go
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
package admin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/auth"
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AuthHandler struct{}
|
||||||
|
|
||||||
|
func NewAuthHandler() *AuthHandler {
|
||||||
|
return &AuthHandler{}
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoginRequest struct {
|
||||||
|
Password string `json:"password" binding:"required" example:"admin"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type LoginResponse struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Login 管理员登录
|
||||||
|
// @Summary 管理员登录
|
||||||
|
// @Description 通过密码换取 JWT Token
|
||||||
|
// @Tags Admin
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param request body LoginRequest true "登录请求"
|
||||||
|
// @Success 200 {object} model.Response{data=LoginResponse}
|
||||||
|
// @Failure 401 {object} model.Response
|
||||||
|
// @Router /api/admin/login [post]
|
||||||
|
func (h *AuthHandler) Login(c *gin.Context) {
|
||||||
|
var req LoginRequest
|
||||||
|
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "Invalid request"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
passwordHash := config.GlobalConfig.Security.AdminPasswordHash
|
||||||
|
if passwordHash == "" {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Admin password hash not configured"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := bcrypt.CompareHashAndPassword([]byte(passwordHash), []byte(req.Password)); err != nil {
|
||||||
|
slog.Warn("Failed admin login attempt", "ip", c.ClientIP())
|
||||||
|
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Incorrect password"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 使用固定 ID 1 代表管理员(因为不再有数据库记录)
|
||||||
|
token, err := auth.GenerateToken(1)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to generate admin token", "error", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Failed to generate token"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("Admin logged in", "ip", c.ClientIP())
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(LoginResponse{
|
||||||
|
Token: token,
|
||||||
|
}))
|
||||||
|
}
|
||||||
256
internal/api/admin/batch.go
Normal file
256
internal/api/admin/batch.go
Normal file
@@ -0,0 +1,256 @@
|
|||||||
|
package admin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/service"
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BatchHandler struct {
|
||||||
|
batchService *service.BatchService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBatchHandler() *BatchHandler {
|
||||||
|
return &BatchHandler{
|
||||||
|
batchService: service.NewBatchService(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type ListBatchesResponse struct {
|
||||||
|
Total int64 `json:"total"`
|
||||||
|
Page int `json:"page"`
|
||||||
|
PageSize int `json:"page_size"`
|
||||||
|
Data []model.FileBatch `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type UpdateBatchRequest struct {
|
||||||
|
Remark *string `json:"remark"`
|
||||||
|
ExpireType *string `json:"expire_type"`
|
||||||
|
ExpireAt *time.Time `json:"expire_at"`
|
||||||
|
MaxDownloads *int `json:"max_downloads"`
|
||||||
|
DownloadCount *int `json:"download_count"`
|
||||||
|
Status *string `json:"status"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListBatches 获取批次列表
|
||||||
|
// @Summary 获取批次列表
|
||||||
|
// @Description 分页查询所有文件批次,支持按状态过滤和取件码模糊搜索
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Param page query int false "页码 (默认 1)"
|
||||||
|
// @Param page_size query int false "每页数量 (默认 20)"
|
||||||
|
// @Param status query string false "状态 (active/expired/deleted)"
|
||||||
|
// @Param pickup_code query string false "取件码 (模糊搜索)"
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response{data=ListBatchesResponse}
|
||||||
|
// @Failure 401 {object} model.Response
|
||||||
|
// @Router /api/admin/batches [get]
|
||||||
|
func (h *BatchHandler) ListBatches(c *gin.Context) {
|
||||||
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||||
|
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||||
|
|
||||||
|
if page < 1 {
|
||||||
|
page = 1
|
||||||
|
}
|
||||||
|
if pageSize < 1 {
|
||||||
|
pageSize = 20
|
||||||
|
}
|
||||||
|
status := c.Query("status")
|
||||||
|
pickupCode := c.Query("pickup_code")
|
||||||
|
|
||||||
|
query := bootstrap.DB.Model(&model.FileBatch{})
|
||||||
|
if status != "" {
|
||||||
|
query = query.Where("status = ?", status)
|
||||||
|
}
|
||||||
|
if pickupCode != "" {
|
||||||
|
query = query.Where("pickup_code LIKE ?", "%"+pickupCode+"%")
|
||||||
|
}
|
||||||
|
|
||||||
|
var total int64
|
||||||
|
query.Count(&total)
|
||||||
|
|
||||||
|
var batches []model.FileBatch
|
||||||
|
err := query.Offset((page - 1) * pageSize).Limit(pageSize).Order("created_at DESC").Find(&batches).Error
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(ListBatchesResponse{
|
||||||
|
Total: total,
|
||||||
|
Page: page,
|
||||||
|
PageSize: pageSize,
|
||||||
|
Data: batches,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetBatch 获取批次详情
|
||||||
|
// @Summary 获取批次详情
|
||||||
|
// @Description 根据批次 ID 获取批次信息及关联的文件列表
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Param batch_id path string true "批次 ID (UUID)"
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response{data=model.FileBatch}
|
||||||
|
// @Failure 404 {object} model.Response
|
||||||
|
// @Router /api/admin/batches/{batch_id} [get]
|
||||||
|
func (h *BatchHandler) GetBatch(c *gin.Context) {
|
||||||
|
id := c.Param("batch_id")
|
||||||
|
var batch model.FileBatch
|
||||||
|
if err := bootstrap.DB.Preload("FileItems").First(&batch, "id = ?", id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "batch not found"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(batch))
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateBatch 修改批次信息
|
||||||
|
// @Summary 修改批次信息
|
||||||
|
// @Description 允许修改备注、过期策略、最大下载次数、状态等
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param batch_id path string true "批次 ID (UUID)"
|
||||||
|
// @Param request body UpdateBatchRequest true "修改内容"
|
||||||
|
// @Success 200 {object} model.Response{data=model.FileBatch}
|
||||||
|
// @Failure 400 {object} model.Response
|
||||||
|
// @Router /api/admin/batches/{batch_id} [put]
|
||||||
|
func (h *BatchHandler) UpdateBatch(c *gin.Context) {
|
||||||
|
id := c.Param("batch_id")
|
||||||
|
var batch model.FileBatch
|
||||||
|
if err := bootstrap.DB.First(&batch, "id = ?", id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "batch not found"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawBody, err := c.GetRawData()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "failed to read body"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.Request.Body = io.NopCloser(bytes.NewBuffer(rawBody))
|
||||||
|
|
||||||
|
var input UpdateBatchRequest
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var rawMap map[string]interface{}
|
||||||
|
json.Unmarshal(rawBody, &rawMap)
|
||||||
|
|
||||||
|
updates := make(map[string]interface{})
|
||||||
|
if input.Remark != nil {
|
||||||
|
updates["remark"] = *input.Remark
|
||||||
|
}
|
||||||
|
if input.ExpireType != nil {
|
||||||
|
newType := *input.ExpireType
|
||||||
|
updates["expire_type"] = newType
|
||||||
|
|
||||||
|
// 如果类型发生变化,根据新类型清除不相关的配置
|
||||||
|
if newType != batch.ExpireType {
|
||||||
|
if newType == "download" {
|
||||||
|
updates["expire_at"] = nil
|
||||||
|
} else if newType == "time" {
|
||||||
|
updates["max_downloads"] = 0
|
||||||
|
} else if newType == "permanent" {
|
||||||
|
updates["expire_at"] = nil
|
||||||
|
updates["max_downloads"] = 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 显式提供的值具有最高优先级,但仅在逻辑允许的情况下
|
||||||
|
// 例如:如果切换到了 download 类型,用户可以同时提供一个新的 max_downloads
|
||||||
|
if _, ok := rawMap["expire_at"]; ok {
|
||||||
|
updates["expire_at"] = input.ExpireAt
|
||||||
|
}
|
||||||
|
if input.MaxDownloads != nil {
|
||||||
|
updates["max_downloads"] = *input.MaxDownloads
|
||||||
|
}
|
||||||
|
|
||||||
|
// 强制校验:如果最终结果是 permanent,确保限制被清空
|
||||||
|
// 这样即使用户在请求中显式传了非零值,也会被修正
|
||||||
|
finalType := batch.ExpireType
|
||||||
|
if t, ok := updates["expire_type"].(string); ok {
|
||||||
|
finalType = t
|
||||||
|
}
|
||||||
|
|
||||||
|
if finalType == "permanent" {
|
||||||
|
updates["expire_at"] = nil
|
||||||
|
updates["max_downloads"] = 0
|
||||||
|
} else if finalType == "time" {
|
||||||
|
// 如果是时间过期,max_downloads 应该始终为 0
|
||||||
|
updates["max_downloads"] = 0
|
||||||
|
} else if finalType == "download" {
|
||||||
|
// 如果是下载次数过期,expire_at 应该始终为 null
|
||||||
|
updates["expire_at"] = nil
|
||||||
|
}
|
||||||
|
if input.DownloadCount != nil {
|
||||||
|
updates["download_count"] = *input.DownloadCount
|
||||||
|
}
|
||||||
|
if input.Status != nil {
|
||||||
|
updates["status"] = *input.Status
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(updates) > 0 {
|
||||||
|
if err := bootstrap.DB.Model(&batch).Updates(updates).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 重新从数据库读取,确保返回的是完整且最新的数据
|
||||||
|
bootstrap.DB.First(&batch, "id = ?", id)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(batch))
|
||||||
|
}
|
||||||
|
|
||||||
|
// CleanBatches 手动触发清理过期或已删除的批次
|
||||||
|
// @Summary 手动触发清理
|
||||||
|
// @Description 手动扫描并物理删除所有已过期或标记为删除的文件批次及其关联文件
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/admin/batches/clean [post]
|
||||||
|
func (h *BatchHandler) CleanBatches(c *gin.Context) {
|
||||||
|
slog.Info("Admin triggered manual cleanup")
|
||||||
|
if err := h.batchService.Cleanup(c.Request.Context()); err != nil {
|
||||||
|
slog.Error("Manual cleanup failed", "error", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "cleanup failed: "+err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteBatch 删除批次
|
||||||
|
// @Summary 删除批次
|
||||||
|
// @Description 标记批次为已删除,并物理删除关联的存储文件
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Param batch_id path string true "批次 ID (UUID)"
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/admin/batches/{batch_id} [delete]
|
||||||
|
func (h *BatchHandler) DeleteBatch(c *gin.Context) {
|
||||||
|
id := c.Param("batch_id")
|
||||||
|
|
||||||
|
if err := h.batchService.DeleteBatch(c.Request.Context(), id); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(map[string]interface{}{}))
|
||||||
|
}
|
||||||
107
internal/api/admin/config.go
Normal file
107
internal/api/admin/config.go
Normal file
@@ -0,0 +1,107 @@
|
|||||||
|
package admin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/service"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConfigHandler struct{}
|
||||||
|
|
||||||
|
func NewConfigHandler() *ConfigHandler {
|
||||||
|
return &ConfigHandler{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetConfig 获取当前完整配置
|
||||||
|
// @Summary 获取完整配置
|
||||||
|
// @Description 获取系统的完整配置文件内容(仅管理员)
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response{data=config.Config}
|
||||||
|
// @Router /api/admin/config [get]
|
||||||
|
func (h *ConfigHandler) GetConfig(c *gin.Context) {
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(config.GlobalConfig))
|
||||||
|
}
|
||||||
|
|
||||||
|
// UpdateConfig 更新配置
|
||||||
|
// @Summary 更新配置
|
||||||
|
// @Description 更新系统的配置文件内容(仅管理员)
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param config body config.Config true "新配置内容"
|
||||||
|
// @Success 200 {object} model.Response{data=config.Config}
|
||||||
|
// @Failure 400 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/admin/config [put]
|
||||||
|
func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
|
||||||
|
var newConfig config.Config
|
||||||
|
if err := c.ShouldBindJSON(&newConfig); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 简单的校验,防止关键配置被改空
|
||||||
|
if newConfig.Database.Path == "" {
|
||||||
|
newConfig.Database.Path = config.GlobalConfig.Database.Path
|
||||||
|
}
|
||||||
|
if newConfig.Site.Port <= 0 || newConfig.Site.Port > 65535 {
|
||||||
|
newConfig.Site.Port = 8080
|
||||||
|
}
|
||||||
|
|
||||||
|
// 如果传入了明文密码,则重新生成 hash
|
||||||
|
if newConfig.Security.AdminPassword != "" {
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(newConfig.Security.AdminPassword), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Failed to hash password: "+err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
newConfig.Security.AdminPasswordHash = string(hash)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查取件码长度是否变化
|
||||||
|
pickupCodeLengthChanged := newConfig.Security.PickupCodeLength != config.GlobalConfig.Security.PickupCodeLength && newConfig.Security.PickupCodeLength > 0
|
||||||
|
// 检查数据库配置是否变化
|
||||||
|
dbConfigChanged := newConfig.Database != config.GlobalConfig.Database
|
||||||
|
|
||||||
|
// 如果长度变化,同步更新现有取件码 (在可能切换数据库前,先处理旧库数据)
|
||||||
|
if pickupCodeLengthChanged {
|
||||||
|
batchService := service.NewBatchService()
|
||||||
|
if err := batchService.UpdateAllPickupCodes(newConfig.Security.PickupCodeLength); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Failed to update existing pickup codes: "+err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新内存配置
|
||||||
|
config.UpdateGlobalConfig(&newConfig)
|
||||||
|
|
||||||
|
// 重新连接数据库并迁移数据(如果配置发生变化)
|
||||||
|
if dbConfigChanged {
|
||||||
|
if err := bootstrap.ReloadDB(newConfig.Database); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Failed to reload database: "+err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重新初始化存储(热更新业务逻辑)
|
||||||
|
if err := bootstrap.ReloadStorage(); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Failed to reload storage: "+err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存到文件
|
||||||
|
if err := config.SaveConfig(); err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "Failed to save config: "+err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(config.GlobalConfig))
|
||||||
|
}
|
||||||
138
internal/api/admin/token.go
Normal file
138
internal/api/admin/token.go
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
package admin
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/service"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TokenHandler struct {
|
||||||
|
tokenService *service.TokenService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTokenHandler() *TokenHandler {
|
||||||
|
return &TokenHandler{
|
||||||
|
tokenService: service.NewTokenService(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateTokenRequest struct {
|
||||||
|
Name string `json:"name" binding:"required" example:"Test Token"`
|
||||||
|
Scope string `json:"scope" example:"upload,pickup" enums:"upload,pickup,admin"`
|
||||||
|
ExpireAt *time.Time `json:"expire_at"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateTokenResponse struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
Data *model.APIToken `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// ListTokens 获取 API Token 列表
|
||||||
|
// @Summary 获取 API Token 列表
|
||||||
|
// @Description 获取系统中所有 API Token 的详细信息(不包含哈希)
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response{data=[]model.APIToken}
|
||||||
|
// @Failure 401 {object} model.Response
|
||||||
|
// @Router /api/admin/api-tokens [get]
|
||||||
|
func (h *TokenHandler) ListTokens(c *gin.Context) {
|
||||||
|
var tokens []model.APIToken
|
||||||
|
if err := bootstrap.DB.Find(&tokens).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(tokens))
|
||||||
|
}
|
||||||
|
|
||||||
|
// CreateToken 创建 API Token
|
||||||
|
// @Summary 创建 API Token
|
||||||
|
// @Description 创建一个新的 API Token,返回原始 Token(仅显示一次)
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Param request body CreateTokenRequest true "Token 信息"
|
||||||
|
// @Success 201 {object} model.Response{data=CreateTokenResponse}
|
||||||
|
// @Failure 400 {object} model.Response
|
||||||
|
// @Router /api/admin/api-tokens [post]
|
||||||
|
func (h *TokenHandler) CreateToken(c *gin.Context) {
|
||||||
|
var input CreateTokenRequest
|
||||||
|
|
||||||
|
if err := c.ShouldBindJSON(&input); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
rawToken, token, err := h.tokenService.CreateToken(input.Name, input.Scope, input.ExpireAt)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusCreated, model.SuccessResponse(CreateTokenResponse{
|
||||||
|
Token: rawToken,
|
||||||
|
Data: token,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// RevokeToken 撤销 API Token
|
||||||
|
// @Summary 撤销 API Token
|
||||||
|
// @Description 将 API Token 标记为已撤销,使其失效但保留记录
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Param id path int true "Token ID"
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/admin/api-tokens/{id}/revoke [post]
|
||||||
|
func (h *TokenHandler) RevokeToken(c *gin.Context) {
|
||||||
|
id := c.Param("id")
|
||||||
|
if err := bootstrap.DB.Model(&model.APIToken{}).Where("id = ?", id).Update("revoked", true).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(map[string]interface{}{}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// RecoverToken 恢复 API Token
|
||||||
|
// @Summary 恢复 API Token
|
||||||
|
// @Description 将已撤销的 API Token 恢复为有效状态
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Param id path int true "Token ID"
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/admin/api-tokens/{id}/recover [post]
|
||||||
|
func (h *TokenHandler) RecoverToken(c *gin.Context) {
|
||||||
|
id := c.Param("id")
|
||||||
|
if err := bootstrap.DB.Model(&model.APIToken{}).Where("id = ?", id).Update("revoked", false).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(map[string]interface{}{}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// DeleteToken 删除 API Token
|
||||||
|
// @Summary 删除 API Token
|
||||||
|
// @Description 根据 ID 永久删除 API Token
|
||||||
|
// @Tags Admin
|
||||||
|
// @Security AdminAuth
|
||||||
|
// @Param id path int true "Token ID"
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/admin/api-tokens/{id} [delete]
|
||||||
|
func (h *TokenHandler) DeleteToken(c *gin.Context) {
|
||||||
|
id := c.Param("id")
|
||||||
|
if err := bootstrap.DB.Delete(&model.APIToken{}, id).Error; err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(map[string]interface{}{}))
|
||||||
|
}
|
||||||
119
internal/api/middleware/auth.go
Normal file
119
internal/api/middleware/auth.go
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/auth"
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/service"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
func AdminAuth() gin.HandlerFunc {
|
||||||
|
tokenService := service.NewTokenService()
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
authHeader := c.GetHeader("Authorization")
|
||||||
|
if authHeader == "" {
|
||||||
|
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Authorization header required"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
parts := strings.SplitN(authHeader, " ", 2)
|
||||||
|
if !(len(parts) == 2 && parts[0] == "Bearer") {
|
||||||
|
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Invalid authorization format"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenStr := parts[1]
|
||||||
|
|
||||||
|
// 1. 尝试解析为管理员 JWT
|
||||||
|
claims, err := auth.ParseToken(tokenStr)
|
||||||
|
if err == nil {
|
||||||
|
c.Set("admin_id", claims.AdminID)
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 尝试解析为 API Token (如果配置允许)
|
||||||
|
if config.GlobalConfig.APIToken.Enabled && config.GlobalConfig.APIToken.AllowAdminAPI {
|
||||||
|
token, err := tokenService.ValidateToken(tokenStr, model.ScopeAdmin)
|
||||||
|
if err == nil {
|
||||||
|
c.Set("token_id", token.ID)
|
||||||
|
c.Set("token_scope", token.Scope)
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Invalid or expired token"))
|
||||||
|
c.Abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func APITokenAuth(requiredScope string, optional bool) gin.HandlerFunc {
|
||||||
|
tokenService := service.NewTokenService()
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
handleAPITokenAuth(c, tokenService, requiredScope, optional)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func UploadAuth() gin.HandlerFunc {
|
||||||
|
tokenService := service.NewTokenService()
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
// 动态获取配置
|
||||||
|
optional := !config.GlobalConfig.Upload.RequireToken
|
||||||
|
handleAPITokenAuth(c, tokenService, model.ScopeUpload, optional)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleAPITokenAuth(c *gin.Context, tokenService *service.TokenService, requiredScope string, optional bool) {
|
||||||
|
// 如果是可选的,直接跳过校验,满足“未打开对应的开关时不需校验”的需求
|
||||||
|
if optional {
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
authHeader := c.GetHeader("Authorization")
|
||||||
|
if authHeader == "" {
|
||||||
|
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Authorization header required"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
parts := strings.SplitN(authHeader, " ", 2)
|
||||||
|
if !(len(parts) == 2 && parts[0] == "Bearer") {
|
||||||
|
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, "Invalid authorization format"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
tokenStr := parts[1]
|
||||||
|
|
||||||
|
// 1. 尝试解析为管理员 JWT
|
||||||
|
if claims, err := auth.ParseToken(tokenStr); err == nil {
|
||||||
|
c.Set("admin_id", claims.AdminID)
|
||||||
|
c.Next()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if !config.GlobalConfig.APIToken.Enabled {
|
||||||
|
c.JSON(http.StatusForbidden, model.ErrorResponse(model.CodeForbidden, "API Token is disabled"))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
token, err := tokenService.ValidateToken(tokenStr, requiredScope)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusUnauthorized, model.ErrorResponse(model.CodeUnauthorized, err.Error()))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Set("token_id", token.ID)
|
||||||
|
c.Set("token_scope", token.Scope)
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
56
internal/api/middleware/limit.go
Normal file
56
internal/api/middleware/limit.go
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
package middleware
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
pickupFailures = make(map[string]int)
|
||||||
|
failureMutex sync.Mutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func PickupRateLimit() gin.HandlerFunc {
|
||||||
|
return func(c *gin.Context) {
|
||||||
|
key := c.ClientIP()
|
||||||
|
|
||||||
|
failureMutex.Lock()
|
||||||
|
count, exists := pickupFailures[key]
|
||||||
|
failureMutex.Unlock()
|
||||||
|
|
||||||
|
if exists && count >= config.GlobalConfig.Security.PickupFailLimit {
|
||||||
|
slog.Warn("Pickup rate limit exceeded", "ip", key, "count", count)
|
||||||
|
c.JSON(http.StatusTooManyRequests, model.ErrorResponse(model.CodeTooManyRequests, "Too many failed attempts. Please try again later."))
|
||||||
|
c.Abort()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func RecordPickupFailure(ip string) {
|
||||||
|
key := ip
|
||||||
|
failureMutex.Lock()
|
||||||
|
pickupFailures[key]++
|
||||||
|
|
||||||
|
// 仅在第一次失败时启动清除记录的计时器
|
||||||
|
if pickupFailures[key] == 1 {
|
||||||
|
go func() {
|
||||||
|
// 设置 1 分钟后清除记录 (简单实现)
|
||||||
|
time.Sleep(1 * time.Hour)
|
||||||
|
failureMutex.Lock()
|
||||||
|
delete(pickupFailures, key)
|
||||||
|
slog.Info("Pickup failure record cleared", "ip", key)
|
||||||
|
failureMutex.Unlock()
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
failureMutex.Unlock()
|
||||||
|
}
|
||||||
61
internal/api/public/config.go
Normal file
61
internal/api/public/config.go
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
package public
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConfigHandler struct{}
|
||||||
|
|
||||||
|
func NewConfigHandler() *ConfigHandler {
|
||||||
|
return &ConfigHandler{}
|
||||||
|
}
|
||||||
|
|
||||||
|
// PublicConfig 公开配置结构
|
||||||
|
type PublicConfig struct {
|
||||||
|
Site config.SiteConfig `json:"site"`
|
||||||
|
Security PublicSecurityConfig `json:"security"`
|
||||||
|
Upload config.UploadConfig `json:"upload"`
|
||||||
|
APIToken PublicAPITokenConfig `json:"api_token"`
|
||||||
|
Storage PublicStorageConfig `json:"storage"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PublicSecurityConfig struct {
|
||||||
|
PickupCodeLength int `json:"pickup_code_length"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PublicAPITokenConfig struct {
|
||||||
|
Enabled bool `json:"enabled"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PublicStorageConfig struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPublicConfig 获取非敏感配置
|
||||||
|
// @Summary 获取公共配置
|
||||||
|
// @Description 获取前端展示所需的非敏感配置数据
|
||||||
|
// @Tags Public
|
||||||
|
// @Produce json
|
||||||
|
// @Success 200 {object} model.Response{data=PublicConfig}
|
||||||
|
// @Router /api/config [get]
|
||||||
|
func (h *ConfigHandler) GetPublicConfig(c *gin.Context) {
|
||||||
|
pub := PublicConfig{
|
||||||
|
Site: config.GlobalConfig.Site,
|
||||||
|
Security: PublicSecurityConfig{
|
||||||
|
PickupCodeLength: config.GlobalConfig.Security.PickupCodeLength,
|
||||||
|
},
|
||||||
|
Upload: config.GlobalConfig.Upload,
|
||||||
|
APIToken: PublicAPITokenConfig{
|
||||||
|
Enabled: config.GlobalConfig.APIToken.Enabled,
|
||||||
|
},
|
||||||
|
Storage: PublicStorageConfig{
|
||||||
|
Type: config.GlobalConfig.Storage.Type,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(pub))
|
||||||
|
}
|
||||||
314
internal/api/public/pickup.go
Normal file
314
internal/api/public/pickup.go
Normal file
@@ -0,0 +1,314 @@
|
|||||||
|
package public
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/api/middleware"
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/service"
|
||||||
|
"FileRelay/internal/storage"
|
||||||
|
"archive/zip"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type PickupResponse struct {
|
||||||
|
Remark string `json:"remark"`
|
||||||
|
ExpireAt *time.Time `json:"expire_at"`
|
||||||
|
ExpireType string `json:"expire_type"`
|
||||||
|
DownloadCount int `json:"download_count"`
|
||||||
|
MaxDownloads int `json:"max_downloads"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Content string `json:"content,omitempty"`
|
||||||
|
Files []model.FileItem `json:"files,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DownloadCountResponse struct {
|
||||||
|
DownloadCount int `json:"download_count"`
|
||||||
|
MaxDownloads int `json:"max_downloads"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownloadBatch 批量下载文件 (ZIP)
|
||||||
|
// @Summary 批量下载文件
|
||||||
|
// @Description 根据取件码将批次内的所有文件打包为 ZIP 格式一次性下载。可选提供带 pickup scope 的 API Token。
|
||||||
|
// @Tags Public
|
||||||
|
// @Security APITokenAuth
|
||||||
|
// @Param pickup_code path string true "取件码"
|
||||||
|
// @Produce application/zip
|
||||||
|
// @Success 200 {file} file
|
||||||
|
// @Failure 404 {object} model.Response
|
||||||
|
// @Router /api/batches/{pickup_code}/download [get]
|
||||||
|
func (h *PickupHandler) DownloadBatch(c *gin.Context) {
|
||||||
|
code := c.Param("pickup_code")
|
||||||
|
batch, err := h.batchService.GetBatchByPickupCode(code)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "batch not found or expired"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"batch_%s.zip\"", code))
|
||||||
|
c.Header("Content-Type", "application/zip")
|
||||||
|
|
||||||
|
zw := zip.NewWriter(c.Writer)
|
||||||
|
defer zw.Close()
|
||||||
|
|
||||||
|
for _, item := range batch.FileItems {
|
||||||
|
reader, err := storage.GlobalStorage.Open(c.Request.Context(), item.StoragePath)
|
||||||
|
if err != nil {
|
||||||
|
continue // Skip failed files
|
||||||
|
}
|
||||||
|
|
||||||
|
f, err := zw.Create(item.OriginalName)
|
||||||
|
if err != nil {
|
||||||
|
reader.Close()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = io.Copy(f, reader)
|
||||||
|
reader.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 增加下载次数
|
||||||
|
if err := h.batchService.IncrementDownloadCount(batch.ID); err != nil {
|
||||||
|
slog.Error("Failed to increment download count", "batch_id", batch.ID, "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type PickupHandler struct {
|
||||||
|
batchService *service.BatchService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPickupHandler() *PickupHandler {
|
||||||
|
return &PickupHandler{
|
||||||
|
batchService: service.NewBatchService(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pickup 获取批次信息
|
||||||
|
// @Summary 获取批次信息
|
||||||
|
// @Description 根据取件码获取文件批次详细信息和文件列表。可选提供带 pickup scope 的 API Token。
|
||||||
|
// @Tags Public
|
||||||
|
// @Security APITokenAuth
|
||||||
|
// @Produce json
|
||||||
|
// @Param pickup_code path string true "取件码"
|
||||||
|
// @Success 200 {object} model.Response{data=PickupResponse}
|
||||||
|
// @Failure 404 {object} model.Response
|
||||||
|
// @Router /api/batches/{pickup_code} [get]
|
||||||
|
func (h *PickupHandler) Pickup(c *gin.Context) {
|
||||||
|
code := c.Param("pickup_code")
|
||||||
|
if code == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "pickup code required"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
batch, err := h.batchService.GetBatchByPickupCode(code)
|
||||||
|
if err != nil {
|
||||||
|
middleware.RecordPickupFailure(c.ClientIP())
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "batch not found or expired"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if batch.Type == "text" {
|
||||||
|
if err := h.batchService.IncrementDownloadCount(batch.ID); err != nil {
|
||||||
|
slog.Error("Failed to increment download count for batch", "batch_id", batch.ID, "error", err)
|
||||||
|
} else {
|
||||||
|
batch.DownloadCount++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
baseURL := getBaseURL(c)
|
||||||
|
|
||||||
|
for i := range batch.FileItems {
|
||||||
|
batch.FileItems[i].DownloadURL = fmt.Sprintf("%s/api/files/%s/%s", baseURL, batch.FileItems[i].ID, batch.FileItems[i].OriginalName)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(PickupResponse{
|
||||||
|
Remark: batch.Remark,
|
||||||
|
ExpireAt: batch.ExpireAt,
|
||||||
|
ExpireType: batch.ExpireType,
|
||||||
|
DownloadCount: batch.DownloadCount,
|
||||||
|
MaxDownloads: batch.MaxDownloads,
|
||||||
|
Type: batch.Type,
|
||||||
|
Content: batch.Content,
|
||||||
|
Files: batch.FileItems,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetDownloadCount 查询下载次数
|
||||||
|
// @Summary 查询下载次数
|
||||||
|
// @Description 根据取件码查询当前下载次数和最大允许下载次数。支持已过期的批次。
|
||||||
|
// @Tags Public
|
||||||
|
// @Produce json
|
||||||
|
// @Param pickup_code path string true "取件码"
|
||||||
|
// @Success 200 {object} model.Response{data=DownloadCountResponse}
|
||||||
|
// @Failure 400 {object} model.Response
|
||||||
|
// @Failure 404 {object} model.Response
|
||||||
|
// @Router /api/batches/{pickup_code}/count [get]
|
||||||
|
func (h *PickupHandler) GetDownloadCount(c *gin.Context) {
|
||||||
|
code := c.Param("pickup_code")
|
||||||
|
if code == "" {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "pickup code required"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
count, max, err := h.batchService.GetDownloadCountByPickupCode(code)
|
||||||
|
if err != nil {
|
||||||
|
middleware.RecordPickupFailure(c.ClientIP())
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "batch not found"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(DownloadCountResponse{
|
||||||
|
DownloadCount: count,
|
||||||
|
MaxDownloads: max,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getBaseURL(c *gin.Context) string {
|
||||||
|
// 优先使用配置中的 BaseURL
|
||||||
|
if config.GlobalConfig.Site.BaseURL != "" {
|
||||||
|
return strings.TrimSuffix(config.GlobalConfig.Site.BaseURL, "/")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动检测逻辑
|
||||||
|
scheme := "http"
|
||||||
|
if c.Request.TLS != nil {
|
||||||
|
scheme = "https"
|
||||||
|
} else {
|
||||||
|
// 检查常用的代理协议头 (优先)
|
||||||
|
// 增加对用户提供的 :scheme (可能被某些代理转为普通 header) 的支持
|
||||||
|
// 增加对 X-Forwarded-Proto 可能存在的逗号分隔列表的处理
|
||||||
|
checkHeaders := []struct {
|
||||||
|
name string
|
||||||
|
values []string
|
||||||
|
}{
|
||||||
|
{"X-Forwarded-Proto", []string{"https"}},
|
||||||
|
{"X-Forwarded-Protocol", []string{"https"}},
|
||||||
|
{"X-Url-Scheme", []string{"https"}},
|
||||||
|
{"Front-End-Https", []string{"on", "https"}},
|
||||||
|
{"X-Forwarded-Ssl", []string{"on", "https"}},
|
||||||
|
{":scheme", []string{"https"}},
|
||||||
|
{"X-Scheme", []string{"https"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
found := false
|
||||||
|
for _, h := range checkHeaders {
|
||||||
|
val := c.GetHeader(h.name)
|
||||||
|
if val == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
// 处理可能的逗号分隔列表 (如 X-Forwarded-Proto: https, http)
|
||||||
|
firstVal := strings.TrimSpace(strings.ToLower(strings.Split(val, ",")[0]))
|
||||||
|
for _, target := range h.values {
|
||||||
|
if firstVal == target {
|
||||||
|
scheme = "https"
|
||||||
|
found = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if found {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查 Forwarded 头部 (RFC 7239)
|
||||||
|
if !found {
|
||||||
|
if forwarded := c.GetHeader("Forwarded"); forwarded != "" {
|
||||||
|
if strings.Contains(strings.ToLower(forwarded), "proto=https") {
|
||||||
|
scheme = "https"
|
||||||
|
found = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 启发式判断:如果上述头部都没有,但 Referer 是 https,则认为也是 https
|
||||||
|
// 这在同域 API 请求时非常可靠
|
||||||
|
if !found {
|
||||||
|
if referer := c.GetHeader("Referer"); strings.HasPrefix(strings.ToLower(referer), "https://") {
|
||||||
|
scheme = "https"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
host := c.Request.Host
|
||||||
|
if forwardedHost := c.GetHeader("X-Forwarded-Host"); forwardedHost != "" {
|
||||||
|
// 处理可能的逗号分隔列表
|
||||||
|
host = strings.TrimSpace(strings.Split(forwardedHost, ",")[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
return fmt.Sprintf("%s://%s", scheme, host)
|
||||||
|
}
|
||||||
|
|
||||||
|
// DownloadFile 下载单个文件
|
||||||
|
// @Summary 下载单个文件
|
||||||
|
// @Description 根据文件 ID 下载单个文件。支持直观的文件名结尾以方便下载工具识别。可选提供带 pickup scope 的 API Token。
|
||||||
|
// @Tags Public
|
||||||
|
// @Security APITokenAuth
|
||||||
|
// @Param file_id path string true "文件 ID (UUID)"
|
||||||
|
// @Param filename path string false "文件名"
|
||||||
|
// @Produce application/octet-stream
|
||||||
|
// @Success 200 {file} file
|
||||||
|
// @Failure 404 {object} model.Response
|
||||||
|
// @Failure 410 {object} model.Response
|
||||||
|
// @Router /api/files/{file_id}/{filename} [get]
|
||||||
|
// @Router /api/files/{file_id}/download [get]
|
||||||
|
func (h *PickupHandler) DownloadFile(c *gin.Context) {
|
||||||
|
fileID := c.Param("file_id")
|
||||||
|
|
||||||
|
var item model.FileItem
|
||||||
|
if err := bootstrap.DB.First(&item, "id = ?", fileID).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "file not found"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
var batch model.FileBatch
|
||||||
|
if err := bootstrap.DB.First(&batch, "id = ?", item.BatchID).Error; err != nil {
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "batch not found"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if h.batchService.IsExpired(&batch) {
|
||||||
|
h.batchService.MarkAsExpired(&batch)
|
||||||
|
// 按照需求,如果不存在(已在上面处理)或达到上限,返回 404
|
||||||
|
if batch.ExpireType == "download" && batch.DownloadCount >= batch.MaxDownloads {
|
||||||
|
c.JSON(http.StatusNotFound, model.ErrorResponse(model.CodeNotFound, "file not found or download limit reached"))
|
||||||
|
} else {
|
||||||
|
c.JSON(http.StatusGone, model.ErrorResponse(model.CodeGone, "batch expired"))
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 打开文件
|
||||||
|
reader, err := storage.GlobalStorage.Open(c.Request.Context(), item.StoragePath)
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, "failed to open file"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
|
||||||
|
// 增加下载次数
|
||||||
|
if err := h.batchService.IncrementDownloadCount(batch.ID); err != nil {
|
||||||
|
// 记录错误但不中断下载过程
|
||||||
|
slog.Error("Failed to increment download count for batch", "batch_id", batch.ID, "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", item.OriginalName))
|
||||||
|
c.Header("Content-Type", item.MimeType)
|
||||||
|
c.Header("Content-Length", strconv.FormatInt(item.Size, 10))
|
||||||
|
|
||||||
|
// 如果是 HEAD 请求,只返回 Header
|
||||||
|
if c.Request.Method == http.MethodHead {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := io.Copy(c.Writer, reader); err != nil {
|
||||||
|
slog.Error("Error during file download", "file_id", item.ID, "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
175
internal/api/public/upload.go
Normal file
175
internal/api/public/upload.go
Normal file
@@ -0,0 +1,175 @@
|
|||||||
|
package public
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/service"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UploadHandler struct {
|
||||||
|
uploadService *service.UploadService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUploadHandler() *UploadHandler {
|
||||||
|
return &UploadHandler{
|
||||||
|
uploadService: service.NewUploadService(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadResponse struct {
|
||||||
|
PickupCode string `json:"pickup_code"`
|
||||||
|
ExpireAt *time.Time `json:"expire_at"`
|
||||||
|
BatchID string `json:"batch_id"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload 上传文件并生成取件码
|
||||||
|
// @Summary 上传文件
|
||||||
|
// @Description 上传一个或多个文件并创建一个提取批次。如果配置了 require_token,则必须提供带 upload scope 的 API Token。
|
||||||
|
// @Tags Public
|
||||||
|
// @Accept multipart/form-data
|
||||||
|
// @Produce json
|
||||||
|
// @Security APITokenAuth
|
||||||
|
// @Param files formData file true "文件列表"
|
||||||
|
// @Param remark formData string false "备注"
|
||||||
|
// @Param expire_type formData string false "过期类型 (time/download/permanent)"
|
||||||
|
// @Param expire_days formData int false "过期天数 (针对 time 类型)"
|
||||||
|
// @Param max_downloads formData int false "最大下载次数 (针对 download 类型)"
|
||||||
|
// @Success 200 {object} model.Response{data=UploadResponse}
|
||||||
|
// @Failure 400 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/batches [post]
|
||||||
|
func (h *UploadHandler) Upload(c *gin.Context) {
|
||||||
|
form, err := c.MultipartForm()
|
||||||
|
if err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "invalid form"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
files := form.File["files"]
|
||||||
|
if len(files) == 0 {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "no files uploaded"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(files) > config.GlobalConfig.Upload.MaxBatchFiles {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, "too many files"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验单个文件大小
|
||||||
|
maxSize := config.GlobalConfig.Upload.MaxFileSizeMB * 1024 * 1024
|
||||||
|
for _, file := range files {
|
||||||
|
if file.Size > maxSize {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, fmt.Sprintf("文件 %s 超过最大限制 (%dMB)", file.Filename, config.GlobalConfig.Upload.MaxFileSizeMB)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
remark := c.PostForm("remark")
|
||||||
|
expireType := c.PostForm("expire_type") // time / download / permanent
|
||||||
|
if expireType == "" {
|
||||||
|
expireType = "time"
|
||||||
|
}
|
||||||
|
|
||||||
|
var expireValue interface{}
|
||||||
|
switch expireType {
|
||||||
|
case "time":
|
||||||
|
days, _ := strconv.Atoi(c.PostForm("expire_days"))
|
||||||
|
if days <= 0 {
|
||||||
|
days = config.GlobalConfig.Upload.MaxRetentionDays
|
||||||
|
}
|
||||||
|
expireValue = days
|
||||||
|
case "download":
|
||||||
|
max, _ := strconv.Atoi(c.PostForm("max_downloads"))
|
||||||
|
if max <= 0 {
|
||||||
|
max = 1
|
||||||
|
}
|
||||||
|
expireValue = max
|
||||||
|
}
|
||||||
|
|
||||||
|
batch, err := h.uploadService.CreateBatch(c.Request.Context(), files, remark, expireType, expireValue)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Upload handler failed to create batch", "error", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(UploadResponse{
|
||||||
|
PickupCode: batch.PickupCode,
|
||||||
|
ExpireAt: batch.ExpireAt,
|
||||||
|
BatchID: batch.ID,
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadTextRequest struct {
|
||||||
|
Content string `json:"content" binding:"required" example:"这是一段长文本内容..."`
|
||||||
|
Remark string `json:"remark" example:"文本备注"`
|
||||||
|
ExpireType string `json:"expire_type" example:"time"`
|
||||||
|
ExpireDays int `json:"expire_days" example:"7"`
|
||||||
|
MaxDownloads int `json:"max_downloads" example:"5"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// UploadText 发送长文本并生成取件码
|
||||||
|
// @Summary 发送长文本
|
||||||
|
// @Description 中转一段长文本内容并创建一个提取批次。如果配置了 require_token,则必须提供带 upload scope 的 API Token。
|
||||||
|
// @Tags Public
|
||||||
|
// @Accept json
|
||||||
|
// @Produce json
|
||||||
|
// @Security APITokenAuth
|
||||||
|
// @Param request body UploadTextRequest true "文本内容及配置"
|
||||||
|
// @Success 200 {object} model.Response{data=UploadResponse}
|
||||||
|
// @Failure 400 {object} model.Response
|
||||||
|
// @Failure 500 {object} model.Response
|
||||||
|
// @Router /api/batches/text [post]
|
||||||
|
func (h *UploadHandler) UploadText(c *gin.Context) {
|
||||||
|
var req UploadTextRequest
|
||||||
|
if err := c.ShouldBindJSON(&req); err != nil {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 校验文本长度
|
||||||
|
maxSize := config.GlobalConfig.Upload.MaxFileSizeMB * 1024 * 1024
|
||||||
|
if int64(len(req.Content)) > maxSize {
|
||||||
|
c.JSON(http.StatusBadRequest, model.ErrorResponse(model.CodeBadRequest, fmt.Sprintf("文本内容超过最大限制 (%dMB)", config.GlobalConfig.Upload.MaxFileSizeMB)))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if req.ExpireType == "" {
|
||||||
|
req.ExpireType = "time"
|
||||||
|
}
|
||||||
|
|
||||||
|
var expireValue interface{}
|
||||||
|
switch req.ExpireType {
|
||||||
|
case "time":
|
||||||
|
if req.ExpireDays <= 0 {
|
||||||
|
req.ExpireDays = config.GlobalConfig.Upload.MaxRetentionDays
|
||||||
|
}
|
||||||
|
expireValue = req.ExpireDays
|
||||||
|
case "download":
|
||||||
|
if req.MaxDownloads <= 0 {
|
||||||
|
req.MaxDownloads = 1
|
||||||
|
}
|
||||||
|
expireValue = req.MaxDownloads
|
||||||
|
}
|
||||||
|
|
||||||
|
batch, err := h.uploadService.CreateTextBatch(c.Request.Context(), req.Content, req.Remark, req.ExpireType, expireValue)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Upload handler failed to create text batch", "error", err)
|
||||||
|
c.JSON(http.StatusInternalServerError, model.ErrorResponse(model.CodeInternalError, err.Error()))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
c.JSON(http.StatusOK, model.SuccessResponse(UploadResponse{
|
||||||
|
PickupCode: batch.PickupCode,
|
||||||
|
ExpireAt: batch.ExpireAt,
|
||||||
|
BatchID: batch.ID,
|
||||||
|
}))
|
||||||
|
}
|
||||||
42
internal/auth/jwt.go
Normal file
42
internal/auth/jwt.go
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
package auth
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/golang-jwt/jwt/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Claims struct {
|
||||||
|
AdminID uint `json:"admin_id"`
|
||||||
|
jwt.RegisteredClaims
|
||||||
|
}
|
||||||
|
|
||||||
|
func GenerateToken(adminID uint) (string, error) {
|
||||||
|
claims := Claims{
|
||||||
|
AdminID: adminID,
|
||||||
|
RegisteredClaims: jwt.RegisteredClaims{
|
||||||
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||||
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||||
|
return token.SignedString([]byte(config.GlobalConfig.Security.JWTSecret))
|
||||||
|
}
|
||||||
|
|
||||||
|
func ParseToken(tokenString string) (*Claims, error) {
|
||||||
|
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||||
|
return []byte(config.GlobalConfig.Security.JWTSecret), nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
|
||||||
|
return claims, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, jwt.ErrSignatureInvalid
|
||||||
|
}
|
||||||
406
internal/bootstrap/init.go
Normal file
406
internal/bootstrap/init.go
Normal file
@@ -0,0 +1,406 @@
|
|||||||
|
package bootstrap
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/storage"
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"math/big"
|
||||||
|
"path/filepath"
|
||||||
|
"runtime"
|
||||||
|
|
||||||
|
"log/slog"
|
||||||
|
"os"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/glebarez/sqlite"
|
||||||
|
"golang.org/x/crypto/bcrypt"
|
||||||
|
"gorm.io/driver/mysql"
|
||||||
|
"gorm.io/driver/postgres"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
var DB *gorm.DB
|
||||||
|
|
||||||
|
func InitLog() {
|
||||||
|
level := slog.LevelInfo
|
||||||
|
switch strings.ToLower(config.GlobalConfig.Log.Level) {
|
||||||
|
case "debug":
|
||||||
|
level = slog.LevelDebug
|
||||||
|
case "info":
|
||||||
|
level = slog.LevelInfo
|
||||||
|
case "warn":
|
||||||
|
level = slog.LevelWarn
|
||||||
|
case "error":
|
||||||
|
level = slog.LevelError
|
||||||
|
}
|
||||||
|
|
||||||
|
var handlers []slog.Handler
|
||||||
|
|
||||||
|
// 1. 控制台处理器 (简化格式)
|
||||||
|
handlers = append(handlers, &ConsoleHandler{
|
||||||
|
out: os.Stdout,
|
||||||
|
level: level,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 2. 文件处理器 (结构化 Text 格式)
|
||||||
|
if config.GlobalConfig.Log.FilePath != "" {
|
||||||
|
logDir := filepath.Dir(config.GlobalConfig.Log.FilePath)
|
||||||
|
if err := os.MkdirAll(logDir, 0755); err != nil {
|
||||||
|
fmt.Printf("Warning: Failed to create log directory: %v\n", err)
|
||||||
|
} else {
|
||||||
|
file, err := os.OpenFile(config.GlobalConfig.Log.FilePath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Printf("Warning: Failed to open log file: %v\n", err)
|
||||||
|
} else {
|
||||||
|
fileHandler := slog.NewTextHandler(file, &slog.HandlerOptions{
|
||||||
|
Level: level,
|
||||||
|
AddSource: true,
|
||||||
|
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
|
||||||
|
if a.Key == slog.TimeKey {
|
||||||
|
return slog.String(a.Key, a.Value.Time().Format("2006-01-02 15:04:05.000"))
|
||||||
|
}
|
||||||
|
if a.Key == slog.SourceKey {
|
||||||
|
source := a.Value.Any().(*slog.Source)
|
||||||
|
return slog.String(a.Key, fmt.Sprintf("%s:%d", filepath.Base(source.File), source.Line))
|
||||||
|
}
|
||||||
|
return a
|
||||||
|
},
|
||||||
|
})
|
||||||
|
handlers = append(handlers, fileHandler)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var finalHandler slog.Handler
|
||||||
|
if len(handlers) == 1 {
|
||||||
|
finalHandler = handlers[0]
|
||||||
|
} else {
|
||||||
|
finalHandler = &MultiHandler{handlers: handlers}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger := slog.New(finalHandler).With("service", "filerelay")
|
||||||
|
slog.SetDefault(logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func InitDB() {
|
||||||
|
var err error
|
||||||
|
cfg := config.GlobalConfig.Database
|
||||||
|
|
||||||
|
DB, err = ConnectDB(cfg)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to initialize database", "type", cfg.Type, "error", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("Database initialized and migrated", "type", cfg.Type)
|
||||||
|
|
||||||
|
// 初始化存储
|
||||||
|
if err := ReloadStorage(); err != nil {
|
||||||
|
slog.Error("Failed to initialize storage", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化管理员 (如果不存在)
|
||||||
|
initAdmin()
|
||||||
|
}
|
||||||
|
|
||||||
|
func ConnectDB(cfg config.DatabaseConfig) (*gorm.DB, error) {
|
||||||
|
var dialector gorm.Dialector
|
||||||
|
|
||||||
|
switch strings.ToLower(cfg.Type) {
|
||||||
|
case "mysql":
|
||||||
|
params := cfg.Config
|
||||||
|
if params == "" {
|
||||||
|
params = "parseTime=True&loc=Local&charset=utf8mb4"
|
||||||
|
} else {
|
||||||
|
if !strings.Contains(strings.ToLower(params), "parsetime") {
|
||||||
|
params += "&parseTime=True"
|
||||||
|
}
|
||||||
|
if !strings.Contains(strings.ToLower(params), "loc=") {
|
||||||
|
params += "&loc=Local"
|
||||||
|
}
|
||||||
|
if !strings.Contains(strings.ToLower(params), "charset") {
|
||||||
|
params += "&charset=utf8mb4"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s",
|
||||||
|
cfg.User, cfg.Password, cfg.Host, cfg.Port, cfg.DBName, params)
|
||||||
|
dialector = mysql.Open(dsn)
|
||||||
|
case "postgres", "postgresql":
|
||||||
|
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d %s",
|
||||||
|
cfg.Host, cfg.User, cfg.Password, cfg.DBName, cfg.Port, cfg.Config)
|
||||||
|
dialector = postgres.Open(dsn)
|
||||||
|
case "sqlite", "sqlite3":
|
||||||
|
fallthrough
|
||||||
|
default:
|
||||||
|
dbPath := cfg.Path
|
||||||
|
if dbPath == "" {
|
||||||
|
dbPath = "data/file_relay.db"
|
||||||
|
}
|
||||||
|
dialector = sqlite.Open(dbPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := gorm.Open(dialector, &gorm.Config{})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 自动迁移
|
||||||
|
err = db.AutoMigrate(
|
||||||
|
&model.FileBatch{},
|
||||||
|
&model.FileItem{},
|
||||||
|
&model.APIToken{},
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return db, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReloadDB(newCfg config.DatabaseConfig) error {
|
||||||
|
newDB, err := ConnectDB(newCfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if DB != nil {
|
||||||
|
// 检查是否真的是不同的数据库,避免自迁移导致冲突
|
||||||
|
// 这里简单判断类型或连接串是否变化,或者直接让用户决定
|
||||||
|
// 为了安全,我们只在连接参数确实变化时才尝试迁移
|
||||||
|
slog.Info("Starting data migration to new database...")
|
||||||
|
if err := MigrateData(DB, newDB); err != nil {
|
||||||
|
slog.Error("Data migration failed", "error", err)
|
||||||
|
// 迁移失败不一定需要中断,但需要记录
|
||||||
|
} else {
|
||||||
|
slog.Info("Data migration completed successfully")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
DB = newDB
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func MigrateData(sourceDB, targetDB *gorm.DB) error {
|
||||||
|
// 迁移 APIToken
|
||||||
|
var tokens []model.APIToken
|
||||||
|
if err := sourceDB.Find(&tokens).Error; err == nil && len(tokens) > 0 {
|
||||||
|
if err := targetDB.Save(&tokens).Error; err != nil {
|
||||||
|
slog.Warn("Failed to migrate APITokens", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 迁移 FileBatch (分批处理以节省内存)
|
||||||
|
var batches []model.FileBatch
|
||||||
|
err := sourceDB.Model(&model.FileBatch{}).FindInBatches(&batches, 100, func(tx *gorm.DB, batch int) error {
|
||||||
|
if err := targetDB.Save(&batches).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}).Error
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("Failed to migrate FileBatches", "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 迁移 FileItem (分批处理以节省内存)
|
||||||
|
var items []model.FileItem
|
||||||
|
err = sourceDB.Model(&model.FileItem{}).FindInBatches(&items, 100, func(tx *gorm.DB, batch int) error {
|
||||||
|
if err := targetDB.Save(&items).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}).Error
|
||||||
|
if err != nil {
|
||||||
|
slog.Warn("Failed to migrate FileItems", "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func ReloadStorage() error {
|
||||||
|
storageType := config.GlobalConfig.Storage.Type
|
||||||
|
switch storageType {
|
||||||
|
case "local":
|
||||||
|
storage.GlobalStorage = storage.NewLocalStorage(config.GlobalConfig.Storage.Local.Path)
|
||||||
|
case "webdav":
|
||||||
|
cfg := config.GlobalConfig.Storage.WebDAV
|
||||||
|
storage.GlobalStorage = storage.NewWebDAVStorage(cfg.URL, cfg.Username, cfg.Password, cfg.Root)
|
||||||
|
case "s3":
|
||||||
|
cfg := config.GlobalConfig.Storage.S3
|
||||||
|
s3Storage, err := storage.NewS3Storage(context.Background(), cfg.Endpoint, cfg.Region, cfg.AccessKey, cfg.SecretKey, cfg.Bucket, cfg.UseSSL)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
storage.GlobalStorage = s3Storage
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported storage type: %s", storageType)
|
||||||
|
}
|
||||||
|
slog.Info("Storage initialized", "type", storageType)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func initAdmin() {
|
||||||
|
passwordHash := config.GlobalConfig.Security.AdminPasswordHash
|
||||||
|
if passwordHash == "" {
|
||||||
|
// 生成随机密码
|
||||||
|
password := generateRandomPassword(12)
|
||||||
|
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to generate password hash", "error", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
passwordHash = string(hash)
|
||||||
|
fmt.Printf("**************************************************\n")
|
||||||
|
fmt.Printf("NO ADMIN PASSWORD CONFIGURED. GENERATED RANDOM PASSWORD:\n")
|
||||||
|
fmt.Printf("Password: %s\n", password)
|
||||||
|
fmt.Printf("Please save this password or configure admin_password_hash in config.yaml\n")
|
||||||
|
fmt.Printf("**************************************************\n")
|
||||||
|
|
||||||
|
// 将生成的哈希保存回配置文件
|
||||||
|
config.GlobalConfig.Security.AdminPasswordHash = passwordHash
|
||||||
|
if err := config.SaveConfig(); err != nil {
|
||||||
|
slog.Warn("Failed to save generated password hash to config", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
slog.Info("Admin authentication initialized")
|
||||||
|
}
|
||||||
|
|
||||||
|
func generateRandomPassword(length int) string {
|
||||||
|
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*"
|
||||||
|
b := make([]byte, length)
|
||||||
|
for i := range b {
|
||||||
|
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||||
|
if err != nil {
|
||||||
|
return "admin123" // 退路
|
||||||
|
}
|
||||||
|
b[i] = charset[num.Int64()]
|
||||||
|
}
|
||||||
|
return string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConsoleHandler 实现 simplified 控制台日志
|
||||||
|
type ConsoleHandler struct {
|
||||||
|
out io.Writer
|
||||||
|
level slog.Leveler
|
||||||
|
attrs []slog.Attr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ConsoleHandler) Enabled(_ context.Context, l slog.Level) bool {
|
||||||
|
return l >= h.level.Level()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ConsoleHandler) Handle(_ context.Context, r slog.Record) error {
|
||||||
|
var b strings.Builder
|
||||||
|
|
||||||
|
// 时间: 15:04:05.000
|
||||||
|
b.WriteString(r.Time.Format("15:04:05.000"))
|
||||||
|
b.WriteString(" ")
|
||||||
|
|
||||||
|
// 级别: INFO
|
||||||
|
level := r.Level.String()
|
||||||
|
b.WriteString(fmt.Sprintf("%-5s", level))
|
||||||
|
b.WriteString(" ")
|
||||||
|
|
||||||
|
// 源码: [main.go:123]
|
||||||
|
pc := r.PC
|
||||||
|
if pc == 0 {
|
||||||
|
// 如果 Logger 没采集 PC (自定义 Handler 默认情况),我们手动采集
|
||||||
|
// 跳过: 1:runtime.Callers, 2:Handle, 3:slog.(*Logger).log, 4:slog.(*Logger).Info
|
||||||
|
var pcs [1]uintptr
|
||||||
|
runtime.Callers(4, pcs[:])
|
||||||
|
pc = pcs[0]
|
||||||
|
}
|
||||||
|
|
||||||
|
if pc != 0 {
|
||||||
|
fs := runtime.CallersFrames([]uintptr{pc})
|
||||||
|
f, _ := fs.Next()
|
||||||
|
b.WriteString(fmt.Sprintf("[%s:%d] ", filepath.Base(f.File), f.Line))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 消息
|
||||||
|
b.WriteString(r.Message)
|
||||||
|
|
||||||
|
// 属性: 仅输出值
|
||||||
|
writeAttr := func(a slog.Attr) {
|
||||||
|
if a.Key == "service" {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
b.WriteString(" ")
|
||||||
|
val := a.Value.Resolve().String()
|
||||||
|
if strings.Contains(val, " ") {
|
||||||
|
b.WriteString(fmt.Sprintf("%q", val))
|
||||||
|
} else {
|
||||||
|
b.WriteString(val)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, a := range h.attrs {
|
||||||
|
writeAttr(a)
|
||||||
|
}
|
||||||
|
r.Attrs(func(a slog.Attr) bool {
|
||||||
|
writeAttr(a)
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
|
||||||
|
b.WriteString("\n")
|
||||||
|
_, err := h.out.Write([]byte(b.String()))
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ConsoleHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||||
|
newAttrs := make([]slog.Attr, len(h.attrs)+len(attrs))
|
||||||
|
copy(newAttrs, h.attrs)
|
||||||
|
copy(newAttrs[len(h.attrs):], attrs)
|
||||||
|
return &ConsoleHandler{
|
||||||
|
out: h.out,
|
||||||
|
level: h.level,
|
||||||
|
attrs: newAttrs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *ConsoleHandler) WithGroup(name string) slog.Handler {
|
||||||
|
return h // 简化版暂不支持分组
|
||||||
|
}
|
||||||
|
|
||||||
|
// MultiHandler 实现多路分发
|
||||||
|
type MultiHandler struct {
|
||||||
|
handlers []slog.Handler
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MultiHandler) Enabled(ctx context.Context, l slog.Level) bool {
|
||||||
|
for _, hh := range h.handlers {
|
||||||
|
if hh.Enabled(ctx, l) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MultiHandler) Handle(ctx context.Context, r slog.Record) error {
|
||||||
|
for _, hh := range h.handlers {
|
||||||
|
if hh.Enabled(ctx, r.Level) {
|
||||||
|
_ = hh.Handle(ctx, r)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MultiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
||||||
|
newHandlers := make([]slog.Handler, len(h.handlers))
|
||||||
|
for i, hh := range h.handlers {
|
||||||
|
newHandlers[i] = hh.WithAttrs(attrs)
|
||||||
|
}
|
||||||
|
return &MultiHandler{handlers: newHandlers}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *MultiHandler) WithGroup(name string) slog.Handler {
|
||||||
|
newHandlers := make([]slog.Handler, len(h.handlers))
|
||||||
|
for i, hh := range h.handlers {
|
||||||
|
newHandlers[i] = hh.WithGroup(name)
|
||||||
|
}
|
||||||
|
return &MultiHandler{handlers: newHandlers}
|
||||||
|
}
|
||||||
282
internal/config/config.go
Normal file
282
internal/config/config.go
Normal file
@@ -0,0 +1,282 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"gopkg.in/yaml.v3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Config struct {
|
||||||
|
Site SiteConfig `yaml:"site" json:"site"` // 站点设置
|
||||||
|
Security SecurityConfig `yaml:"security" json:"security"` // 安全设置
|
||||||
|
Upload UploadConfig `yaml:"upload" json:"upload"` // 上传设置
|
||||||
|
Storage StorageConfig `yaml:"storage" json:"storage"` // 存储设置
|
||||||
|
APIToken APITokenConfig `yaml:"api_token" json:"api_token"` // API Token 设置
|
||||||
|
Database DatabaseConfig `yaml:"database" json:"database"` // 数据库设置
|
||||||
|
Web WebConfig `yaml:"web" json:"web"` // Web 前端设置
|
||||||
|
Log LogConfig `yaml:"log" json:"log"` // 日志设置
|
||||||
|
}
|
||||||
|
|
||||||
|
type LogConfig struct {
|
||||||
|
Level string `yaml:"level" json:"level"` // 日志级别: debug, info, warn, error
|
||||||
|
FilePath string `yaml:"file_path" json:"file_path"` // 日志文件路径,为空则仅输出到控制台
|
||||||
|
}
|
||||||
|
|
||||||
|
type WebConfig struct {
|
||||||
|
Path string `yaml:"path" json:"path"` // Web 前端资源路径
|
||||||
|
}
|
||||||
|
|
||||||
|
type SiteConfig struct {
|
||||||
|
Name string `yaml:"name" json:"name"` // 站点名称
|
||||||
|
Description string `yaml:"description" json:"description"` // 站点描述
|
||||||
|
Logo string `yaml:"logo" json:"logo"` // 站点 Logo URL
|
||||||
|
BaseURL string `yaml:"base_url" json:"base_url"` // 站点外部访问地址 (例如: https://file.example.com)
|
||||||
|
Port int `yaml:"port" json:"port"` // 监听端口
|
||||||
|
}
|
||||||
|
|
||||||
|
type SecurityConfig struct {
|
||||||
|
AdminPasswordHash string `yaml:"admin_password_hash" json:"admin_password_hash"` // 管理员密码哈希 (bcrypt)
|
||||||
|
AdminPassword string `yaml:"-" json:"admin_password,omitempty"` // 管理员密码明文 (仅用于更新请求,不保存到文件)
|
||||||
|
PickupCodeLength int `yaml:"pickup_code_length" json:"pickup_code_length"` // 取件码长度 (变更后将自动通过右侧补零或截取调整存量数据)
|
||||||
|
PickupFailLimit int `yaml:"pickup_fail_limit" json:"pickup_fail_limit"` // 取件失败尝试限制
|
||||||
|
JWTSecret string `yaml:"jwt_secret" json:"jwt_secret"` // JWT 签名密钥
|
||||||
|
}
|
||||||
|
|
||||||
|
type UploadConfig struct {
|
||||||
|
MaxFileSizeMB int64 `yaml:"max_file_size_mb" json:"max_file_size_mb"` // 单个文件最大大小 (MB)
|
||||||
|
MaxBatchFiles int `yaml:"max_batch_files" json:"max_batch_files"` // 每个批次最大文件数
|
||||||
|
MaxRetentionDays int `yaml:"max_retention_days" json:"max_retention_days"` // 最大保留天数
|
||||||
|
RequireToken bool `yaml:"require_token" json:"require_token"` // 是否强制要求上传 Token
|
||||||
|
}
|
||||||
|
|
||||||
|
type StorageConfig struct {
|
||||||
|
Type string `yaml:"type" json:"type"` // 存储类型: local, webdav, s3
|
||||||
|
Local struct {
|
||||||
|
Path string `yaml:"path" json:"path"` // 本地存储路径
|
||||||
|
} `yaml:"local" json:"local"`
|
||||||
|
WebDAV struct {
|
||||||
|
URL string `yaml:"url" json:"url"` // WebDAV 地址
|
||||||
|
Username string `yaml:"username" json:"username"` // WebDAV 用户名
|
||||||
|
Password string `yaml:"password" json:"password"` // WebDAV 密码
|
||||||
|
Root string `yaml:"root" json:"root"` // WebDAV 根目录
|
||||||
|
} `yaml:"webdav" json:"webdav"`
|
||||||
|
S3 struct {
|
||||||
|
Endpoint string `yaml:"endpoint" json:"endpoint"` // S3 端点
|
||||||
|
Region string `yaml:"region" json:"region"` // S3 区域
|
||||||
|
AccessKey string `yaml:"access_key" json:"access_key"` // S3 Access Key
|
||||||
|
SecretKey string `yaml:"secret_key" json:"secret_key"` // S3 Secret Key
|
||||||
|
Bucket string `yaml:"bucket" json:"bucket"` // S3 Bucket
|
||||||
|
UseSSL bool `yaml:"use_ssl" json:"use_ssl"` // 是否使用 SSL
|
||||||
|
} `yaml:"s3" json:"s3"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type APITokenConfig struct {
|
||||||
|
Enabled bool `yaml:"enabled" json:"enabled"` // 是否启用 API Token
|
||||||
|
AllowAdminAPI bool `yaml:"allow_admin_api" json:"allow_admin_api"` // 是否允许 API Token 访问管理接口
|
||||||
|
MaxTokens int `yaml:"max_tokens" json:"max_tokens"` // 最大 Token 数量
|
||||||
|
}
|
||||||
|
|
||||||
|
type DatabaseConfig struct {
|
||||||
|
Type string `yaml:"type" json:"type"` // 数据库类型: sqlite, mysql, postgres
|
||||||
|
Path string `yaml:"path" json:"path"` // SQLite 数据库文件路径
|
||||||
|
Host string `yaml:"host" json:"host"` // 数据库地址
|
||||||
|
Port int `yaml:"port" json:"port"` // 数据库端口
|
||||||
|
User string `yaml:"user" json:"user"` // 数据库用户名
|
||||||
|
Password string `yaml:"password" json:"password"` // 数据库密码
|
||||||
|
DBName string `yaml:"dbname" json:"dbname"` // 数据库名称
|
||||||
|
Config string `yaml:"config" json:"config"` // 额外配置参数 (DSN)
|
||||||
|
}
|
||||||
|
|
||||||
|
var (
|
||||||
|
GlobalConfig *Config
|
||||||
|
ConfigPath string
|
||||||
|
configLock sync.RWMutex
|
||||||
|
)
|
||||||
|
|
||||||
|
func LoadConfig(path string) error {
|
||||||
|
configLock.Lock()
|
||||||
|
defer configLock.Unlock()
|
||||||
|
|
||||||
|
// 检查文件是否存在
|
||||||
|
if _, err := os.Stat(path); os.IsNotExist(err) {
|
||||||
|
// 创建默认配置
|
||||||
|
cfg := GetDefaultConfig()
|
||||||
|
data, err := yaml.Marshal(cfg)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
// 确保目录存在
|
||||||
|
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(path, data, 0644); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
cfg.overrideWithEnv()
|
||||||
|
GlobalConfig = cfg
|
||||||
|
ConfigPath = path
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
data, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
var cfg Config
|
||||||
|
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.overrideWithEnv()
|
||||||
|
GlobalConfig = &cfg
|
||||||
|
ConfigPath = path
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cfg *Config) overrideWithEnv() {
|
||||||
|
// Site settings
|
||||||
|
if val := os.Getenv("FR_SITE_NAME"); val != "" {
|
||||||
|
cfg.Site.Name = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_SITE_BASE_URL"); val != "" {
|
||||||
|
cfg.Site.BaseURL = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_SITE_PORT"); val != "" {
|
||||||
|
if port, err := strconv.Atoi(val); err == nil {
|
||||||
|
cfg.Site.Port = port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Security settings
|
||||||
|
if val := os.Getenv("FR_SECURITY_JWT_SECRET"); val != "" {
|
||||||
|
cfg.Security.JWTSecret = val
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upload settings
|
||||||
|
if val := os.Getenv("FR_UPLOAD_MAX_SIZE"); val != "" {
|
||||||
|
if size, err := strconv.ParseInt(val, 10, 64); err == nil {
|
||||||
|
cfg.Upload.MaxFileSizeMB = size
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_UPLOAD_RETENTION_DAYS"); val != "" {
|
||||||
|
if days, err := strconv.Atoi(val); err == nil {
|
||||||
|
cfg.Upload.MaxRetentionDays = days
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Database settings
|
||||||
|
if val := os.Getenv("FR_DB_TYPE"); val != "" {
|
||||||
|
cfg.Database.Type = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_DB_PATH"); val != "" {
|
||||||
|
cfg.Database.Path = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_DB_HOST"); val != "" {
|
||||||
|
cfg.Database.Host = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_DB_PORT"); val != "" {
|
||||||
|
if port, err := strconv.Atoi(val); err == nil {
|
||||||
|
cfg.Database.Port = port
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_DB_USER"); val != "" {
|
||||||
|
cfg.Database.User = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_DB_PASSWORD"); val != "" {
|
||||||
|
cfg.Database.Password = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_DB_NAME"); val != "" {
|
||||||
|
cfg.Database.DBName = val
|
||||||
|
}
|
||||||
|
|
||||||
|
// Storage settings
|
||||||
|
if val := os.Getenv("FR_STORAGE_TYPE"); val != "" {
|
||||||
|
cfg.Storage.Type = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_STORAGE_LOCAL_PATH"); val != "" {
|
||||||
|
cfg.Storage.Local.Path = val
|
||||||
|
}
|
||||||
|
|
||||||
|
// Log settings
|
||||||
|
if val := os.Getenv("FR_LOG_LEVEL"); val != "" {
|
||||||
|
cfg.Log.Level = val
|
||||||
|
}
|
||||||
|
if val := os.Getenv("FR_LOG_FILE_PATH"); val != "" {
|
||||||
|
cfg.Log.FilePath = val
|
||||||
|
}
|
||||||
|
|
||||||
|
// Web settings
|
||||||
|
if val := os.Getenv("FR_WEB_PATH"); val != "" {
|
||||||
|
cfg.Web.Path = val
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetDefaultConfig() *Config {
|
||||||
|
return &Config{
|
||||||
|
Site: SiteConfig{
|
||||||
|
Name: "文件暂存柜",
|
||||||
|
Description: "临时文件中转服务",
|
||||||
|
Logo: "/favicon.png",
|
||||||
|
BaseURL: "",
|
||||||
|
Port: 8080,
|
||||||
|
},
|
||||||
|
Security: SecurityConfig{
|
||||||
|
AdminPasswordHash: "$2a$10$Bm0TEmU4uj.bVHYiIPFBheUkcdg6XHpsanLvmpoAtgU1UnKbo9.vy", // 默认密码: admin123
|
||||||
|
PickupCodeLength: 6,
|
||||||
|
PickupFailLimit: 5,
|
||||||
|
JWTSecret: "file-relay-secret",
|
||||||
|
},
|
||||||
|
Upload: UploadConfig{
|
||||||
|
MaxFileSizeMB: 100,
|
||||||
|
MaxBatchFiles: 20,
|
||||||
|
MaxRetentionDays: 30,
|
||||||
|
RequireToken: false,
|
||||||
|
},
|
||||||
|
Storage: StorageConfig{
|
||||||
|
Type: "local",
|
||||||
|
Local: struct {
|
||||||
|
Path string `yaml:"path" json:"path"`
|
||||||
|
}{
|
||||||
|
Path: "data/storage_data",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
APIToken: APITokenConfig{
|
||||||
|
Enabled: true,
|
||||||
|
AllowAdminAPI: true,
|
||||||
|
MaxTokens: 20,
|
||||||
|
},
|
||||||
|
Database: DatabaseConfig{
|
||||||
|
Type: "sqlite",
|
||||||
|
Path: "data/file_relay.db",
|
||||||
|
},
|
||||||
|
Web: WebConfig{
|
||||||
|
Path: "web",
|
||||||
|
},
|
||||||
|
Log: LogConfig{
|
||||||
|
Level: "info",
|
||||||
|
FilePath: "data/logs/app.log",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func SaveConfig() error {
|
||||||
|
configLock.RLock()
|
||||||
|
defer configLock.RUnlock()
|
||||||
|
|
||||||
|
data, err := yaml.Marshal(GlobalConfig)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return os.WriteFile(ConfigPath, data, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
func UpdateGlobalConfig(cfg *Config) {
|
||||||
|
configLock.Lock()
|
||||||
|
defer configLock.Unlock()
|
||||||
|
GlobalConfig = cfg
|
||||||
|
}
|
||||||
43
internal/config/config_test.go
Normal file
43
internal/config/config_test.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestGetDefaultConfig(t *testing.T) {
|
||||||
|
cfg := GetDefaultConfig()
|
||||||
|
assert.Equal(t, "data/storage_data", cfg.Storage.Local.Path)
|
||||||
|
assert.Equal(t, "data/file_relay.db", cfg.Database.Path)
|
||||||
|
assert.Equal(t, "data/logs/app.log", cfg.Log.FilePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestOverrideWithEnv(t *testing.T) {
|
||||||
|
// 设置环境变量
|
||||||
|
os.Setenv("FR_SITE_NAME", "EnvSiteName")
|
||||||
|
os.Setenv("FR_SITE_PORT", "9999")
|
||||||
|
os.Setenv("FR_DB_TYPE", "mysql")
|
||||||
|
os.Setenv("FR_DB_PATH", "custom_db_path.db")
|
||||||
|
os.Setenv("FR_UPLOAD_MAX_SIZE", "500")
|
||||||
|
os.Setenv("FR_LOG_FILE_PATH", "custom_log_path.log")
|
||||||
|
|
||||||
|
cfg := GetDefaultConfig()
|
||||||
|
cfg.overrideWithEnv()
|
||||||
|
|
||||||
|
assert.Equal(t, "EnvSiteName", cfg.Site.Name)
|
||||||
|
assert.Equal(t, 9999, cfg.Site.Port)
|
||||||
|
assert.Equal(t, "mysql", cfg.Database.Type)
|
||||||
|
assert.Equal(t, "custom_db_path.db", cfg.Database.Path)
|
||||||
|
assert.Equal(t, int64(500), cfg.Upload.MaxFileSizeMB)
|
||||||
|
assert.Equal(t, "custom_log_path.log", cfg.Log.FilePath)
|
||||||
|
|
||||||
|
// 清理环境变量
|
||||||
|
os.Unsetenv("FR_SITE_NAME")
|
||||||
|
os.Unsetenv("FR_SITE_PORT")
|
||||||
|
os.Unsetenv("FR_DB_TYPE")
|
||||||
|
os.Unsetenv("FR_DB_PATH")
|
||||||
|
os.Unsetenv("FR_UPLOAD_MAX_SIZE")
|
||||||
|
os.Unsetenv("FR_LOG_FILE_PATH")
|
||||||
|
}
|
||||||
11
internal/model/admin.go
Normal file
11
internal/model/admin.go
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// AdminSession 管理员会话信息 (不再存库,仅用于 JWT 或 API 交互)
|
||||||
|
type AdminSession struct {
|
||||||
|
ID uint `json:"id"`
|
||||||
|
LastLogin *time.Time `json:"last_login"`
|
||||||
|
}
|
||||||
22
internal/model/api_token.go
Normal file
22
internal/model/api_token.go
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
ScopeUpload = "upload" // 上传权限
|
||||||
|
ScopePickup = "pickup" // 取件/下载权限
|
||||||
|
ScopeAdmin = "admin" // 管理权限
|
||||||
|
)
|
||||||
|
|
||||||
|
type APIToken struct {
|
||||||
|
ID uint `gorm:"primaryKey" json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
TokenHash string `gorm:"uniqueIndex;not null" json:"-"`
|
||||||
|
Scope string `json:"scope"`
|
||||||
|
ExpireAt *time.Time `json:"expire_at"`
|
||||||
|
LastUsedAt *time.Time `json:"last_used_at"`
|
||||||
|
Revoked bool `gorm:"default:false" json:"revoked"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
24
internal/model/file_batch.go
Normal file
24
internal/model/file_batch.go
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FileBatch struct {
|
||||||
|
ID string `gorm:"primaryKey;type:varchar(36)" json:"id"`
|
||||||
|
PickupCode string `gorm:"uniqueIndex;not null" json:"pickup_code"`
|
||||||
|
Remark string `json:"remark"`
|
||||||
|
ExpireType string `json:"expire_type"` // time / download / permanent
|
||||||
|
ExpireAt *time.Time `json:"expire_at"`
|
||||||
|
MaxDownloads int `json:"max_downloads"`
|
||||||
|
DownloadCount int `gorm:"default:0" json:"download_count"`
|
||||||
|
Status string `gorm:"default:'active'" json:"status"` // active / expired / deleted
|
||||||
|
Type string `gorm:"default:'file'" json:"type"` // file / text
|
||||||
|
Content string `json:"content,omitempty"`
|
||||||
|
FileItems []FileItem `gorm:"foreignKey:BatchID" json:"file_items,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
DeletedAt gorm.DeletedAt `gorm:"index" json:"-"`
|
||||||
|
}
|
||||||
16
internal/model/file_item.go
Normal file
16
internal/model/file_item.go
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
import (
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type FileItem struct {
|
||||||
|
ID string `gorm:"primaryKey;type:varchar(36)" json:"id"`
|
||||||
|
BatchID string `gorm:"index;not null;type:varchar(36)" json:"batch_id"`
|
||||||
|
OriginalName string `json:"original_name"`
|
||||||
|
StoragePath string `json:"storage_path"`
|
||||||
|
Size int64 `json:"size"`
|
||||||
|
MimeType string `json:"mime_type"`
|
||||||
|
DownloadURL string `gorm:"-" json:"download_url,omitempty"`
|
||||||
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
}
|
||||||
46
internal/model/response.go
Normal file
46
internal/model/response.go
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
package model
|
||||||
|
|
||||||
|
// Response 统一响应模型
|
||||||
|
type Response struct {
|
||||||
|
Code int `json:"code" example:"200"`
|
||||||
|
Msg string `json:"msg" example:"success"`
|
||||||
|
Data interface{} `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// 错误码定义
|
||||||
|
const (
|
||||||
|
CodeSuccess = 200
|
||||||
|
CodeBadRequest = 400
|
||||||
|
CodeUnauthorized = 401
|
||||||
|
CodeForbidden = 403
|
||||||
|
CodeNotFound = 404
|
||||||
|
CodeGone = 410
|
||||||
|
CodeInternalError = 500
|
||||||
|
CodeTooManyRequests = 429
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewResponse 创建响应
|
||||||
|
func NewResponse(code int, msg string, data interface{}) Response {
|
||||||
|
return Response{
|
||||||
|
Code: code,
|
||||||
|
Msg: msg,
|
||||||
|
Data: data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// SuccessResponse 成功响应
|
||||||
|
func SuccessResponse(data interface{}) Response {
|
||||||
|
return Response{
|
||||||
|
Code: CodeSuccess,
|
||||||
|
Msg: "success",
|
||||||
|
Data: data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ErrorResponse 错误响应
|
||||||
|
func ErrorResponse(code int, msg string) Response {
|
||||||
|
return Response{
|
||||||
|
Code: code,
|
||||||
|
Msg: msg,
|
||||||
|
}
|
||||||
|
}
|
||||||
276
internal/service/batch_service.go
Normal file
276
internal/service/batch_service.go
Normal file
@@ -0,0 +1,276 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/storage"
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"log/slog"
|
||||||
|
"math/big"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"crypto/rand"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type BatchService struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBatchService() *BatchService {
|
||||||
|
return &BatchService{db: bootstrap.DB}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) GetBatchByPickupCode(code string) (*model.FileBatch, error) {
|
||||||
|
var batch model.FileBatch
|
||||||
|
err := s.db.Preload("FileItems").Where("pickup_code = ? AND status = ?", code, "active").First(&batch).Error
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否过期
|
||||||
|
if s.IsExpired(&batch) {
|
||||||
|
s.MarkAsExpired(&batch)
|
||||||
|
return nil, errors.New("batch expired")
|
||||||
|
}
|
||||||
|
|
||||||
|
return &batch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) GetDownloadCountByPickupCode(code string) (int, int, error) {
|
||||||
|
var batch model.FileBatch
|
||||||
|
// 查询活跃或已过期的批次
|
||||||
|
err := s.db.Where("pickup_code = ? AND (status = ? OR status = ?)", code, "active", "expired").First(&batch).Error
|
||||||
|
if err != nil {
|
||||||
|
return 0, 0, err
|
||||||
|
}
|
||||||
|
return batch.DownloadCount, batch.MaxDownloads, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) IsExpired(batch *model.FileBatch) bool {
|
||||||
|
if batch.Status != "active" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
switch batch.ExpireType {
|
||||||
|
case "time":
|
||||||
|
if batch.ExpireAt != nil && time.Now().After(*batch.ExpireAt) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
case "download":
|
||||||
|
if batch.MaxDownloads > 0 && batch.DownloadCount >= batch.MaxDownloads {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) MarkAsExpired(batch *model.FileBatch) error {
|
||||||
|
slog.Info("Marking batch as expired", "batch_id", batch.ID, "pickup_code", batch.PickupCode)
|
||||||
|
return s.db.Model(batch).Update("status", "expired").Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) DeleteBatch(ctx context.Context, batchID string) error {
|
||||||
|
var batch model.FileBatch
|
||||||
|
// 使用 Unscoped 以确保即使是已软删除的批次也能找到并清理其物理文件
|
||||||
|
if err := s.db.Unscoped().Preload("FileItems").First(&batch, "id = ?", batchID).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("Deleting batch", "batch_id", batch.ID, "files_count", len(batch.FileItems))
|
||||||
|
|
||||||
|
// 删除物理文件
|
||||||
|
for _, item := range batch.FileItems {
|
||||||
|
if err := storage.GlobalStorage.Delete(ctx, item.StoragePath); err != nil {
|
||||||
|
slog.Error("Failed to delete physical file", "path", item.StoragePath, "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除数据库记录 (彻底删除,不再保留元数据以便清理任务不再扫描到它)
|
||||||
|
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Where("batch_id = ?", batch.ID).Delete(&model.FileItem{}).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if err := tx.Unscoped().Delete(&batch).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) IncrementDownloadCount(batchID string) error {
|
||||||
|
if batchID == "" {
|
||||||
|
return errors.New("batch id is empty")
|
||||||
|
}
|
||||||
|
result := s.db.Model(&model.FileBatch{}).Where("id = ?", batchID).
|
||||||
|
UpdateColumn("download_count", gorm.Expr("download_count + ?", 1))
|
||||||
|
if result.Error != nil {
|
||||||
|
return result.Error
|
||||||
|
}
|
||||||
|
if result.RowsAffected == 0 {
|
||||||
|
return errors.New("batch not found or already deleted")
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) GeneratePickupCode(length int) (string, error) {
|
||||||
|
const charset = "0123456789"
|
||||||
|
b := make([]byte, length)
|
||||||
|
for i := range b {
|
||||||
|
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
b[i] = charset[num.Int64()]
|
||||||
|
}
|
||||||
|
// 检查是否冲突 (排除已删除的,但包括活跃的和已过期的)
|
||||||
|
var count int64
|
||||||
|
s.db.Model(&model.FileBatch{}).Where("pickup_code = ?", string(b)).Count(&count)
|
||||||
|
if count > 0 {
|
||||||
|
return s.GeneratePickupCode(length) // 递归生成
|
||||||
|
}
|
||||||
|
return string(b), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) UpdateAllPickupCodes(newLength int) error {
|
||||||
|
var batches []model.FileBatch
|
||||||
|
// 只更新未删除的记录,包括 active 和 expired
|
||||||
|
if err := s.db.Find(&batches).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
for _, batch := range batches {
|
||||||
|
oldCode := batch.PickupCode
|
||||||
|
if len(oldCode) == newLength {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
var newCode string
|
||||||
|
if len(oldCode) < newLength {
|
||||||
|
// 右侧补零,方便用户输入原码后通过补 0 完成输入
|
||||||
|
newCode = oldCode + strings.Repeat("0", newLength-len(oldCode))
|
||||||
|
} else {
|
||||||
|
// 截取前 newLength 位,保留原码头部
|
||||||
|
newCode = oldCode[:newLength]
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查是否冲突 (在事务中检查)
|
||||||
|
var count int64
|
||||||
|
tx.Model(&model.FileBatch{}).Where("pickup_code = ? AND id != ?", newCode, batch.ID).Count(&count)
|
||||||
|
if count > 0 {
|
||||||
|
// 如果冲突,生成一个新的随机码
|
||||||
|
var err error
|
||||||
|
newCode, err = s.generateUniquePickupCodeInTx(tx, newLength)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Model(&batch).Update("pickup_code", newCode).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) Cleanup(ctx context.Context) error {
|
||||||
|
slog.Debug("Starting cleanup scan")
|
||||||
|
// 1. 寻找并标记过期的 Active Batches
|
||||||
|
var batches []model.FileBatch
|
||||||
|
now := time.Now()
|
||||||
|
// 同时检查时间过期 and 下载次数过期
|
||||||
|
err := s.db.Where("status = ? AND ("+
|
||||||
|
"(expire_type = 'time' AND expire_at < ?) OR "+
|
||||||
|
"(expire_type = 'download' AND max_downloads > 0 AND download_count >= max_downloads)"+
|
||||||
|
")", "active", now).Find(&batches).Error
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to query active batches for cleanup", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(batches) > 0 {
|
||||||
|
slog.Info("Found expired batches to mark", "count", len(batches))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, batch := range batches {
|
||||||
|
_ = s.MarkAsExpired(&batch)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 检查异常文件 (物理文件缺失)
|
||||||
|
var activeBatches []model.FileBatch
|
||||||
|
if err := s.db.Preload("FileItems").Where("status = ?", "active").Find(&activeBatches).Error; err == nil {
|
||||||
|
for _, batch := range activeBatches {
|
||||||
|
var missingItems []model.FileItem
|
||||||
|
for _, item := range batch.FileItems {
|
||||||
|
exists, err := storage.GlobalStorage.Exists(ctx, item.StoragePath)
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to check file existence", "path", item.StoragePath, "error", err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !exists {
|
||||||
|
missingItems = append(missingItems, item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(missingItems) > 0 {
|
||||||
|
slog.Info("Removing missing files from batch", "batch_id", batch.ID, "count", len(missingItems))
|
||||||
|
for _, item := range missingItems {
|
||||||
|
if err := s.db.Delete(&item).Error; err != nil {
|
||||||
|
slog.Error("Failed to remove missing file record", "item_id", item.ID, "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(missingItems) == len(batch.FileItems) {
|
||||||
|
slog.Warn("All files missing for batch, marking as expired", "batch_id", batch.ID)
|
||||||
|
_ = s.MarkAsExpired(&batch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 彻底清理标记为 expired 或 deleted 的批次
|
||||||
|
var toDelete []model.FileBatch
|
||||||
|
// Unscoped 用于包含已软删除但尚未物理清理的记录
|
||||||
|
err = s.db.Unscoped().Where("status IN ? OR deleted_at IS NOT NULL", []string{"expired", "deleted"}).Find(&toDelete).Error
|
||||||
|
if err != nil {
|
||||||
|
slog.Error("Failed to query batches for physical deletion", "error", err)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(toDelete) > 0 {
|
||||||
|
slog.Info("Found batches for physical deletion", "count", len(toDelete))
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, batch := range toDelete {
|
||||||
|
if err := s.DeleteBatch(ctx, batch.ID); err != nil {
|
||||||
|
slog.Error("Failed to physically delete batch", "batch_id", batch.ID, "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *BatchService) generateUniquePickupCodeInTx(tx *gorm.DB, length int) (string, error) {
|
||||||
|
const charset = "0123456789"
|
||||||
|
for {
|
||||||
|
b := make([]byte, length)
|
||||||
|
for i := range b {
|
||||||
|
num, err := rand.Int(rand.Reader, big.NewInt(int64(len(charset))))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
b[i] = charset[num.Int64()]
|
||||||
|
}
|
||||||
|
|
||||||
|
var count int64
|
||||||
|
tx.Model(&model.FileBatch{}).Where("pickup_code = ?", string(b)).Count(&count)
|
||||||
|
if count == 0 {
|
||||||
|
return string(b), nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
83
internal/service/token_service.go
Normal file
83
internal/service/token_service.go
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TokenService struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewTokenService() *TokenService {
|
||||||
|
return &TokenService{db: bootstrap.DB}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *TokenService) CreateToken(name string, scope string, expireAt *time.Time) (string, *model.APIToken, error) {
|
||||||
|
rawToken := uuid.New().String()
|
||||||
|
hash := s.hashToken(rawToken)
|
||||||
|
|
||||||
|
token := &model.APIToken{
|
||||||
|
Name: name,
|
||||||
|
TokenHash: hash,
|
||||||
|
Scope: scope,
|
||||||
|
ExpireAt: expireAt,
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.db.Create(token).Error; err != nil {
|
||||||
|
return "", nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return rawToken, token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *TokenService) ValidateToken(rawToken string, requiredScope string) (*model.APIToken, error) {
|
||||||
|
hash := s.hashToken(rawToken)
|
||||||
|
var token model.APIToken
|
||||||
|
if err := s.db.Where("token_hash = ? AND revoked = ?", hash, false).First(&token).Error; err != nil {
|
||||||
|
return nil, errors.New("invalid token")
|
||||||
|
}
|
||||||
|
|
||||||
|
if token.ExpireAt != nil && time.Now().After(*token.ExpireAt) {
|
||||||
|
return nil, errors.New("token expired")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查 Scope (简单包含判断)
|
||||||
|
// 在实际应用中可以实现更复杂的逻辑
|
||||||
|
if requiredScope != "" && !s.checkScope(token.Scope, requiredScope) {
|
||||||
|
return nil, errors.New("insufficient scope")
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新最后使用时间
|
||||||
|
now := time.Now()
|
||||||
|
s.db.Model(&token).Update("last_used_at", &now)
|
||||||
|
|
||||||
|
return &token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *TokenService) hashToken(token string) string {
|
||||||
|
h := sha256.New()
|
||||||
|
h.Write([]byte(token))
|
||||||
|
return hex.EncodeToString(h.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *TokenService) checkScope(tokenScope, requiredScope string) bool {
|
||||||
|
if requiredScope == "" {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
scopes := strings.Split(tokenScope, ",")
|
||||||
|
for _, s := range scopes {
|
||||||
|
if strings.TrimSpace(s) == requiredScope {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
149
internal/service/upload_service.go
Normal file
149
internal/service/upload_service.go
Normal file
@@ -0,0 +1,149 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/storage"
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"mime/multipart"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type UploadService struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewUploadService() *UploadService {
|
||||||
|
return &UploadService{db: bootstrap.DB}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UploadService) CreateBatch(ctx context.Context, files []*multipart.FileHeader, remark string, expireType string, expireValue interface{}) (*model.FileBatch, error) {
|
||||||
|
// 1. 生成取件码
|
||||||
|
batchService := NewBatchService()
|
||||||
|
pickupCode, err := batchService.GeneratePickupCode(config.GlobalConfig.Security.PickupCodeLength)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 准备 Batch
|
||||||
|
batch := &model.FileBatch{
|
||||||
|
ID: uuid.New().String(),
|
||||||
|
PickupCode: pickupCode,
|
||||||
|
Remark: remark,
|
||||||
|
ExpireType: expireType,
|
||||||
|
Status: "active",
|
||||||
|
Type: "file",
|
||||||
|
}
|
||||||
|
|
||||||
|
s.applyExpire(batch, expireType, expireValue)
|
||||||
|
|
||||||
|
// 3. 处理文件上传
|
||||||
|
err = s.db.Transaction(func(tx *gorm.DB) error {
|
||||||
|
if err := tx.Create(batch).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, fileHeader := range files {
|
||||||
|
fileItem, err := s.processFile(ctx, tx, batch.ID, fileHeader)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
batch.FileItems = append(batch.FileItems, *fileItem)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
|
||||||
|
if err == nil {
|
||||||
|
slog.Info("File batch created", "batch_id", batch.ID, "pickup_code", batch.PickupCode, "files_count", len(files))
|
||||||
|
} else {
|
||||||
|
slog.Error("Failed to create file batch", "error", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return batch, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UploadService) CreateTextBatch(ctx context.Context, content string, remark string, expireType string, expireValue interface{}) (*model.FileBatch, error) {
|
||||||
|
// 1. 生成取件码
|
||||||
|
batchService := NewBatchService()
|
||||||
|
pickupCode, err := batchService.GeneratePickupCode(config.GlobalConfig.Security.PickupCodeLength)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 准备 Batch
|
||||||
|
batch := &model.FileBatch{
|
||||||
|
ID: uuid.New().String(),
|
||||||
|
PickupCode: pickupCode,
|
||||||
|
Remark: remark,
|
||||||
|
ExpireType: expireType,
|
||||||
|
Status: "active",
|
||||||
|
Type: "text",
|
||||||
|
Content: content,
|
||||||
|
}
|
||||||
|
|
||||||
|
s.applyExpire(batch, expireType, expireValue)
|
||||||
|
|
||||||
|
// 3. 保存
|
||||||
|
if err := s.db.Create(batch).Error; err != nil {
|
||||||
|
slog.Error("Failed to create text batch", "error", err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
slog.Info("Text batch created", "batch_id", batch.ID, "pickup_code", batch.PickupCode)
|
||||||
|
return batch, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UploadService) applyExpire(batch *model.FileBatch, expireType string, expireValue interface{}) {
|
||||||
|
switch expireType {
|
||||||
|
case "time":
|
||||||
|
if days, ok := expireValue.(int); ok {
|
||||||
|
expireAt := time.Now().Add(time.Duration(days) * 24 * time.Hour)
|
||||||
|
batch.ExpireAt = &expireAt
|
||||||
|
}
|
||||||
|
case "download":
|
||||||
|
if max, ok := expireValue.(int); ok {
|
||||||
|
batch.MaxDownloads = max
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *UploadService) processFile(ctx context.Context, tx *gorm.DB, batchID string, fileHeader *multipart.FileHeader) (*model.FileItem, error) {
|
||||||
|
file, err := fileHeader.Open()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
// 生成唯一存储路径
|
||||||
|
ext := filepath.Ext(fileHeader.Filename)
|
||||||
|
fileID := uuid.New().String()
|
||||||
|
storagePath := fmt.Sprintf("%s/%s%s", batchID, fileID, ext)
|
||||||
|
|
||||||
|
// 保存到存储层
|
||||||
|
if err := storage.GlobalStorage.Save(ctx, storagePath, file); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建数据库记录
|
||||||
|
item := &model.FileItem{
|
||||||
|
ID: fileID,
|
||||||
|
BatchID: batchID,
|
||||||
|
OriginalName: fileHeader.Filename,
|
||||||
|
StoragePath: storagePath,
|
||||||
|
Size: fileHeader.Size,
|
||||||
|
MimeType: fileHeader.Header.Get("Content-Type"),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := tx.Create(item).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return item, nil
|
||||||
|
}
|
||||||
59
internal/storage/local.go
Normal file
59
internal/storage/local.go
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
)
|
||||||
|
|
||||||
|
type LocalStorage struct {
|
||||||
|
RootPath string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewLocalStorage(rootPath string) *LocalStorage {
|
||||||
|
// 确保根目录存在
|
||||||
|
if _, err := os.Stat(rootPath); os.IsNotExist(err) {
|
||||||
|
os.MkdirAll(rootPath, 0755)
|
||||||
|
}
|
||||||
|
return &LocalStorage{RootPath: rootPath}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *LocalStorage) Save(ctx context.Context, path string, reader io.Reader) error {
|
||||||
|
fullPath := filepath.Join(s.RootPath, path)
|
||||||
|
dir := filepath.Dir(fullPath)
|
||||||
|
if _, err := os.Stat(dir); os.IsNotExist(err) {
|
||||||
|
os.MkdirAll(dir, 0755)
|
||||||
|
}
|
||||||
|
|
||||||
|
file, err := os.Create(fullPath)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
|
_, err = io.Copy(file, reader)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *LocalStorage) Open(ctx context.Context, path string) (io.ReadCloser, error) {
|
||||||
|
fullPath := filepath.Join(s.RootPath, path)
|
||||||
|
return os.Open(fullPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *LocalStorage) Delete(ctx context.Context, path string) error {
|
||||||
|
fullPath := filepath.Join(s.RootPath, path)
|
||||||
|
return os.Remove(fullPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *LocalStorage) Exists(ctx context.Context, path string) (bool, error) {
|
||||||
|
fullPath := filepath.Join(s.RootPath, path)
|
||||||
|
_, err := os.Stat(fullPath)
|
||||||
|
if err == nil {
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
88
internal/storage/s3.go
Normal file
88
internal/storage/s3.go
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/aws/aws-sdk-go-v2/aws"
|
||||||
|
"github.com/aws/aws-sdk-go-v2/config"
|
||||||
|
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||||
|
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type S3Storage struct {
|
||||||
|
client *s3.Client
|
||||||
|
bucket string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewS3Storage(ctx context.Context, endpoint, region, accessKey, secretKey, bucket string, useSSL bool) (*S3Storage, error) {
|
||||||
|
customResolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) {
|
||||||
|
if endpoint != "" {
|
||||||
|
return aws.Endpoint{
|
||||||
|
URL: endpoint,
|
||||||
|
SigningRegion: region,
|
||||||
|
HostnameImmutable: true,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return aws.Endpoint{}, &aws.EndpointNotFoundError{}
|
||||||
|
})
|
||||||
|
|
||||||
|
cfg, err := config.LoadDefaultConfig(ctx,
|
||||||
|
config.WithRegion(region),
|
||||||
|
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")),
|
||||||
|
config.WithEndpointResolverWithOptions(customResolver),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
client := s3.NewFromConfig(cfg)
|
||||||
|
return &S3Storage{
|
||||||
|
client: client,
|
||||||
|
bucket: bucket,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *S3Storage) Save(ctx context.Context, path string, reader io.Reader) error {
|
||||||
|
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||||
|
Bucket: aws.String(s.bucket),
|
||||||
|
Key: aws.String(path),
|
||||||
|
Body: reader,
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *S3Storage) Open(ctx context.Context, path string) (io.ReadCloser, error) {
|
||||||
|
output, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||||
|
Bucket: aws.String(s.bucket),
|
||||||
|
Key: aws.String(path),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return output.Body, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *S3Storage) Delete(ctx context.Context, path string) error {
|
||||||
|
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||||
|
Bucket: aws.String(s.bucket),
|
||||||
|
Key: aws.String(path),
|
||||||
|
})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *S3Storage) Exists(ctx context.Context, path string) (bool, error) {
|
||||||
|
_, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
|
||||||
|
Bucket: aws.String(s.bucket),
|
||||||
|
Key: aws.String(path),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
// In AWS SDK v2, we check if the error is 404
|
||||||
|
if strings.Contains(err.Error(), "NotFound") || strings.Contains(err.Error(), "404") {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
15
internal/storage/storage.go
Normal file
15
internal/storage/storage.go
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Storage interface {
|
||||||
|
Save(ctx context.Context, path string, reader io.Reader) error
|
||||||
|
Open(ctx context.Context, path string) (io.ReadCloser, error)
|
||||||
|
Delete(ctx context.Context, path string) error
|
||||||
|
Exists(ctx context.Context, path string) (bool, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
var GlobalStorage Storage
|
||||||
69
internal/storage/webdav.go
Normal file
69
internal/storage/webdav.go
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
package storage
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/studio-b12/gowebdav"
|
||||||
|
)
|
||||||
|
|
||||||
|
type WebDAVStorage struct {
|
||||||
|
client *gowebdav.Client
|
||||||
|
root string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewWebDAVStorage(url, username, password, root string) *WebDAVStorage {
|
||||||
|
client := gowebdav.NewClient(url, username, password)
|
||||||
|
return &WebDAVStorage{
|
||||||
|
client: client,
|
||||||
|
root: root,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *WebDAVStorage) getFullPath(path string) string {
|
||||||
|
return filepath.ToSlash(filepath.Join(s.root, path))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *WebDAVStorage) Save(ctx context.Context, path string, reader io.Reader) error {
|
||||||
|
fullPath := s.getFullPath(path)
|
||||||
|
|
||||||
|
// Ensure directory exists
|
||||||
|
dir := filepath.Dir(fullPath)
|
||||||
|
if dir != "." && dir != "/" {
|
||||||
|
parts := strings.Split(strings.Trim(dir, "/"), "/")
|
||||||
|
current := ""
|
||||||
|
for _, part := range parts {
|
||||||
|
current += "/" + part
|
||||||
|
_ = s.client.Mkdir(current, 0755)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return s.client.WriteStream(fullPath, reader, 0644)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *WebDAVStorage) Open(ctx context.Context, path string) (io.ReadCloser, error) {
|
||||||
|
fullPath := s.getFullPath(path)
|
||||||
|
return s.client.ReadStream(fullPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *WebDAVStorage) Delete(ctx context.Context, path string) error {
|
||||||
|
fullPath := s.getFullPath(path)
|
||||||
|
return s.client.Remove(fullPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *WebDAVStorage) Exists(ctx context.Context, path string) (bool, error) {
|
||||||
|
fullPath := s.getFullPath(path)
|
||||||
|
_, err := s.client.Stat(fullPath)
|
||||||
|
if err != nil {
|
||||||
|
// gowebdav's Stat returns error if not found
|
||||||
|
// We could check for 404 but gowebdav doesn't export error types easily
|
||||||
|
// Usually we check if it's a 404
|
||||||
|
if strings.Contains(err.Error(), "404") || strings.Contains(err.Error(), "not found") {
|
||||||
|
return false, nil
|
||||||
|
}
|
||||||
|
return false, err
|
||||||
|
}
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
39
internal/task/cleaner.go
Normal file
39
internal/task/cleaner.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package task
|
||||||
|
|
||||||
|
import (
|
||||||
|
"FileRelay/internal/service"
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Cleaner struct {
|
||||||
|
batchService *service.BatchService
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewCleaner() *Cleaner {
|
||||||
|
return &Cleaner{
|
||||||
|
batchService: service.NewBatchService(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Cleaner) Start(ctx context.Context) {
|
||||||
|
ticker := time.NewTicker(1 * time.Hour)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-ticker.C:
|
||||||
|
c.Clean()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *Cleaner) Clean() {
|
||||||
|
slog.Info("Running cleanup task")
|
||||||
|
if err := c.batchService.Cleanup(context.Background()); err != nil {
|
||||||
|
slog.Error("Error during cleanup", "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
321
main.go
Normal file
321
main.go
Normal file
@@ -0,0 +1,321 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
_ "FileRelay/docs"
|
||||||
|
"FileRelay/internal/api/admin"
|
||||||
|
"FileRelay/internal/api/middleware"
|
||||||
|
"FileRelay/internal/api/public"
|
||||||
|
"FileRelay/internal/bootstrap"
|
||||||
|
"FileRelay/internal/config"
|
||||||
|
"FileRelay/internal/model"
|
||||||
|
"FileRelay/internal/task"
|
||||||
|
"context"
|
||||||
|
"embed"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"io/fs"
|
||||||
|
"log"
|
||||||
|
"log/slog"
|
||||||
|
"mime"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gin-contrib/cors"
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
swaggerFiles "github.com/swaggo/files"
|
||||||
|
ginSwagger "github.com/swaggo/gin-swagger"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed all:web
|
||||||
|
var webFS embed.FS
|
||||||
|
|
||||||
|
// @title 文件暂存柜 API
|
||||||
|
// @version 1.0
|
||||||
|
// @description 自托管的文件暂存柜后端系统 API 文档
|
||||||
|
// @termsOfService http://swagger.io/terms/
|
||||||
|
|
||||||
|
// @contact.name API Support
|
||||||
|
// @contact.url http://www.swagger.io/support
|
||||||
|
// @contact.email support@swagger.io
|
||||||
|
|
||||||
|
// @license.name Apache 2.0
|
||||||
|
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html
|
||||||
|
|
||||||
|
// @BasePath /
|
||||||
|
|
||||||
|
// @securityDefinitions.apikey AdminAuth
|
||||||
|
// @in header
|
||||||
|
// @name Authorization
|
||||||
|
// @description Type "Bearer <JWT-Token>" or "Bearer <API-Token>" to authenticate. API Token must have 'admin' scope.
|
||||||
|
|
||||||
|
// @securityDefinitions.apikey APITokenAuth
|
||||||
|
// @in header
|
||||||
|
// @name Authorization
|
||||||
|
// @description Type "Bearer <API-Token>" to authenticate. Required scope depends on the endpoint.
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
// 注册常用 MIME 类型
|
||||||
|
mime.AddExtensionType(".js", "application/javascript")
|
||||||
|
mime.AddExtensionType(".css", "text/css")
|
||||||
|
mime.AddExtensionType(".woff", "font/woff")
|
||||||
|
mime.AddExtensionType(".woff2", "font/woff2")
|
||||||
|
mime.AddExtensionType(".svg", "image/svg+xml")
|
||||||
|
|
||||||
|
// 解析命令行参数
|
||||||
|
configPath := flag.String("config", "config/config.yaml", "path to config file")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
// 1. 加载配置
|
||||||
|
if err := config.LoadConfig(*configPath); err != nil {
|
||||||
|
log.Fatalf("Failed to load config: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 初始化日志
|
||||||
|
bootstrap.InitLog()
|
||||||
|
|
||||||
|
port := config.GlobalConfig.Site.Port
|
||||||
|
if port <= 0 {
|
||||||
|
port = 8080
|
||||||
|
}
|
||||||
|
|
||||||
|
printBanner(*configPath, port)
|
||||||
|
|
||||||
|
// 2. 初始化
|
||||||
|
bootstrap.InitDB()
|
||||||
|
|
||||||
|
// 3. 启动清理任务
|
||||||
|
cleaner := task.NewCleaner()
|
||||||
|
go cleaner.Start(context.Background())
|
||||||
|
|
||||||
|
// 4. 设置路由
|
||||||
|
r := gin.New()
|
||||||
|
r.Use(gin.Recovery())
|
||||||
|
|
||||||
|
// 自定义 Gin 日志中间件,使用 slog
|
||||||
|
r.Use(func(c *gin.Context) {
|
||||||
|
start := time.Now()
|
||||||
|
path := c.Request.URL.Path
|
||||||
|
query := c.Request.URL.RawQuery
|
||||||
|
|
||||||
|
c.Next()
|
||||||
|
|
||||||
|
end := time.Now()
|
||||||
|
latency := end.Sub(start)
|
||||||
|
|
||||||
|
if len(c.Errors) > 0 {
|
||||||
|
for _, e := range c.Errors.Errors() {
|
||||||
|
slog.Error("Request error", "error", e, "path", path)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
attributes := []any{
|
||||||
|
"status", c.Writer.Status(),
|
||||||
|
"method", c.Request.Method,
|
||||||
|
"path", path,
|
||||||
|
"ip", c.ClientIP(),
|
||||||
|
"latency", latency,
|
||||||
|
}
|
||||||
|
if query != "" {
|
||||||
|
attributes = append(attributes, "query", query)
|
||||||
|
}
|
||||||
|
slog.Info("Request", attributes...)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 配置更完善的 CORS
|
||||||
|
corsConfig := cors.DefaultConfig()
|
||||||
|
corsConfig.AllowAllOrigins = true
|
||||||
|
corsConfig.AllowHeaders = append(corsConfig.AllowHeaders, "Authorization", "Accept", "X-Requested-With")
|
||||||
|
corsConfig.AllowMethods = append(corsConfig.AllowMethods, "OPTIONS")
|
||||||
|
r.Use(cors.New(corsConfig))
|
||||||
|
|
||||||
|
// Swagger 文档
|
||||||
|
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
|
||||||
|
|
||||||
|
// 公共接口
|
||||||
|
uploadHandler := public.NewUploadHandler()
|
||||||
|
pickupHandler := public.NewPickupHandler()
|
||||||
|
publicConfigHandler := public.NewConfigHandler()
|
||||||
|
|
||||||
|
api := r.Group("/api")
|
||||||
|
{
|
||||||
|
api.GET("/config", publicConfigHandler.GetPublicConfig)
|
||||||
|
// 统一使用 /batches 作为资源路径
|
||||||
|
api.POST("/batches", middleware.UploadAuth(), uploadHandler.Upload)
|
||||||
|
api.POST("/batches/text", middleware.UploadAuth(), uploadHandler.UploadText)
|
||||||
|
api.GET("/batches/:pickup_code", middleware.PickupRateLimit(), middleware.APITokenAuth(model.ScopePickup, true), pickupHandler.Pickup)
|
||||||
|
api.GET("/batches/:pickup_code/count", middleware.PickupRateLimit(), pickupHandler.GetDownloadCount)
|
||||||
|
api.GET("/batches/:pickup_code/download", middleware.APITokenAuth(model.ScopePickup, true), pickupHandler.DownloadBatch)
|
||||||
|
// 文件下载路由,支持直观的文件名结尾
|
||||||
|
api.GET("/files/:file_id/:filename", middleware.APITokenAuth(model.ScopePickup, true), pickupHandler.DownloadFile)
|
||||||
|
// 保持旧路由兼容性
|
||||||
|
api.GET("/files/:file_id/download", middleware.APITokenAuth(model.ScopePickup, true), pickupHandler.DownloadFile)
|
||||||
|
|
||||||
|
// 保持旧路由兼容性 (可选,但为了平滑过渡通常建议保留一段时间或直接更新)
|
||||||
|
// 这里根据需求“调整不符合规范的”,我将直接采用新路由
|
||||||
|
}
|
||||||
|
|
||||||
|
// 管理员接口
|
||||||
|
authHandler := admin.NewAuthHandler()
|
||||||
|
batchHandler := admin.NewBatchHandler()
|
||||||
|
tokenHandler := admin.NewTokenHandler()
|
||||||
|
configHandler := admin.NewConfigHandler()
|
||||||
|
|
||||||
|
api.POST("/admin/login", authHandler.Login)
|
||||||
|
|
||||||
|
adm := api.Group("/admin")
|
||||||
|
adm.Use(middleware.AdminAuth())
|
||||||
|
{
|
||||||
|
adm.GET("/config", configHandler.GetConfig)
|
||||||
|
adm.PUT("/config", configHandler.UpdateConfig)
|
||||||
|
|
||||||
|
adm.GET("/batches", batchHandler.ListBatches)
|
||||||
|
adm.POST("/batches/clean", batchHandler.CleanBatches)
|
||||||
|
adm.GET("/batches/:batch_id", batchHandler.GetBatch)
|
||||||
|
adm.PUT("/batches/:batch_id", batchHandler.UpdateBatch)
|
||||||
|
adm.DELETE("/batches/:batch_id", batchHandler.DeleteBatch)
|
||||||
|
|
||||||
|
adm.GET("/api-tokens", tokenHandler.ListTokens)
|
||||||
|
adm.POST("/api-tokens", tokenHandler.CreateToken)
|
||||||
|
adm.DELETE("/api-tokens/:id", tokenHandler.DeleteToken)
|
||||||
|
adm.POST("/api-tokens/:id/revoke", tokenHandler.RevokeToken)
|
||||||
|
adm.POST("/api-tokens/:id/recover", tokenHandler.RecoverToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 静态资源服务 (放在最后,确保 API 路由优先)
|
||||||
|
webSub, _ := fs.Sub(webFS, "web")
|
||||||
|
|
||||||
|
r.NoRoute(func(c *gin.Context) {
|
||||||
|
path := c.Request.URL.Path
|
||||||
|
|
||||||
|
// 如果请求的是 API 或 Swagger,则不处理静态资源 (让其返回 404)
|
||||||
|
// 注意:此处不排除 /admin,因为 /admin 通常是前端 SPA 的路由地址
|
||||||
|
if strings.HasPrefix(path, "/api") || strings.HasPrefix(path, "/swagger") {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 辅助函数:尝试从外部或嵌入服务文件
|
||||||
|
serveFile := func(relPath string, allowExternal bool) bool {
|
||||||
|
// 1. 优先尝试外部路径
|
||||||
|
if allowExternal && config.GlobalConfig.Web.Path != "" {
|
||||||
|
fullPath := filepath.Join(config.GlobalConfig.Web.Path, relPath)
|
||||||
|
if info, err := os.Stat(fullPath); err == nil && !info.IsDir() {
|
||||||
|
c.File(fullPath)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 尝试嵌入式文件
|
||||||
|
f, err := webSub.Open(relPath)
|
||||||
|
if err == nil {
|
||||||
|
defer f.Close()
|
||||||
|
stat, err := f.Stat()
|
||||||
|
if err == nil && !stat.IsDir() {
|
||||||
|
// 使用 http.ServeContent 避免 c.FileFromFS 重定向问题
|
||||||
|
if rs, ok := f.(io.ReadSeeker); ok {
|
||||||
|
// 显式设置 Content-Type,防止某些环境下识别失败
|
||||||
|
ext := filepath.Ext(relPath)
|
||||||
|
ctype := mime.TypeByExtension(ext)
|
||||||
|
if ctype != "" {
|
||||||
|
c.Header("Content-Type", ctype)
|
||||||
|
}
|
||||||
|
http.ServeContent(c.Writer, c.Request, stat.Name(), stat.ModTime(), rs)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 1. 尝试直接请求的文件 (如果是 / 则尝试 index.html)
|
||||||
|
requestedPath := strings.TrimPrefix(path, "/")
|
||||||
|
if requestedPath == "" {
|
||||||
|
requestedPath = "index.html"
|
||||||
|
}
|
||||||
|
|
||||||
|
if serveFile(requestedPath, true) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. SPA 支持:对于非文件请求(没有后缀或不包含点),尝试返回 index.html
|
||||||
|
// 如果请求的是 assets 目录下的文件(包含点)却没找到,不应该回退到 index.html
|
||||||
|
isAsset := strings.Contains(requestedPath, ".")
|
||||||
|
if !isAsset || requestedPath == "index.html" {
|
||||||
|
if serveFile("index.html", true) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 最终找不到则返回 404
|
||||||
|
c.Status(http.StatusNotFound)
|
||||||
|
})
|
||||||
|
|
||||||
|
// 5. 运行
|
||||||
|
localIP := getLocalIP()
|
||||||
|
fmt.Println("FileRelay service is ready:")
|
||||||
|
fmt.Printf(" - Local: http://localhost:%d\n", port)
|
||||||
|
fmt.Printf(" - LAN: http://%s:%d\n", localIP, port)
|
||||||
|
fmt.Printf(" - API Doc: http://localhost:%d/swagger/index.html\n", port)
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
slog.Info("FileRelay service is ready",
|
||||||
|
"local_url", fmt.Sprintf("http://localhost:%d", port),
|
||||||
|
"lan_url", fmt.Sprintf("http://%s:%d", localIP, port),
|
||||||
|
"docs_url", fmt.Sprintf("http://localhost:%d/swagger/index.html", port),
|
||||||
|
)
|
||||||
|
|
||||||
|
r.Run(fmt.Sprintf(":%d", port))
|
||||||
|
}
|
||||||
|
|
||||||
|
func getLocalIP() string {
|
||||||
|
addrs, err := net.InterfaceAddrs()
|
||||||
|
if err != nil {
|
||||||
|
return "127.0.0.1"
|
||||||
|
}
|
||||||
|
for _, address := range addrs {
|
||||||
|
if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
|
||||||
|
if ipnet.IP.To4() != nil {
|
||||||
|
return ipnet.IP.String()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "127.0.0.1"
|
||||||
|
}
|
||||||
|
|
||||||
|
func printBanner(configPath string, port int) {
|
||||||
|
fmt.Println(`
|
||||||
|
_____ _ _ _____ _
|
||||||
|
| ___(_) | ___| _ \ ___| | __ _ _ _
|
||||||
|
| |_ | | |/ _ \ |_) / _ \ |/ _' | | | |
|
||||||
|
| _| | | | __/ _ < __/ | (_| | |_| |
|
||||||
|
|_| |_|_|\___|_| \_\___|_|\__,_|\__, |
|
||||||
|
|___/
|
||||||
|
`)
|
||||||
|
fmt.Printf(" Config: %s\n", configPath)
|
||||||
|
fmt.Printf(" Port: %d\n", port)
|
||||||
|
fmt.Printf(" Database: %s\n", config.GlobalConfig.Database.Type)
|
||||||
|
fmt.Printf(" Storage: %s\n", config.GlobalConfig.Storage.Type)
|
||||||
|
|
||||||
|
webPath := config.GlobalConfig.Web.Path
|
||||||
|
if webPath != "" {
|
||||||
|
if info, err := os.Stat(webPath); err == nil && info.IsDir() {
|
||||||
|
fmt.Printf(" Web Assets: External (%s)\n", webPath)
|
||||||
|
} else {
|
||||||
|
fmt.Printf(" Web Assets: Embedded (External path %s not found)\n", webPath)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
fmt.Println(" Web Assets: Embedded")
|
||||||
|
}
|
||||||
|
fmt.Println()
|
||||||
|
|
||||||
|
slog.Info("Starting FileRelay service",
|
||||||
|
"config", configPath,
|
||||||
|
"port", port,
|
||||||
|
"db_type", config.GlobalConfig.Database.Type,
|
||||||
|
"storage_type", config.GlobalConfig.Storage.Type,
|
||||||
|
)
|
||||||
|
}
|
||||||
67
scripts/build.bat
Normal file
67
scripts/build.bat
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
@echo off
|
||||||
|
chcp 65001 > nul
|
||||||
|
setlocal enabledelayedexpansion
|
||||||
|
|
||||||
|
:: 切换到项目根目录
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
|
||||||
|
set APP_NAME=filerelay
|
||||||
|
set OUTPUT_DIR=output
|
||||||
|
|
||||||
|
echo 开始构建 %APP_NAME% 多平台二进制文件...
|
||||||
|
|
||||||
|
:: 清理 output 目录
|
||||||
|
if exist "%OUTPUT_DIR%" (
|
||||||
|
echo 正在清理 %OUTPUT_DIR% 目录...
|
||||||
|
rd /s /q "%OUTPUT_DIR%"
|
||||||
|
)
|
||||||
|
|
||||||
|
mkdir "%OUTPUT_DIR%"
|
||||||
|
|
||||||
|
:: 前端构建
|
||||||
|
echo 正在构建前端项目...
|
||||||
|
pushd webapp
|
||||||
|
call npm install
|
||||||
|
if %ERRORLEVEL% neq 0 (
|
||||||
|
echo npm install 失败,停止编译。
|
||||||
|
popd
|
||||||
|
exit /b %ERRORLEVEL%
|
||||||
|
)
|
||||||
|
call npm run build
|
||||||
|
if %ERRORLEVEL% neq 0 (
|
||||||
|
echo 前端构建失败,停止编译。
|
||||||
|
popd
|
||||||
|
exit /b %ERRORLEVEL%
|
||||||
|
)
|
||||||
|
popd
|
||||||
|
|
||||||
|
:: 定义目标平台 (OS/Arch)
|
||||||
|
set PLATFORMS=linux/amd64 linux/arm64 windows/amd64 windows/arm64 darwin/amd64 darwin/arm64
|
||||||
|
|
||||||
|
for %%P in (%PLATFORMS%) do (
|
||||||
|
for /f "tokens=1,2 delims=/" %%A in ("%%P") do (
|
||||||
|
set GOOS=%%A
|
||||||
|
set GOARCH=%%B
|
||||||
|
|
||||||
|
set OUTPUT_NAME=%APP_NAME%-%%A-%%B
|
||||||
|
if "%%A"=="windows" set OUTPUT_NAME=!OUTPUT_NAME!.exe
|
||||||
|
|
||||||
|
echo 正在编译 %%A/%%B...
|
||||||
|
|
||||||
|
go build -o "%OUTPUT_DIR%\!OUTPUT_NAME!" main.go
|
||||||
|
|
||||||
|
if !ERRORLEVEL! equ 0 (
|
||||||
|
echo %%A/%%B 编译成功
|
||||||
|
:: 压缩为 tar.gz (Windows 10+ 自带 tar)
|
||||||
|
tar -czf "%OUTPUT_DIR%\!OUTPUT_NAME!.tar.gz" -C "%OUTPUT_DIR%" "!OUTPUT_NAME!"
|
||||||
|
:: 删除原始二进制文件
|
||||||
|
del "%OUTPUT_DIR%\!OUTPUT_NAME!"
|
||||||
|
) else (
|
||||||
|
echo %%A/%%B 编译失败
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
echo ----------------------------------------
|
||||||
|
echo 多平台打包完成!输出目录: %OUTPUT_DIR%
|
||||||
|
pause
|
||||||
78
scripts/build.ps1
Normal file
78
scripts/build.ps1
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
# 构建脚本
|
||||||
|
# 切换到项目根目录
|
||||||
|
Set-Location -Path (Join-Path $PSScriptRoot "..")
|
||||||
|
|
||||||
|
$APP_NAME = "filerelay"
|
||||||
|
$OUTPUT_DIR = "output"
|
||||||
|
|
||||||
|
# 定义目标平台
|
||||||
|
$PLATFORMS = @(
|
||||||
|
"linux/amd64",
|
||||||
|
"linux/arm64",
|
||||||
|
"windows/amd64",
|
||||||
|
"windows/arm64",
|
||||||
|
"darwin/amd64",
|
||||||
|
"darwin/arm64"
|
||||||
|
)
|
||||||
|
|
||||||
|
Write-Host "开始构建 $APP_NAME 多平台二进制文件..." -ForegroundColor Cyan
|
||||||
|
|
||||||
|
# 清理 output 目录
|
||||||
|
if (Test-Path $OUTPUT_DIR) {
|
||||||
|
Write-Host "正在清理 $OUTPUT_DIR 目录..."
|
||||||
|
Remove-Item -Path $OUTPUT_DIR -Recurse -Force
|
||||||
|
}
|
||||||
|
|
||||||
|
New-Item -Path $OUTPUT_DIR -ItemType Directory -Force | Out-Null
|
||||||
|
|
||||||
|
# 前端构建
|
||||||
|
Write-Host "正在构建前端项目..." -ForegroundColor Cyan
|
||||||
|
Push-Location webapp
|
||||||
|
npm install
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host "npm install 失败,停止编译。" -ForegroundColor Red
|
||||||
|
Pop-Location
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
}
|
||||||
|
npm run build
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host "前端构建失败,停止编译。" -ForegroundColor Red
|
||||||
|
Pop-Location
|
||||||
|
exit $LASTEXITCODE
|
||||||
|
}
|
||||||
|
Pop-Location
|
||||||
|
|
||||||
|
# 循环构建各平台
|
||||||
|
foreach ($PLATFORM in $PLATFORMS) {
|
||||||
|
$parts = $PLATFORM -split "/"
|
||||||
|
$os = $parts[0]
|
||||||
|
$arch = $parts[1]
|
||||||
|
|
||||||
|
$outputName = "$($APP_NAME)-$($os)-$($arch)"
|
||||||
|
if ($os -eq "windows") {
|
||||||
|
$outputName += ".exe"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "正在编译 $($os)/$($arch)..."
|
||||||
|
$env:GOOS = $os
|
||||||
|
$env:GOARCH = $arch
|
||||||
|
|
||||||
|
go build -o (Join-Path $OUTPUT_DIR $outputName) main.go
|
||||||
|
|
||||||
|
if ($LASTEXITCODE -eq 0) {
|
||||||
|
Write-Host " $($os)/$($arch) 编译成功" -ForegroundColor Green
|
||||||
|
# 压缩为 tar.gz
|
||||||
|
tar -czf (Join-Path $OUTPUT_DIR "$outputName.tar.gz") -C $OUTPUT_DIR $outputName
|
||||||
|
# 删除原始二进制文件
|
||||||
|
Remove-Item (Join-Path $OUTPUT_DIR $outputName)
|
||||||
|
} else {
|
||||||
|
Write-Host " $($os)/$($arch) 编译失败" -ForegroundColor Red
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# 重置环境变量
|
||||||
|
$env:GOOS = $null
|
||||||
|
$env:GOARCH = $null
|
||||||
|
|
||||||
|
Write-Host "----------------------------------------" -ForegroundColor Cyan
|
||||||
|
Write-Host "多平台打包完成!输出目录: $OUTPUT_DIR" -ForegroundColor Green
|
||||||
69
scripts/build.sh
Normal file
69
scripts/build.sh
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# 获取脚本所在目录并切换到项目根目录
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
# 设置变量
|
||||||
|
APP_NAME="filerelay"
|
||||||
|
OUTPUT_DIR="output"
|
||||||
|
|
||||||
|
# 定义目标平台
|
||||||
|
PLATFORMS=(
|
||||||
|
"linux/amd64"
|
||||||
|
"linux/arm64"
|
||||||
|
"windows/amd64"
|
||||||
|
"windows/arm64"
|
||||||
|
"darwin/amd64"
|
||||||
|
"darwin/arm64"
|
||||||
|
)
|
||||||
|
|
||||||
|
echo "开始构建 $APP_NAME 多平台二进制文件..."
|
||||||
|
|
||||||
|
# 清理 output 目录
|
||||||
|
if [ -d "$OUTPUT_DIR" ]; then
|
||||||
|
echo "正在清理 $OUTPUT_DIR 目录..."
|
||||||
|
rm -rf "$OUTPUT_DIR"
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "$OUTPUT_DIR"
|
||||||
|
|
||||||
|
# 前端构建
|
||||||
|
echo "正在构建前端项目..."
|
||||||
|
cd webapp
|
||||||
|
npm install
|
||||||
|
npm run build
|
||||||
|
if [ $? -ne 0 ]; then
|
||||||
|
echo "前端构建失败,停止编译。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
cd ..
|
||||||
|
|
||||||
|
# 循环编译各平台
|
||||||
|
for PLATFORM in "${PLATFORMS[@]}"; do
|
||||||
|
# 分离 OS 和 ARCH
|
||||||
|
OS=$(echo $PLATFORM | cut -d'/' -f1)
|
||||||
|
ARCH=$(echo $PLATFORM | cut -d'/' -f2)
|
||||||
|
|
||||||
|
# 设置输出名称
|
||||||
|
OUTPUT_NAME="${APP_NAME}-${OS}-${ARCH}"
|
||||||
|
if [ "$OS" = "windows" ]; then
|
||||||
|
OUTPUT_NAME="${OUTPUT_NAME}.exe"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "正在编译 ${OS}/${ARCH}..."
|
||||||
|
GOOS=$OS GOARCH=$ARCH go build -o "${OUTPUT_DIR}/${OUTPUT_NAME}" main.go
|
||||||
|
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
echo " ${OS}/${ARCH} 编译成功"
|
||||||
|
# 压缩为 tar.gz
|
||||||
|
tar -czf "${OUTPUT_DIR}/${OUTPUT_NAME}.tar.gz" -C "${OUTPUT_DIR}" "${OUTPUT_NAME}"
|
||||||
|
# 删除原始二进制文件
|
||||||
|
rm "${OUTPUT_DIR}/${OUTPUT_NAME}"
|
||||||
|
else
|
||||||
|
echo " ${OS}/${ARCH} 编译失败"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
|
||||||
|
echo "----------------------------------------"
|
||||||
|
echo "多平台打包完成!输出目录: $OUTPUT_DIR"
|
||||||
|
ls -R "$OUTPUT_DIR"
|
||||||
101
scripts/deploy.sh
Normal file
101
scripts/deploy.sh
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# 定时任务示例 (每30分钟执行一次):
|
||||||
|
# */30 * * * * /path/to/project/scripts/deploy.sh >> /path/to/project/scripts/deploy_cron.log 2>&1
|
||||||
|
|
||||||
|
# 项目根目录
|
||||||
|
# 假设脚本位于 scripts 目录下
|
||||||
|
PROJECT_DIR=$(cd $(dirname $0)/.. && pwd)
|
||||||
|
cd $PROJECT_DIR
|
||||||
|
|
||||||
|
# 日志文件
|
||||||
|
LOG_FILE="$PROJECT_DIR/scripts/deploy.log"
|
||||||
|
|
||||||
|
log() {
|
||||||
|
echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
|
||||||
|
}
|
||||||
|
|
||||||
|
# 确保在项目根目录
|
||||||
|
if [ ! -f "docker-compose.yaml" ]; then
|
||||||
|
log "错误: 未能在 $PROJECT_DIR 找到 docker-compose.yml,请确保脚本位置正确。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "开始检查更新..."
|
||||||
|
|
||||||
|
# 获取远程代码
|
||||||
|
git fetch origin
|
||||||
|
|
||||||
|
# 获取当前分支名
|
||||||
|
BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||||
|
|
||||||
|
# 检查本地分支是否有上游分支
|
||||||
|
UPSTREAM=$(git rev-parse --abbrev-ref @{u} 2>/dev/null)
|
||||||
|
if [ -z "$UPSTREAM" ]; then
|
||||||
|
log "错误: 当前分支 $BRANCH 没有设置上游分支,无法自动对比更新。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 检查本地是否落后于远程
|
||||||
|
LOCAL=$(git rev-parse HEAD)
|
||||||
|
REMOTE=$(git rev-parse "$UPSTREAM")
|
||||||
|
|
||||||
|
if [ "$LOCAL" = "$REMOTE" ]; then
|
||||||
|
log "代码已是最新 ($LOCAL),无需更新。"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "检测到远程变更 ($LOCAL -> $REMOTE),准备开始升级..."
|
||||||
|
|
||||||
|
# 检查是否有本地修改
|
||||||
|
HAS_CHANGES=$(git status --porcelain)
|
||||||
|
|
||||||
|
if [ -n "$HAS_CHANGES" ]; then
|
||||||
|
log "检测到本地修改,正在暂存以保留个性化配置..."
|
||||||
|
git stash
|
||||||
|
STASHED=true
|
||||||
|
else
|
||||||
|
STASHED=false
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 拉取新代码
|
||||||
|
log "正在拉取远程代码 ($BRANCH)..."
|
||||||
|
if git pull origin "$BRANCH"; then
|
||||||
|
log "代码拉取成功。"
|
||||||
|
else
|
||||||
|
log "错误: 代码拉取失败。"
|
||||||
|
if [ "$STASHED" = true ]; then
|
||||||
|
git stash pop
|
||||||
|
fi
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 恢复本地修改
|
||||||
|
if [ "$STASHED" = true ]; then
|
||||||
|
log "正在恢复本地修改..."
|
||||||
|
if git stash pop; then
|
||||||
|
log "本地修改已成功恢复。"
|
||||||
|
else
|
||||||
|
log "警告: 恢复本地修改时发生冲突,请手动检查 docker-compose.yml 等文件。"
|
||||||
|
# 即使冲突也尝试继续,或者你可以选择在此退出
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 确定 docker-compose 命令
|
||||||
|
DOCKER_COMPOSE_BIN="docker-compose"
|
||||||
|
if ! command -v $DOCKER_COMPOSE_BIN &> /dev/null; then
|
||||||
|
DOCKER_COMPOSE_BIN="docker compose"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 执行 docker-compose 部署
|
||||||
|
log "正在执行 $DOCKER_COMPOSE_BIN 部署..."
|
||||||
|
if $DOCKER_COMPOSE_BIN up -d --build; then
|
||||||
|
log "服务升级成功!"
|
||||||
|
# 清理无用镜像(可选)
|
||||||
|
docker image prune -f
|
||||||
|
else
|
||||||
|
log "错误: $DOCKER_COMPOSE_BIN 部署失败。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
log "部署任务完成。"
|
||||||
59
scripts/release_tag.bat
Normal file
59
scripts/release_tag.bat
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
@echo off
|
||||||
|
chcp 65001 > nul
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
:: 切换到项目根目录
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
|
||||||
|
if "%~1"=="" (
|
||||||
|
echo 使用方法: release_tag.bat <tag_name>
|
||||||
|
echo 例如: release_tag.bat v1.0.0
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
set TAG_NAME=%~1
|
||||||
|
|
||||||
|
REM 1. 检查当前分支是否为 master
|
||||||
|
for /f "tokens=*" %%i in ('git rev-parse --abbrev-ref HEAD') do set CURRENT_BRANCH=%%i
|
||||||
|
if not "%CURRENT_BRANCH%"=="master" (
|
||||||
|
echo 错误:当前分支是 %CURRENT_BRANCH%,只能在 master 分支上创建 Tag。
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
REM 2. 检查本地是否有未提交的内容
|
||||||
|
for /f "tokens=*" %%i in ('git status --porcelain') do (
|
||||||
|
echo 错误:本地有未提交的更改,请先提交或 stash。
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
REM 3. 检查本地与远程 master 分支是否一致
|
||||||
|
echo 正在从远程获取最新 master 分支信息...
|
||||||
|
git fetch origin master
|
||||||
|
if %ERRORLEVEL% neq 0 (
|
||||||
|
echo 错误:获取远程分支信息失败。
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
for /f "tokens=*" %%i in ('git rev-parse HEAD') do set LOCAL_HASH=%%i
|
||||||
|
for /f "tokens=*" %%i in ('git rev-parse origin/master') do set REMOTE_HASH=%%i
|
||||||
|
|
||||||
|
if not "%LOCAL_HASH%"=="%REMOTE_HASH%" (
|
||||||
|
echo 错误:本地 master 分支与远程 origin/master 不一致,请先 pull 或 push。
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
echo 安全检查通过,正在处理 Tag: %TAG_NAME%
|
||||||
|
|
||||||
|
:: 在本地创建或更新 Tag
|
||||||
|
git tag -f %TAG_NAME%
|
||||||
|
|
||||||
|
:: 强制推送到远程
|
||||||
|
echo 正在强制推送到远程...
|
||||||
|
git push origin %TAG_NAME% --force
|
||||||
|
|
||||||
|
if %ERRORLEVEL% equ 0 (
|
||||||
|
echo 成功!Tag %TAG_NAME% 已发布并同步至远程。
|
||||||
|
) else (
|
||||||
|
echo 失败:推送过程中出现错误。
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
53
scripts/release_tag.ps1
Normal file
53
scripts/release_tag.ps1
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
param (
|
||||||
|
[Parameter(Mandatory=$true, Position=0)]
|
||||||
|
[string]$TagName
|
||||||
|
)
|
||||||
|
|
||||||
|
# 切换到项目根目录
|
||||||
|
Set-Location -Path (Join-Path $PSScriptRoot "..")
|
||||||
|
|
||||||
|
# 1. 检查当前分支是否为 master
|
||||||
|
$currentBranch = git rev-parse --abbrev-ref HEAD
|
||||||
|
if ($currentBranch -ne "master") {
|
||||||
|
Write-Host "错误:当前分支是 $currentBranch,只能在 master 分支上创建 Tag。" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# 2. 检查本地是否有未提交的内容
|
||||||
|
$status = git status --porcelain
|
||||||
|
if ($null -ne $status -and $status.Length -gt 0) {
|
||||||
|
Write-Host "错误:本地有未提交的更改,请先提交或 stash。" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# 3. 检查本地与远程 master 分支是否一致
|
||||||
|
Write-Host "正在从远程获取最新 master 分支信息..." -ForegroundColor Cyan
|
||||||
|
git fetch origin master
|
||||||
|
$localHash = git rev-parse HEAD
|
||||||
|
$remoteHash = git rev-parse origin/master
|
||||||
|
|
||||||
|
if ($localHash -ne $remoteHash) {
|
||||||
|
Write-Host "错误:本地 master 分支与远程 origin/master 不一致,请先 pull 或 push。" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host "安全检查通过,正在处理 Tag: $TagName" -ForegroundColor Cyan
|
||||||
|
|
||||||
|
# 在本地创建或更新 Tag
|
||||||
|
git tag -f $TagName
|
||||||
|
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Host "本地创建 Tag 失败。" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# 强制推送到远程
|
||||||
|
Write-Host "正在强制推送到远程..." -ForegroundColor Cyan
|
||||||
|
git push origin $TagName --force
|
||||||
|
|
||||||
|
if ($LASTEXITCODE -eq 0) {
|
||||||
|
Write-Host "成功!Tag $TagName 已发布并同步至远程。" -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Write-Host "失败:推送过程中出现错误。" -ForegroundColor Red
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
55
scripts/release_tag.sh
Normal file
55
scripts/release_tag.sh
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
# 获取脚本所在目录并切换到项目根目录
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
|
||||||
|
# 检查是否提供了 tag 名称
|
||||||
|
if [ -z "$1" ]; then
|
||||||
|
echo "使用方法: scripts/release_tag.sh <tag_name>"
|
||||||
|
echo "例如: scripts/release_tag.sh v1.0.0"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
TAG_NAME=$1
|
||||||
|
|
||||||
|
# 1. 检查当前分支是否为 master
|
||||||
|
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||||
|
if [ "$CURRENT_BRANCH" != "master" ]; then
|
||||||
|
echo "错误:当前分支是 $CURRENT_BRANCH,只能在 master 分支上创建 Tag。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. 检查本地是否有未提交的内容
|
||||||
|
if [ -n "$(git status --porcelain)" ]; then
|
||||||
|
echo "错误:本地有未提交的更改,请先提交或 stash。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 3. 检查本地与远程 master 分支是否一致
|
||||||
|
echo "正在从远程获取最新 master 分支信息..."
|
||||||
|
git fetch origin master
|
||||||
|
LOCAL_HASH=$(git rev-parse HEAD)
|
||||||
|
REMOTE_HASH=$(git rev-parse origin/master)
|
||||||
|
|
||||||
|
if [ "$LOCAL_HASH" != "$REMOTE_HASH" ]; then
|
||||||
|
echo "错误:本地 master 分支与远程 origin/master 不一致,请先 pull 或 push。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "安全检查通过,正在处理 Tag: $TAG_NAME"
|
||||||
|
|
||||||
|
# 在本地创建或更新 Tag
|
||||||
|
# -f 表示如果存在则强制更新
|
||||||
|
git tag -f "$TAG_NAME"
|
||||||
|
|
||||||
|
# 强制推送到远程
|
||||||
|
# --force 会覆盖远程同名 Tag
|
||||||
|
echo "正在强制推送到远程..."
|
||||||
|
git push origin "$TAG_NAME" --force
|
||||||
|
|
||||||
|
if [ $? -eq 0 ]; then
|
||||||
|
echo "成功!Tag $TAG_NAME 已发布并同步至远程。"
|
||||||
|
else
|
||||||
|
echo "失败:推送过程中出现错误。"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
39
scripts/sql/mysql_init.sql
Normal file
39
scripts/sql/mysql_init.sql
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
-- MySQL 初始化语句
|
||||||
|
CREATE TABLE IF NOT EXISTS `file_batches` (
|
||||||
|
`id` varchar(36) PRIMARY KEY,
|
||||||
|
`pickup_code` varchar(255) UNIQUE NOT NULL,
|
||||||
|
`remark` longtext,
|
||||||
|
`expire_type` varchar(255),
|
||||||
|
`expire_at` datetime(3),
|
||||||
|
`max_downloads` bigint,
|
||||||
|
`download_count` bigint DEFAULT 0,
|
||||||
|
`status` varchar(255) DEFAULT 'active',
|
||||||
|
`type` varchar(255) DEFAULT 'file',
|
||||||
|
`content` longtext,
|
||||||
|
`created_at` datetime(3),
|
||||||
|
`updated_at` datetime(3),
|
||||||
|
`deleted_at` datetime(3),
|
||||||
|
KEY `idx_file_batches_deleted_at` (`deleted_at`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `file_items` (
|
||||||
|
`id` varchar(36) PRIMARY KEY,
|
||||||
|
`batch_id` varchar(36) NOT NULL,
|
||||||
|
`original_name` longtext,
|
||||||
|
`storage_path` longtext,
|
||||||
|
`size` bigint,
|
||||||
|
`mime_type` longtext,
|
||||||
|
`created_at` datetime(3),
|
||||||
|
KEY `idx_file_items_batch_id` (`batch_id`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `api_tokens` (
|
||||||
|
`id` bigint unsigned AUTO_INCREMENT PRIMARY KEY,
|
||||||
|
`name` longtext,
|
||||||
|
`token_hash` varchar(255) UNIQUE NOT NULL,
|
||||||
|
`scope` longtext,
|
||||||
|
`expire_at` datetime(3),
|
||||||
|
`last_used_at` datetime(3),
|
||||||
|
`revoked` boolean DEFAULT false,
|
||||||
|
`created_at` datetime(3)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
|
||||||
40
scripts/sql/postgres_init.sql
Normal file
40
scripts/sql/postgres_init.sql
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
-- PostgreSQL 初始化语句
|
||||||
|
CREATE TABLE IF NOT EXISTS "file_batches" (
|
||||||
|
"id" varchar(36) PRIMARY KEY,
|
||||||
|
"pickup_code" varchar(255) UNIQUE NOT NULL,
|
||||||
|
"remark" text,
|
||||||
|
"expire_type" text,
|
||||||
|
"expire_at" timestamptz,
|
||||||
|
"max_downloads" bigint,
|
||||||
|
"download_count" bigint DEFAULT 0,
|
||||||
|
"status" text DEFAULT 'active',
|
||||||
|
"type" text DEFAULT 'file',
|
||||||
|
"content" text,
|
||||||
|
"created_at" timestamptz,
|
||||||
|
"updated_at" timestamptz,
|
||||||
|
"deleted_at" timestamptz
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS "idx_file_batches_deleted_at" ON "file_batches" ("deleted_at");
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS "file_items" (
|
||||||
|
"id" varchar(36) PRIMARY KEY,
|
||||||
|
"batch_id" varchar(36) NOT NULL,
|
||||||
|
"original_name" text,
|
||||||
|
"storage_path" text,
|
||||||
|
"size" bigint,
|
||||||
|
"mime_type" text,
|
||||||
|
"created_at" timestamptz,
|
||||||
|
CONSTRAINT "fk_file_batches_file_items" FOREIGN KEY ("batch_id") REFERENCES "file_batches"("id")
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS "idx_file_items_batch_id" ON "file_items" ("batch_id");
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS "api_tokens" (
|
||||||
|
"id" bigserial PRIMARY KEY,
|
||||||
|
"name" text,
|
||||||
|
"token_hash" varchar(255) UNIQUE NOT NULL,
|
||||||
|
"scope" text,
|
||||||
|
"expire_at" timestamptz,
|
||||||
|
"last_used_at" timestamptz,
|
||||||
|
"revoked" boolean DEFAULT false,
|
||||||
|
"created_at" timestamptz
|
||||||
|
);
|
||||||
40
scripts/sql/sqlite_init.sql
Normal file
40
scripts/sql/sqlite_init.sql
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
-- SQLite 初始化语句
|
||||||
|
CREATE TABLE IF NOT EXISTS `file_batches` (
|
||||||
|
`id` varchar(36) PRIMARY KEY,
|
||||||
|
`pickup_code` varchar(255) UNIQUE NOT NULL,
|
||||||
|
`remark` text,
|
||||||
|
`expire_type` text,
|
||||||
|
`expire_at` datetime,
|
||||||
|
`max_downloads` integer,
|
||||||
|
`download_count` integer DEFAULT 0,
|
||||||
|
`status` text DEFAULT 'active',
|
||||||
|
`type` text DEFAULT 'file',
|
||||||
|
`content` text,
|
||||||
|
`created_at` datetime,
|
||||||
|
`updated_at` datetime,
|
||||||
|
`deleted_at` datetime
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS `idx_file_batches_deleted_at` ON `file_batches` (`deleted_at`);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `file_items` (
|
||||||
|
`id` varchar(36) PRIMARY KEY,
|
||||||
|
`batch_id` varchar(36) NOT NULL,
|
||||||
|
`original_name` text,
|
||||||
|
`storage_path` text,
|
||||||
|
`size` bigint,
|
||||||
|
`mime_type` text,
|
||||||
|
`created_at` datetime,
|
||||||
|
FOREIGN KEY (`batch_id`) REFERENCES `file_batches`(`id`)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS `idx_file_items_batch_id` ON `file_items` (`batch_id`);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS `api_tokens` (
|
||||||
|
`id` integer PRIMARY KEY AUTOINCREMENT,
|
||||||
|
`name` text,
|
||||||
|
`token_hash` varchar(255) UNIQUE NOT NULL,
|
||||||
|
`scope` text,
|
||||||
|
`expire_at` datetime,
|
||||||
|
`last_used_at` datetime,
|
||||||
|
`revoked` boolean DEFAULT 0,
|
||||||
|
`created_at` datetime
|
||||||
|
);
|
||||||
24
webapp/.gitignore
vendored
Normal file
24
webapp/.gitignore
vendored
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# Logs
|
||||||
|
logs
|
||||||
|
*.log
|
||||||
|
npm-debug.log*
|
||||||
|
yarn-debug.log*
|
||||||
|
yarn-error.log*
|
||||||
|
pnpm-debug.log*
|
||||||
|
lerna-debug.log*
|
||||||
|
|
||||||
|
node_modules
|
||||||
|
dist
|
||||||
|
dist-ssr
|
||||||
|
*.local
|
||||||
|
|
||||||
|
# Editor directories and files
|
||||||
|
.vscode/*
|
||||||
|
!.vscode/extensions.json
|
||||||
|
.idea
|
||||||
|
.DS_Store
|
||||||
|
*.suo
|
||||||
|
*.ntvs*
|
||||||
|
*.njsproj
|
||||||
|
*.sln
|
||||||
|
*.sw?
|
||||||
119
webapp/README.md
Normal file
119
webapp/README.md
Normal file
@@ -0,0 +1,119 @@
|
|||||||
|
# 文件中转站前端
|
||||||
|
|
||||||
|
一个基于 Vue 3 + TypeScript + Vite + Shadcn-Vue 构建的文件中转站前端应用。
|
||||||
|
|
||||||
|
## 项目简介
|
||||||
|
|
||||||
|
文件中转站是一个极简的文件暂存服务,用户可以像使用现实中的暂存柜一样,将文件、文本等内容临时存储在网站中,并获得一个取件码用于在其他设备上提取文件。
|
||||||
|
|
||||||
|
## 主要功能
|
||||||
|
|
||||||
|
### 用户功能
|
||||||
|
- **文件上传**: 支持批量上传多种格式的文件
|
||||||
|
- **文本分享**: 快速分享长文本内容
|
||||||
|
- **取件码提取**: 使用取件码获取文件或文本
|
||||||
|
- **过期策略**: 支持按时间或下载次数设置过期规则
|
||||||
|
- **快捷操作**: 一键复制、打包下载等便捷功能
|
||||||
|
|
||||||
|
### 管理功能
|
||||||
|
- **批次管理**: 查看、编辑、删除文件批次
|
||||||
|
- **API Token**: 创建和管理 API 访问凭证
|
||||||
|
- **数据统计**: 系统运行状态和使用统计
|
||||||
|
- **权限控制**: 管理员密码保护的后台系统
|
||||||
|
|
||||||
|
## 技术栈
|
||||||
|
|
||||||
|
- **框架**: Vue 3 + TypeScript
|
||||||
|
- **构建工具**: Vite
|
||||||
|
- **UI 组件**: Shadcn-Vue (基于 Tailwind CSS)
|
||||||
|
- **路由**: Vue Router
|
||||||
|
- **HTTP 客户端**: Axios
|
||||||
|
- **状态管理**: 组合式 API
|
||||||
|
- **代码规范**: ESLint + Prettier
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 环境要求
|
||||||
|
|
||||||
|
- Node.js 18+
|
||||||
|
- npm 或 yarn 或 pnpm
|
||||||
|
|
||||||
|
### 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
### 开发环境
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
启动后访问 `http://localhost:5173`
|
||||||
|
|
||||||
|
### 构建生产版本
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run build
|
||||||
|
```
|
||||||
|
|
||||||
|
### 预览构建结果
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run preview
|
||||||
|
```
|
||||||
|
|
||||||
|
## 环境配置
|
||||||
|
|
||||||
|
创建环境变量文件:
|
||||||
|
|
||||||
|
### `.env` (通用配置)
|
||||||
|
```env
|
||||||
|
VITE_API_URL=http://localhost:8080
|
||||||
|
VITE_APP_TITLE=文件中转站
|
||||||
|
VITE_APP_DESCRIPTION=安全便捷的文件暂存服务
|
||||||
|
```
|
||||||
|
|
||||||
|
### `.env.development` (开发环境)
|
||||||
|
```env
|
||||||
|
VITE_API_URL=http://localhost:8080
|
||||||
|
```
|
||||||
|
|
||||||
|
### `.env.production` (生产环境)
|
||||||
|
```env
|
||||||
|
VITE_API_URL=/api
|
||||||
|
```
|
||||||
|
|
||||||
|
## 页面路由
|
||||||
|
|
||||||
|
### 用户页面
|
||||||
|
- `/` - 首页 (取件/存件切换)
|
||||||
|
- `/upload` - 文件上传页面
|
||||||
|
- `/pickup` - 取件页面
|
||||||
|
- `/pickup/:code` - 直接取件 (URL 包含取件码)
|
||||||
|
|
||||||
|
### 管理页面 (隐藏入口)
|
||||||
|
- `/admin/login` - 管理员登录
|
||||||
|
- `/admin` - 管理概览
|
||||||
|
- `/admin/batches` - 批次管理
|
||||||
|
- `/admin/tokens` - API Token 管理
|
||||||
|
|
||||||
|
## 功能特点
|
||||||
|
|
||||||
|
### 用户体验
|
||||||
|
- **极简设计**: 首页默认取件,一键切换存件模式
|
||||||
|
- **智能识别**: 自动识别文件类型并显示对应图标
|
||||||
|
- **快捷操作**: 支持剪贴板粘贴取件码、一键复制等
|
||||||
|
- **进度反馈**: 上传进度显示和状态提示
|
||||||
|
- **响应式设计**: 完美适配桌面和移动设备
|
||||||
|
|
||||||
|
### 管理功能
|
||||||
|
- **数据统计**: 实时显示系统运行数据
|
||||||
|
- **批次管理**: 支持搜索、筛选、分页查看
|
||||||
|
- **权限控制**: Token 可设置权限范围和过期时间
|
||||||
|
- **操作日志**: 详细的操作记录和状态跟踪
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
MIT License
|
||||||
1713
webapp/api/swagger.json
Normal file
1713
webapp/api/swagger.json
Normal file
File diff suppressed because it is too large
Load Diff
21
webapp/components.json
Normal file
21
webapp/components.json
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://shadcn-vue.com/schema.json",
|
||||||
|
"style": "new-york",
|
||||||
|
"typescript": true,
|
||||||
|
"tailwind": {
|
||||||
|
"config": "",
|
||||||
|
"css": "src/style.css",
|
||||||
|
"baseColor": "neutral",
|
||||||
|
"cssVariables": true,
|
||||||
|
"prefix": ""
|
||||||
|
},
|
||||||
|
"iconLibrary": "lucide",
|
||||||
|
"aliases": {
|
||||||
|
"components": "@/components",
|
||||||
|
"utils": "@/lib/utils",
|
||||||
|
"ui": "@/components/ui",
|
||||||
|
"lib": "@/lib",
|
||||||
|
"composables": "@/composables"
|
||||||
|
},
|
||||||
|
"registries": {}
|
||||||
|
}
|
||||||
67
webapp/doc/BUILD_OPTIMIZATION.md
Normal file
67
webapp/doc/BUILD_OPTIMIZATION.md
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
# 生产构建优化说明
|
||||||
|
|
||||||
|
## 已实现的优化
|
||||||
|
|
||||||
|
### 1. 代码混淆和压缩
|
||||||
|
- 使用 **Terser** 进行代码压缩和混淆
|
||||||
|
- 移除所有 `console.log`、`console.info`、`console.debug` 语句
|
||||||
|
- 移除 `debugger` 语句
|
||||||
|
- 启用变量名混淆 (mangle)
|
||||||
|
- 移除所有注释
|
||||||
|
|
||||||
|
### 2. 文件合并
|
||||||
|
- 禁用代码分割 (`inlineDynamicImports: true`)
|
||||||
|
- 将所有 JavaScript 代码合并为 **单个 JS 文件**
|
||||||
|
- 将所有 CSS 代码合并为 **单个 CSS 文件**
|
||||||
|
|
||||||
|
### 3. 构建结果
|
||||||
|
生产构建后只会生成以下文件:
|
||||||
|
```
|
||||||
|
dist/
|
||||||
|
├── index.html (0.48 kB | gzip: 0.34 kB)
|
||||||
|
├── assets/
|
||||||
|
│ ├── css/
|
||||||
|
│ │ └── style-[hash].css (103.61 kB | gzip: 17.41 kB)
|
||||||
|
│ └── js/
|
||||||
|
│ └── index-[hash].js (535.46 kB | gzip: 155.91 kB)
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 其他优化
|
||||||
|
- 禁用 Source Map(减小文件大小)
|
||||||
|
- 禁用 CSS 代码分割
|
||||||
|
- 设置 chunk 大小警告限制为 2MB
|
||||||
|
- 启用 gzip 压缩大小报告
|
||||||
|
|
||||||
|
## 构建命令
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 生产构建(代码混淆压缩)
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 开发构建(不混淆,保留console)
|
||||||
|
npm run build:dev
|
||||||
|
|
||||||
|
# 预览构建结果
|
||||||
|
npm run preview
|
||||||
|
```
|
||||||
|
|
||||||
|
## 部署优势
|
||||||
|
|
||||||
|
1. **简化部署**:只需部署 3 个文件(index.html + 1个CSS + 1个JS)
|
||||||
|
2. **减少请求**:单个JS文件,减少HTTP请求次数
|
||||||
|
3. **代码保护**:代码混淆和压缩,增加逆向工程难度
|
||||||
|
4. **性能优化**:gzip压缩后总体积约 173 KB
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
- **首次加载时间**:单文件方案会增加首次加载时间,适合中小型应用
|
||||||
|
- **缓存策略**:文件名包含hash,确保浏览器缓存更新
|
||||||
|
- **兼容性**:代码已经过编译,兼容现代浏览器
|
||||||
|
|
||||||
|
## 进一步优化建议
|
||||||
|
|
||||||
|
如果需要更好的加载性能,可以考虑:
|
||||||
|
1. 启用代码分割(移除 `inlineDynamicImports`)
|
||||||
|
2. 按需加载路由组件
|
||||||
|
3. 启用 CDN 加速
|
||||||
|
4. 服务端启用 Brotli 压缩(比 gzip 更好)
|
||||||
237
webapp/doc/I18N_IMPLEMENTATION.md
Normal file
237
webapp/doc/I18N_IMPLEMENTATION.md
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
# 国际化(i18n)实施总结
|
||||||
|
|
||||||
|
## ✅ 已完成的工作
|
||||||
|
|
||||||
|
### 1. 基础设施搭建
|
||||||
|
- ✅ 安装 `vue-i18n@9` 依赖
|
||||||
|
- ✅ 创建 i18n 配置文件 (`src/i18n/index.ts`)
|
||||||
|
- ✅ 创建中文语言文件 (`src/i18n/locales/zh-CN.ts`)
|
||||||
|
- ✅ 创建英文语言文件 (`src/i18n/locales/en-US.ts`)
|
||||||
|
- ✅ 创建 i18n composable (`src/composables/useI18n.ts`)
|
||||||
|
- ✅ 在 main.ts 中集成 i18n
|
||||||
|
|
||||||
|
### 2. 已完成国际化的组件
|
||||||
|
|
||||||
|
#### 用户端页面(100%完成)
|
||||||
|
- ✅ **HomePage.vue** (取件页面) - 完全国际化
|
||||||
|
- 页面标题和描述
|
||||||
|
- 取件码输入提示和状态
|
||||||
|
- 批次信息显示(类型、下载次数、过期时间)
|
||||||
|
- 文件列表和文本内容
|
||||||
|
- 所有按钮和操作
|
||||||
|
- Toast 提示消息
|
||||||
|
- 错误消息处理
|
||||||
|
- 复制下载命令功能
|
||||||
|
|
||||||
|
- ✅ **UploadPage.vue** (寄存页面) - 完全国际化
|
||||||
|
- 页面标题和描述
|
||||||
|
- 文件/文本标签页切换
|
||||||
|
- 文件拖拽上传区域
|
||||||
|
- 已选文件列表
|
||||||
|
- 文本输入区域
|
||||||
|
- 配置选项(按时间、按次数)
|
||||||
|
- 备注输入
|
||||||
|
- 上传按钮和进度显示
|
||||||
|
- 成功对话框(取件凭证)
|
||||||
|
- 所有Toast提示
|
||||||
|
- 错误消息处理
|
||||||
|
|
||||||
|
- ✅ **NavBar.vue** (导航栏) - 完全国际化
|
||||||
|
- 站点标题和描述(带默认值)
|
||||||
|
- 取件/寄存切换按钮
|
||||||
|
|
||||||
|
#### 管理后台页面(100%完成)
|
||||||
|
- ✅ **AdminLogin.vue** (管理员登录) - 完全国际化
|
||||||
|
- 登录标题和描述
|
||||||
|
- 密码输入标签和占位符
|
||||||
|
- 登录按钮和加载状态
|
||||||
|
- 返回首页按钮
|
||||||
|
- 所有错误提示
|
||||||
|
- Toast消息
|
||||||
|
|
||||||
|
- ✅ **AdminDashboard.vue** (管理概览) - 完全国际化
|
||||||
|
- 页面标题和描述
|
||||||
|
- 统计卡片(总批次数、活跃批次、已过期批次、总文件数)
|
||||||
|
- 最近批次标题和描述
|
||||||
|
- 表格列标题
|
||||||
|
- 类型和状态显示
|
||||||
|
- 查看全部按钮
|
||||||
|
|
||||||
|
- ✅ **BatchManagement.vue** (批次管理) - 部分国际化
|
||||||
|
- 页面标题和按钮
|
||||||
|
- 筛选器标签和选项
|
||||||
|
|
||||||
|
### 3. 语言文件结构(完整)
|
||||||
|
|
||||||
|
#### 中文 (zh-CN.ts) - 包含500+翻译条目
|
||||||
|
```typescript
|
||||||
|
{
|
||||||
|
common: { /* 通用文本40+条 */ },
|
||||||
|
site: { /* 站点信息 */ },
|
||||||
|
nav: { /* 导航 */ },
|
||||||
|
pickup: { /* 取件功能25+条 */ },
|
||||||
|
upload: { /* 上传功能40+条 */ },
|
||||||
|
admin: {
|
||||||
|
login: { /* 登录10+条 */ },
|
||||||
|
nav: { /* 管理导航 */ },
|
||||||
|
dashboard: { /* 概览15+条 */ },
|
||||||
|
batches: { /* 批次管理80+条 */ },
|
||||||
|
tokens: { /* 令牌管理30+条 */ },
|
||||||
|
config: { /* 系统配置20+条 */ }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 英文 (en-US.ts)
|
||||||
|
- 完整的英文翻译对应所有中文条目
|
||||||
|
|
||||||
|
## 📊 完成度统计
|
||||||
|
|
||||||
|
| 模块 | 状态 | 完成度 |
|
||||||
|
|------|------|--------|
|
||||||
|
| 基础设施 | ✅ 完成 | 100% |
|
||||||
|
| 用户端页面 | ✅ 完成 | 100% |
|
||||||
|
| 导航组件 | ✅ 完成 | 100% |
|
||||||
|
| 管理登录 | ✅ 完成 | 100% |
|
||||||
|
| 管理概览 | ✅ 完成 | 100% |
|
||||||
|
| 批次管理 | ⚠️ 部分 | 60% |
|
||||||
|
| 令牌管理 | ⏳ 待完成 | 0% |
|
||||||
|
| 系统配置 | ⏳ 待完成 | 0% |
|
||||||
|
| **总体进度** | **进行中** | **85%** |
|
||||||
|
|
||||||
|
### 在 Vue 组件中使用
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from '@/composables/useI18n'
|
||||||
|
|
||||||
|
const { t, locale, setLocale } = useI18n()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<!-- 简单文本 -->
|
||||||
|
<h1>{{ t('pickup.title') }}</h1>
|
||||||
|
|
||||||
|
<!-- 带参数的文本 -->
|
||||||
|
<p>{{ t('pickup.inputPlaceholder', { length: 6 }) }}</p>
|
||||||
|
|
||||||
|
<!-- 带后备文本 -->
|
||||||
|
<span>{{ t('site.title', '文件中转站') }}</span>
|
||||||
|
</template>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 切换语言
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 切换到英文
|
||||||
|
setLocale('en-US')
|
||||||
|
|
||||||
|
// 切换到中文
|
||||||
|
setLocale('zh-CN')
|
||||||
|
|
||||||
|
// 当前语言
|
||||||
|
console.log(locale.value) // 'zh-CN' 或 'en-US'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 在 TypeScript 中使用
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { useI18n } from '@/composables/useI18n'
|
||||||
|
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
// 在函数中使用
|
||||||
|
function showMessage() {
|
||||||
|
toast.success(t('common.saveSuccess'))
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 待完成的工作
|
||||||
|
|
||||||
|
### 需要国际化的页面
|
||||||
|
1. **UploadPage.vue** (寄存页面)
|
||||||
|
- 文件上传界面
|
||||||
|
- 文本输入界面
|
||||||
|
- 设置表单
|
||||||
|
- 上传成功提示
|
||||||
|
|
||||||
|
2. **AdminLogin.vue** (管理员登录)
|
||||||
|
- 登录表单
|
||||||
|
- 错误提示
|
||||||
|
|
||||||
|
3. **AdminDashboard.vue** (管理概览)
|
||||||
|
- 统计卡片
|
||||||
|
- 最近批次列表
|
||||||
|
|
||||||
|
4. **BatchManagement.vue** (批次管理)
|
||||||
|
- 筛选器
|
||||||
|
- 批次列表
|
||||||
|
- 批次详情
|
||||||
|
- 编辑/删除对话框
|
||||||
|
|
||||||
|
5. **TokenManagement.vue** (令牌管理)
|
||||||
|
6. **ConfigManagement.vue** (系统配置)
|
||||||
|
|
||||||
|
### 其他组件
|
||||||
|
- AdminNavBar.vue
|
||||||
|
- ThemeSwitcher.vue (如果需要语言选择器)
|
||||||
|
|
||||||
|
## 语言文件扩展
|
||||||
|
|
||||||
|
当需要添加新的翻译时:
|
||||||
|
|
||||||
|
1. 在 `src/i18n/locales/zh-CN.ts` 添加中文
|
||||||
|
2. 在 `src/i18n/locales/en-US.ts` 添加英文
|
||||||
|
3. 使用 `t('key')` 在组件中调用
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
1. **命名规范**
|
||||||
|
- 使用点号分隔的层级结构
|
||||||
|
- 例如: `admin.batches.list.title`
|
||||||
|
|
||||||
|
2. **参数化文本**
|
||||||
|
- 对于需要动态内容的文本,使用参数
|
||||||
|
- 例如: `t('pickup.inputPlaceholder', { length: 6 })`
|
||||||
|
|
||||||
|
3. **后备文本**
|
||||||
|
- 对于配置项或可能缺失的翻译,提供后备文本
|
||||||
|
- 例如: `t('site.title', '默认标题')`
|
||||||
|
|
||||||
|
4. **保持一致性**
|
||||||
|
- 相同含义的文本使用相同的 key
|
||||||
|
- 例如: 所有"保存"按钮都使用 `common.save`
|
||||||
|
|
||||||
|
## 语言持久化
|
||||||
|
|
||||||
|
- 用户选择的语言会保存在 localStorage
|
||||||
|
- Key: `locale`
|
||||||
|
- 下次访问时自动恢复
|
||||||
|
|
||||||
|
## 添加新语言
|
||||||
|
|
||||||
|
要添加新语言(如日语):
|
||||||
|
|
||||||
|
1. 创建 `src/i18n/locales/ja-JP.ts`
|
||||||
|
2. 在 `src/i18n/index.ts` 中导入并注册
|
||||||
|
3. 添加语言切换选项到 UI
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// src/i18n/index.ts
|
||||||
|
import jaJP from './locales/ja-JP'
|
||||||
|
|
||||||
|
const i18n = createI18n({
|
||||||
|
messages: {
|
||||||
|
'zh-CN': zhCN,
|
||||||
|
'en-US': enUS,
|
||||||
|
'ja-JP': jaJP, // 新增
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. i18n 已在全局注册,所有组件都可以直接使用
|
||||||
|
2. 使用 Composition API 模式 (`legacy: false`)
|
||||||
|
3. 默认语言为中文 (zh-CN)
|
||||||
|
4. 回退语言也是中文
|
||||||
139
webapp/doc/config_specification.md
Normal file
139
webapp/doc/config_specification.md
Normal file
@@ -0,0 +1,139 @@
|
|||||||
|
# FileRelay 配置项详细说明文档
|
||||||
|
|
||||||
|
本文档整理了 FileRelay 系统 `config.yaml` 配置文件中各字段的含义、类型及示例,供前端配置页面开发参考。
|
||||||
|
|
||||||
|
## 1. 站点设置 (site)
|
||||||
|
用于定义前端展示的站点基本信息。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `name` | string | 站点名称,显示在网页标题和页头 | `文件暂存柜` |
|
||||||
|
| `description` | string | 站点描述,显示在首页或元标签中 | `临时文件中转服务` |
|
||||||
|
| `logo` | string | 站点 Logo 的 URL 地址 | `/logo.png` |
|
||||||
|
| `base_url` | string | 站点外部访问地址。若配置则固定使用该地址拼接直链;若留空,系统将尝试从请求头(如 `X-Forwarded-Proto`, `:scheme`, `Forwarded` 等)或 `Referer` 中自动检测协议及主机名,以确保在 HTTPS 代理环境下链接正确。 | `https://file.example.com` |
|
||||||
|
| `port` | int | 后端服务监听端口 | `8080` |
|
||||||
|
|
||||||
|
## 2. 安全设置 (security)
|
||||||
|
涉及系统鉴权、取件保护相关的核心安全配置。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `admin_password_hash` | string | 管理员密码的 bcrypt 哈希值。可以通过更新配置接口修改,修改后立即生效,且不再依赖数据库存储。 | `$2a$10$...` |
|
||||||
|
| `pickup_code_length` | int | 自动生成的取件码长度。变更后系统将自动对存量取件码进行右侧补零或截取以适配新长度。 | `6` |
|
||||||
|
| `pickup_fail_limit` | int | 单个 IP 对单个取件码尝试失败的最大次数,超过后将被临时封禁 | `5` |
|
||||||
|
| `jwt_secret` | string | 用于签发管理端 JWT Token 的密钥,建议设置为复杂随机字符串 | `file-relay-secret` |
|
||||||
|
|
||||||
|
## 3. 上传设置 (upload)
|
||||||
|
控制文件上传的限制和策略。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `max_file_size_mb` | int64 | 单个文件的最大允许大小(单位:MB) | `100` |
|
||||||
|
| `max_batch_files` | int | 一个取件批次中允许包含的最大文件数量 | `20` |
|
||||||
|
| `max_retention_days` | int | 文件在服务器上的最长保留天数(针对 time 类型的过期策略) | `30` |
|
||||||
|
| `require_token` | bool | 是否强制要求提供 API Token 才能进行上传操作 | `false` |
|
||||||
|
|
||||||
|
## 4. 存储设置 (storage)
|
||||||
|
定义文件的实际物理存储方式。系统支持多种存储后端。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `type` | string | 当前激活的存储类型。可选值:`local`, `webdav`, `s3` | `local` |
|
||||||
|
|
||||||
|
### 4.1 本地存储 (local)
|
||||||
|
当 `type` 为 `local` 时生效。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `path` | string | 文件存储在服务器本地的相对或绝对路径 | `storage_data` |
|
||||||
|
|
||||||
|
### 4.2 WebDAV 存储 (webdav)
|
||||||
|
当 `type` 为 `webdav` 时生效。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `url` | string | WebDAV 服务器的 API 地址 | `https://dav.example.com` |
|
||||||
|
| `username` | string | WebDAV 登录用户名 | `user` |
|
||||||
|
| `password` | string | WebDAV 登录密码 | `pass` |
|
||||||
|
| `root` | string | WebDAV 上的基础存储根目录 | `/file-relay` |
|
||||||
|
|
||||||
|
### 4.3 S3 存储 (s3)
|
||||||
|
当 `type` 为 `s3` 时生效。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `endpoint` | string | S3 服务端点 | `s3.amazonaws.com` |
|
||||||
|
| `region` | string | S3 区域 | `us-east-1` |
|
||||||
|
| `access_key` | string | S3 Access Key | `your-access-key` |
|
||||||
|
| `secret_key` | string | S3 Secret Key | `your-secret-key` |
|
||||||
|
| `bucket` | string | S3 存储桶名称 | `file-relay-bucket` |
|
||||||
|
| `use_ssl` | bool | 是否强制使用 SSL (HTTPS) 连接 | `false` |
|
||||||
|
|
||||||
|
## 5. API Token 设置 (api_token)
|
||||||
|
控制系统对外开放的 API Token 管理功能。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `enabled` | bool | 是否启用 API Token 功能模块 | `true` |
|
||||||
|
| `allow_admin_api` | bool | 是否允许具备 `admin` 权限的 API Token 访问管理接口 | `true` |
|
||||||
|
| `max_tokens` | int | 系统允许创建的 API Token 最大总数限制 | `20` |
|
||||||
|
|
||||||
|
### 5.1 API Token 权限说明 (Scopes)
|
||||||
|
在创建 API Token 时,可以通过 `scope` 字段赋予以下一种或多种权限(多个权限用逗号分隔,如 `upload,pickup`):
|
||||||
|
|
||||||
|
| 权限值 | 含义 | 说明 |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `upload` | 上传权限 | 允许调用文件和长文本上传接口 |
|
||||||
|
| `pickup` | 取件权限 | 允许获取批次详情、下载文件及查询下载次数 |
|
||||||
|
| `admin` | 管理权限 | 允许访问管理端(Admin)所有接口。需开启 `allow_admin_api` 且 Token 功能已启用 |
|
||||||
|
|
||||||
|
## 6. Web 前端设置 (web)
|
||||||
|
定义前端静态资源的加载方式。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `path` | string | 外部前端资源目录路径。若该路径存在且包含 `index.html`,系统将优先使用此目录;否则回退使用内置前端资源。 | `web` |
|
||||||
|
|
||||||
|
## 7. 数据库设置 (database)
|
||||||
|
系统元数据存储配置。支持 SQLite, MySQL 和 PostgreSQL。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `type` | string | 数据库类型。可选值:`sqlite`, `mysql`, `postgres` | `sqlite` |
|
||||||
|
| `path` | string | SQLite 数据库文件的路径 (仅在 `type` 为 `sqlite` 时生效) | `file_relay.db` |
|
||||||
|
| `host` | string | 数据库地址 (MySQL/PostgreSQL) | `127.0.0.1` |
|
||||||
|
| `port` | int | 数据库端口 (MySQL/PostgreSQL) | `3306` 或 `5432` |
|
||||||
|
| `user` | string | 数据库用户名 (MySQL/PostgreSQL) | `root` |
|
||||||
|
| `password` | string | 数据库密码 (MySQL/PostgreSQL) | `password` |
|
||||||
|
| `dbname` | string | 数据库名称 (MySQL/PostgreSQL) | `file_relay` |
|
||||||
|
| `config` | string | 额外 DSN 配置参数。MySQL 如 `charset=utf8mb4&parseTime=True&loc=Local`;PostgreSQL 如 `sslmode=disable` | `charset=utf8mb4&parseTime=True&loc=Local` |
|
||||||
|
|
||||||
|
## 8. 日志设置 (log)
|
||||||
|
控制系统日志的输出级别和目的地。
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 含义 | 示例 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| `level` | string | 日志级别。可选值:`debug`, `info`, `warn`, `error` | `info` |
|
||||||
|
| `file_path` | string | 日志文件路径。如果设置,日志将同时输出到控制台和该文件;若为空则仅输出到控制台。 | `logs/app.log` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录:公共配置接口 (/api/config)
|
||||||
|
|
||||||
|
为了方便前端展示和交互约束,系统提供了 `/api/config` 接口,该接口不需要鉴权,返回以下非敏感字段(结构与完整配置保持一致):
|
||||||
|
|
||||||
|
- **site**: 完整内容(`name`, `description`, `logo`, `base_url`)
|
||||||
|
- **security**: 仅包含 `pickup_code_length`
|
||||||
|
- **upload**: 完整内容(`max_file_size_mb`, `max_batch_files`, `max_retention_days`, `require_token`)
|
||||||
|
- **api_token**: 仅包含 `enabled` 开关
|
||||||
|
- **storage**: 仅包含 `type`(存储类型)
|
||||||
|
|
||||||
|
## 附录:其他关键接口
|
||||||
|
|
||||||
|
### 查询下载次数 (GET /api/batches/:pickup_code/count)
|
||||||
|
- **用途**:供前端实时刷新当前取件批次的下载次数。
|
||||||
|
- **特性**:支持查询已过期的文件。
|
||||||
|
|
||||||
|
### 恢复 API Token (POST /api/admin/api-tokens/:id/recover)
|
||||||
|
- **权限**:需要管理员权限。
|
||||||
|
- **用途**:将状态为“已撤销”的 Token 重新恢复为有效状态。
|
||||||
309
webapp/doc/i18n_guide.md
Normal file
309
webapp/doc/i18n_guide.md
Normal file
@@ -0,0 +1,309 @@
|
|||||||
|
# 国际化 (i18n) 使用指南
|
||||||
|
|
||||||
|
本文档说明如何在项目中新增语言支持和使用国际化功能。
|
||||||
|
|
||||||
|
## 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
├── i18n/
|
||||||
|
│ ├── index.ts # i18n 配置入口
|
||||||
|
│ ├── languages.ts # 语言配置文件(集中管理所有支持的语言)
|
||||||
|
│ └── locales/ # 翻译文件目录
|
||||||
|
│ ├── zh-CN.ts # 简体中文翻译
|
||||||
|
│ └── en-US.ts # 英文翻译
|
||||||
|
├── composables/
|
||||||
|
│ └── useI18n.ts # i18n Composable 封装
|
||||||
|
└── components/
|
||||||
|
└── ui/
|
||||||
|
└── LanguageSwitcher.vue # 语言切换组件
|
||||||
|
```
|
||||||
|
|
||||||
|
## 新增语言支持
|
||||||
|
|
||||||
|
### 步骤 1: 添加语言配置
|
||||||
|
|
||||||
|
编辑 `src/i18n/languages.ts`,在 `languages` 数组中添加新语言:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export const languages: Language[] = [
|
||||||
|
{
|
||||||
|
code: 'zh-CN',
|
||||||
|
name: '简体中文',
|
||||||
|
flag: '🇨🇳',
|
||||||
|
englishName: 'Simplified Chinese',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
code: 'en-US',
|
||||||
|
name: 'English',
|
||||||
|
flag: '🇺🇸',
|
||||||
|
englishName: 'English',
|
||||||
|
},
|
||||||
|
// 新增日语
|
||||||
|
{
|
||||||
|
code: 'ja-JP',
|
||||||
|
name: '日本語',
|
||||||
|
flag: '🇯🇵',
|
||||||
|
englishName: 'Japanese',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
**字段说明:**
|
||||||
|
- `code`: 语言代码(BCP 47 标准),如 `ja-JP`、`zh-TW`、`fr-FR` 等
|
||||||
|
- `name`: 用该语言自身的文字显示的名称(如日语用 "日本語")
|
||||||
|
- `flag`: 对应的旗帜 Emoji(可选,用于视觉识别)
|
||||||
|
- `englishName`: 英文名称(可选,用于文档和调试)
|
||||||
|
|
||||||
|
### 步骤 2: 创建翻译文件
|
||||||
|
|
||||||
|
在 `src/i18n/locales/` 目录下创建新的翻译文件,如 `ja-JP.ts`:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export default {
|
||||||
|
// 通用文本
|
||||||
|
common: {
|
||||||
|
submit: '送信',
|
||||||
|
cancel: 'キャンセル',
|
||||||
|
confirm: '確認',
|
||||||
|
// ... 其他翻译
|
||||||
|
},
|
||||||
|
|
||||||
|
// 站点信息
|
||||||
|
site: {
|
||||||
|
title: 'ファイル中継ステーション',
|
||||||
|
description: '安全で便利なファイル一時保管サービス',
|
||||||
|
// ... 其他翻译
|
||||||
|
},
|
||||||
|
|
||||||
|
// 导航栏
|
||||||
|
nav: {
|
||||||
|
pickup: '受取',
|
||||||
|
upload: 'アップロード',
|
||||||
|
// ... 其他翻译
|
||||||
|
},
|
||||||
|
|
||||||
|
// 更多模块...
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**💡 提示:** 可以参考 `zh-CN.ts` 或 `en-US.ts` 的结构,确保所有 key 保持一致。
|
||||||
|
|
||||||
|
### 步骤 3: 注册翻译文件
|
||||||
|
|
||||||
|
编辑 `src/i18n/index.ts`,导入并注册新的翻译文件:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import zhCN from './locales/zh-CN'
|
||||||
|
import enUS from './locales/en-US'
|
||||||
|
import jaJP from './locales/ja-JP' // 导入新语言
|
||||||
|
|
||||||
|
const messages = {
|
||||||
|
'zh-CN': zhCN,
|
||||||
|
'en-US': enUS,
|
||||||
|
'ja-JP': jaJP, // 注册新语言
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 步骤 4: 测试
|
||||||
|
|
||||||
|
完成以上步骤后,语言切换器会自动显示新语言选项。切换语言后,检查所有页面的翻译是否正确显示。
|
||||||
|
|
||||||
|
## 使用国际化
|
||||||
|
|
||||||
|
### 在 Vue 组件中使用
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { useI18n } from '@/composables/useI18n'
|
||||||
|
|
||||||
|
const { t, locale, setLocale } = useI18n()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div>
|
||||||
|
<!-- 使用翻译 -->
|
||||||
|
<h1>{{ t('site.title') }}</h1>
|
||||||
|
<p>{{ t('site.description') }}</p>
|
||||||
|
|
||||||
|
<!-- 带默认值的翻译 -->
|
||||||
|
<button>{{ t('common.submit', '提交') }}</button>
|
||||||
|
|
||||||
|
<!-- 显示当前语言 -->
|
||||||
|
<p>Current locale: {{ locale }}</p>
|
||||||
|
|
||||||
|
<!-- 切换语言 -->
|
||||||
|
<button @click="setLocale('en-US')">Switch to English</button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
```
|
||||||
|
|
||||||
|
### API 说明
|
||||||
|
|
||||||
|
- `t(key: string, defaultValue?: string)`: 获取翻译文本
|
||||||
|
- `key`: 翻译的键名(如 `'common.submit'`)
|
||||||
|
- `defaultValue`: 可选的默认值(当翻译不存在时使用)
|
||||||
|
|
||||||
|
- `locale`: 当前激活的语言代码(响应式)
|
||||||
|
|
||||||
|
- `setLocale(lang: string)`: 切换语言
|
||||||
|
- 自动保存到 localStorage
|
||||||
|
- 全局生效
|
||||||
|
|
||||||
|
### 翻译 key 命名规范
|
||||||
|
|
||||||
|
建议使用 **模块化** 的命名结构:
|
||||||
|
|
||||||
|
```
|
||||||
|
模块.子模块.具体项
|
||||||
|
```
|
||||||
|
|
||||||
|
示例:
|
||||||
|
- `common.submit` - 通用模块的"提交"按钮
|
||||||
|
- `nav.pickup` - 导航栏的"取件"链接
|
||||||
|
- `admin.dashboard.title` - 管理后台仪表板标题
|
||||||
|
- `upload.dragHint` - 上传页面的拖拽提示
|
||||||
|
|
||||||
|
## 语言切换器
|
||||||
|
|
||||||
|
项目包含一个独立的语言切换组件 `LanguageSwitcher.vue`,可以在任何页面中使用:
|
||||||
|
|
||||||
|
```vue
|
||||||
|
<template>
|
||||||
|
<LanguageSwitcher />
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import LanguageSwitcher from '@/components/ui/LanguageSwitcher.vue'
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
**已集成位置:**
|
||||||
|
- 用户前台导航栏 (`NavBar.vue`) - 右上角
|
||||||
|
- 管理后台导航栏 (`AdminNavBar.vue`) - 右上角
|
||||||
|
|
||||||
|
语言切换器会自动:
|
||||||
|
- 读取 `languages.ts` 中配置的所有语言
|
||||||
|
- 显示当前激活的语言
|
||||||
|
- 提供下拉菜单供用户切换
|
||||||
|
- 保存用户的语言偏好到 localStorage
|
||||||
|
|
||||||
|
## 常见的翻译 key
|
||||||
|
|
||||||
|
以下是项目中常用的翻译 key,新增语言时需要提供对应翻译:
|
||||||
|
|
||||||
|
### 通用 (common)
|
||||||
|
- `submit`, `cancel`, `confirm`, `delete`, `edit`, `save`, `reset`
|
||||||
|
- `loading`, `success`, `error`, `warning`
|
||||||
|
- `yes`, `no`
|
||||||
|
|
||||||
|
### 站点 (site)
|
||||||
|
- `title`, `description`, `logo`
|
||||||
|
|
||||||
|
### 导航 (nav)
|
||||||
|
- `pickup`, `upload`, `home`
|
||||||
|
|
||||||
|
### 管理后台 (admin)
|
||||||
|
- `admin.nav.*` - 导航栏各项
|
||||||
|
- `admin.dashboard.*` - 仪表板
|
||||||
|
- `admin.batches.*` - 批次管理
|
||||||
|
- `admin.tokens.*` - Token 管理
|
||||||
|
- `admin.config.*` - 系统配置
|
||||||
|
|
||||||
|
### 上传 (upload)
|
||||||
|
- `upload.title`, `upload.selectFile`, `upload.dragHint`
|
||||||
|
|
||||||
|
### 取件 (pickup)
|
||||||
|
- `pickup.title`, `pickup.enterCode`, `pickup.download`
|
||||||
|
|
||||||
|
## 最佳实践
|
||||||
|
|
||||||
|
1. **保持 key 一致性**
|
||||||
|
所有语言的翻译文件必须包含相同的 key 结构,否则会导致部分语言缺失翻译。
|
||||||
|
|
||||||
|
2. **使用有意义的 key 名称**
|
||||||
|
避免使用 `text1`、`label2` 这样的名称,应该使用描述性的名称如 `uploadButton`、`successMessage`。
|
||||||
|
|
||||||
|
3. **提供默认值**
|
||||||
|
在调用 `t()` 时提供默认值,可以在翻译缺失时有更好的用户体验:
|
||||||
|
```vue
|
||||||
|
{{ t('some.key', '默认文本') }}
|
||||||
|
```
|
||||||
|
|
||||||
|
4. **模块化组织**
|
||||||
|
按照功能模块组织翻译文件,便于维护:
|
||||||
|
```typescript
|
||||||
|
export default {
|
||||||
|
common: { /* 通用翻译 */ },
|
||||||
|
nav: { /* 导航翻译 */ },
|
||||||
|
admin: {
|
||||||
|
dashboard: { /* 仪表板翻译 */ },
|
||||||
|
config: { /* 配置翻译 */ },
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
5. **注释复杂翻译**
|
||||||
|
对于有特殊含义或上下文的翻译,添加注释说明:
|
||||||
|
```typescript
|
||||||
|
export default {
|
||||||
|
upload: {
|
||||||
|
// 提示用户拖拽文件到上传区域
|
||||||
|
dragHint: '拖拽文件到此处,或点击选择文件',
|
||||||
|
},
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
6. **测试所有语言**
|
||||||
|
新增或修改翻译后,切换到每种语言测试,确保显示正确。
|
||||||
|
|
||||||
|
## 技术实现
|
||||||
|
|
||||||
|
项目使用 [vue-i18n v9](https://vue-i18n.intlify.dev/) 作为国际化框架,采用 **Composition API** 模式。
|
||||||
|
|
||||||
|
### 特性
|
||||||
|
- ✅ 响应式语言切换
|
||||||
|
- ✅ localStorage 持久化
|
||||||
|
- ✅ TypeScript 类型支持
|
||||||
|
- ✅ 模块化翻译文件
|
||||||
|
- ✅ 集中式语言配置
|
||||||
|
- ✅ 易于扩展新语言
|
||||||
|
|
||||||
|
### 配置文件说明
|
||||||
|
|
||||||
|
- **`src/i18n/index.ts`**
|
||||||
|
vue-i18n 配置入口,设置默认语言、回退语言、翻译消息等。
|
||||||
|
|
||||||
|
- **`src/i18n/languages.ts`**
|
||||||
|
语言配置文件,集中管理所有支持的语言信息(代码、名称、旗帜等)。新增语言首先在此配置。
|
||||||
|
|
||||||
|
- **`src/composables/useI18n.ts`**
|
||||||
|
封装了 vue-i18n 的 Composable,提供简化的 API(`t`、`locale`、`setLocale`)。
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
**Q: 新增语言后,语言切换器没有显示新语言?**
|
||||||
|
A: 检查 `src/i18n/languages.ts` 是否正确添加了语言配置,确保 `code`、`name` 和 `flag` 字段都已填写。
|
||||||
|
|
||||||
|
**Q: 切换语言后,部分内容没有翻译?**
|
||||||
|
A: 检查新语言的翻译文件是否包含所有必需的 key。可以对比 `zh-CN.ts` 确保结构一致。
|
||||||
|
|
||||||
|
**Q: 如何修改默认语言?**
|
||||||
|
A: 编辑 `src/i18n/languages.ts`,修改 `DEFAULT_LANGUAGE` 常量的值。
|
||||||
|
|
||||||
|
**Q: 语言偏好保存在哪里?**
|
||||||
|
A: 保存在浏览器的 localStorage 中,key 为 `'locale'`。
|
||||||
|
|
||||||
|
**Q: 如何在 JavaScript 代码中使用翻译?**
|
||||||
|
A: 在 `<script setup>` 中通过 `useI18n()` 获取 `t` 函数,然后调用 `t('key')`。
|
||||||
|
|
||||||
|
## 参考资源
|
||||||
|
|
||||||
|
- [Vue I18n 官方文档](https://vue-i18n.intlify.dev/)
|
||||||
|
- [BCP 47 语言标签](https://www.rfc-editor.org/rfc/bcp/bcp47.txt)
|
||||||
|
- [Unicode CLDR 语言数据](https://cldr.unicode.org/)
|
||||||
|
- [Emoji 国旗列表](https://emojipedia.org/flags/)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**维护者注意:** 新增或修改语言配置后,请更新本文档。
|
||||||
13
webapp/index.html
Normal file
13
webapp/index.html
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<link rel="icon" type="image/png" href="/favicon.png" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>文件中转站</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.ts"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
2866
webapp/package-lock.json
generated
Normal file
2866
webapp/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
43
webapp/package.json
Normal file
43
webapp/package.json
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
{
|
||||||
|
"name": "file-relay-ui",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"description": "文件中转站前端应用",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite --host",
|
||||||
|
"build": "vue-tsc -b && vite build",
|
||||||
|
"build:prod": "vue-tsc -b && vite build --mode production",
|
||||||
|
"build:dev": "vue-tsc -b && vite build --mode development",
|
||||||
|
"preview": "vite preview --host",
|
||||||
|
"serve": "vite preview",
|
||||||
|
"lint": "eslint . --ext .vue,.js,.jsx,.cjs,.mjs,.ts,.tsx,.cts,.mts --fix --ignore-path .gitignore"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@tailwindcss/vite": "^4.1.18",
|
||||||
|
"@tanstack/vue-table": "^8.21.3",
|
||||||
|
"@vueuse/core": "^14.1.0",
|
||||||
|
"axios": "^1.13.2",
|
||||||
|
"class-variance-authority": "^0.7.1",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"lucide-vue-next": "^0.562.0",
|
||||||
|
"reka-ui": "^2.7.0",
|
||||||
|
"tailwind-merge": "^3.4.0",
|
||||||
|
"tailwindcss": "^4.1.18",
|
||||||
|
"vue": "^3.5.24",
|
||||||
|
"vue-i18n": "^9.14.5",
|
||||||
|
"vue-input-otp": "^0.3.2",
|
||||||
|
"vue-router": "^4.6.4",
|
||||||
|
"vue-sonner": "^2.0.9"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/node": "^24.10.8",
|
||||||
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
|
"@vue/tsconfig": "^0.8.1",
|
||||||
|
"terser": "^5.46.0",
|
||||||
|
"tw-animate-css": "^1.4.0",
|
||||||
|
"typescript": "~5.9.3",
|
||||||
|
"vite": "^7.2.4",
|
||||||
|
"vue-tsc": "^3.1.4"
|
||||||
|
}
|
||||||
|
}
|
||||||
BIN
webapp/public/favicon.png
Normal file
BIN
webapp/public/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 7.8 KiB |
73
webapp/src/App.vue
Normal file
73
webapp/src/App.vue
Normal file
@@ -0,0 +1,73 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import 'vue-sonner/style.css'
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div id="app">
|
||||||
|
<router-view />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
#app {
|
||||||
|
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
#app {
|
||||||
|
min-height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 全局滚动条样式 - 默认隐藏,滚动时显示 */
|
||||||
|
* {
|
||||||
|
scrollbar-width: thin;
|
||||||
|
scrollbar-color: transparent transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
*:hover {
|
||||||
|
scrollbar-color: rgba(156, 163, 175, 0.3) transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark *:hover {
|
||||||
|
scrollbar-color: rgba(156, 163, 175, 0.5) transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Webkit 滚动条样式 */
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 6px;
|
||||||
|
height: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: transparent;
|
||||||
|
border-radius: 3px;
|
||||||
|
transition: background 0.2s;
|
||||||
|
}
|
||||||
|
|
||||||
|
*:hover::-webkit-scrollbar-thumb {
|
||||||
|
background: rgba(156, 163, 175, 0.3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark *:hover::-webkit-scrollbar-thumb {
|
||||||
|
background: rgba(156, 163, 175, 0.5);
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: rgba(156, 163, 175, 0.5) !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dark ::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: rgba(156, 163, 175, 0.7) !important;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
1
webapp/src/assets/vue.svg
Normal file
1
webapp/src/assets/vue.svg
Normal file
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>
|
||||||
|
After Width: | Height: | Size: 496 B |
216
webapp/src/components/ui/AdminNavBar.vue
Normal file
216
webapp/src/components/ui/AdminNavBar.vue
Normal file
@@ -0,0 +1,216 @@
|
|||||||
|
<template>
|
||||||
|
<nav class="bg-white/75 dark:bg-gray-900/75 backdrop-blur-lg border-b border-gray-200 dark:border-gray-700 shadow-sm transition-colors">
|
||||||
|
<div class="max-w-7xl mx-auto px-2 sm:px-4 lg:px-8">
|
||||||
|
<div class="flex justify-between h-14 sm:h-16">
|
||||||
|
<!-- 左侧 Logo 和菜单 -->
|
||||||
|
<div class="flex items-center min-w-0 flex-1">
|
||||||
|
<div class="flex-shrink-0 flex items-center space-x-1.5 sm:space-x-2">
|
||||||
|
<!-- Logo -->
|
||||||
|
<div v-if="config.site?.logo" class="w-7 h-7 sm:w-8 sm:h-8 rounded-lg overflow-hidden flex items-center justify-center flex-shrink-0">
|
||||||
|
<img :src="config.site.logo" :alt="config.site?.name || t('site.title')" class="w-full h-full object-contain" />
|
||||||
|
</div>
|
||||||
|
<div v-else class="w-7 h-7 sm:w-8 sm:h-8 bg-indigo-600 rounded-lg flex items-center justify-center flex-shrink-0">
|
||||||
|
<svg class="w-4 h-4 sm:w-5 sm:h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<!-- 站点名称和徽章 -->
|
||||||
|
<div class="flex items-center space-x-1.5 min-w-0">
|
||||||
|
<h1 class="hidden sm:block text-lg lg:text-xl font-bold text-gray-900 dark:text-gray-100 truncate">
|
||||||
|
{{ config.site?.name || t('site.title') }}
|
||||||
|
</h1>
|
||||||
|
<Badge variant="secondary" class="text-[10px] sm:text-xs px-1.5 py-0.5 flex-shrink-0">ADMIN</Badge>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 桌面端导航菜单 -->
|
||||||
|
<div class="hidden lg:ml-6 lg:flex lg:space-x-4 xl:space-x-6 min-w-0">
|
||||||
|
<router-link
|
||||||
|
to="/admin"
|
||||||
|
class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium whitespace-nowrap"
|
||||||
|
:class="$route.path === '/admin' ? 'border-indigo-500 text-gray-900 dark:text-gray-100' : 'border-transparent text-gray-500 dark:text-gray-400 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-300'"
|
||||||
|
>
|
||||||
|
{{ t('admin.nav.overview') }}
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
to="/admin/batches"
|
||||||
|
class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium whitespace-nowrap"
|
||||||
|
:class="$route.path.includes('/admin/batches') ? 'border-indigo-500 text-gray-900 dark:text-gray-100' : 'border-transparent text-gray-500 dark:text-gray-400 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-300'"
|
||||||
|
>
|
||||||
|
{{ t('admin.nav.fileManagement') }}
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
to="/admin/tokens"
|
||||||
|
class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium whitespace-nowrap"
|
||||||
|
:class="$route.path.includes('/admin/tokens') ? 'border-indigo-500 text-gray-900 dark:text-gray-100' : 'border-transparent text-gray-500 dark:text-gray-400 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-300'"
|
||||||
|
>
|
||||||
|
{{ t('admin.nav.apiManagement') }}
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
to="/admin/config"
|
||||||
|
class="inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium whitespace-nowrap"
|
||||||
|
:class="$route.path.includes('/admin/config') ? 'border-indigo-500 text-gray-900 dark:text-gray-100' : 'border-transparent text-gray-500 dark:text-gray-400 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-700 dark:hover:text-gray-300'"
|
||||||
|
>
|
||||||
|
{{ t('admin.nav.systemConfig') }}
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 右侧操作按钮 -->
|
||||||
|
<div class="flex items-center space-x-0.5 sm:space-x-1 flex-shrink-0">
|
||||||
|
<!-- 主题切换 -->
|
||||||
|
<ThemeSwitcher class="flex-shrink-0" />
|
||||||
|
|
||||||
|
<!-- 语言切换 -->
|
||||||
|
<LanguageSwitcher class="flex-shrink-0" />
|
||||||
|
|
||||||
|
<!-- 移动端菜单按钮 -->
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
@click="showMobileMenu = !showMobileMenu"
|
||||||
|
class="lg:hidden flex-shrink-0"
|
||||||
|
size="sm"
|
||||||
|
:aria-label="t('admin.nav.toggleMenu')"
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
class="w-5 h-5 transition-transform duration-200"
|
||||||
|
:class="{ 'rotate-90': showMobileMenu }"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
v-if="!showMobileMenu"
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M4 6h16M4 12h16M4 18h16"
|
||||||
|
></path>
|
||||||
|
<path
|
||||||
|
v-else
|
||||||
|
stroke-linecap="round"
|
||||||
|
stroke-linejoin="round"
|
||||||
|
stroke-width="2"
|
||||||
|
d="M6 18L18 6M6 6l12 12"
|
||||||
|
></path>
|
||||||
|
</svg>
|
||||||
|
</Button>
|
||||||
|
|
||||||
|
<!-- 桌面端操作按钮 -->
|
||||||
|
<div class="hidden lg:flex lg:items-center lg:space-x-1">
|
||||||
|
<Button variant="outline" @click="router.push('/')" size="sm" class="flex-shrink-0">
|
||||||
|
<svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-1a1 1 0 011-1h2a1 1 0 011 1v1a1 1 0 001 1m-6 0h6"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="text-sm">{{ t('admin.nav.goToFront') }}</span>
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" @click="handleLogout" size="sm" class="flex-shrink-0">
|
||||||
|
<svg class="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="text-sm">{{ t('admin.nav.logout') }}</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 移动端菜单 -->
|
||||||
|
<transition
|
||||||
|
enter-active-class="transition ease-out duration-200"
|
||||||
|
enter-from-class="opacity-0 -translate-y-1"
|
||||||
|
enter-to-class="opacity-100 translate-y-0"
|
||||||
|
leave-active-class="transition ease-in duration-150"
|
||||||
|
leave-from-class="opacity-100 translate-y-0"
|
||||||
|
leave-to-class="opacity-0 -translate-y-1"
|
||||||
|
>
|
||||||
|
<div class="lg:hidden" v-if="showMobileMenu">
|
||||||
|
<div class="pt-2 pb-3 space-y-1 bg-gray-50/50 dark:bg-gray-800/50 backdrop-blur-sm">
|
||||||
|
<router-link
|
||||||
|
to="/admin"
|
||||||
|
class="flex items-center pl-3 pr-4 py-2.5 text-sm sm:text-base font-medium border-l-4 transition-all"
|
||||||
|
:class="$route.path === '/admin' ? 'bg-indigo-50 dark:bg-indigo-900/30 border-indigo-500 text-indigo-700 dark:text-indigo-400' : 'border-transparent text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-800 dark:hover:text-gray-200'"
|
||||||
|
@click="showMobileMenu = false"
|
||||||
|
>
|
||||||
|
<svg class="w-5 h-5 mr-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="truncate">{{ t('admin.nav.overview') }}</span>
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
to="/admin/batches"
|
||||||
|
class="flex items-center pl-3 pr-4 py-2.5 text-sm sm:text-base font-medium border-l-4 transition-all"
|
||||||
|
:class="$route.path.includes('/admin/batches') ? 'bg-indigo-50 dark:bg-indigo-900/30 border-indigo-500 text-indigo-700 dark:text-indigo-400' : 'border-transparent text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-800 dark:hover:text-gray-200'"
|
||||||
|
@click="showMobileMenu = false"
|
||||||
|
>
|
||||||
|
<svg class="w-5 h-5 mr-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="truncate">{{ t('admin.nav.fileManagement') }}</span>
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
to="/admin/tokens"
|
||||||
|
class="flex items-center pl-3 pr-4 py-2.5 text-sm sm:text-base font-medium border-l-4 transition-all"
|
||||||
|
:class="$route.path.includes('/admin/tokens') ? 'bg-indigo-50 dark:bg-indigo-900/30 border-indigo-500 text-indigo-700 dark:text-indigo-400' : 'border-transparent text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-800 dark:hover:text-gray-200'"
|
||||||
|
@click="showMobileMenu = false"
|
||||||
|
>
|
||||||
|
<svg class="w-5 h-5 mr-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="truncate">{{ t('admin.nav.apiManagement') }}</span>
|
||||||
|
</router-link>
|
||||||
|
<router-link
|
||||||
|
to="/admin/config"
|
||||||
|
class="flex items-center pl-3 pr-4 py-2.5 text-sm sm:text-base font-medium border-l-4 transition-all"
|
||||||
|
:class="$route.path.includes('/admin/config') ? 'bg-indigo-50 dark:bg-indigo-900/30 border-indigo-500 text-indigo-700 dark:text-indigo-400' : 'border-transparent text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-800 hover:border-gray-300 dark:hover:border-gray-600 hover:text-gray-800 dark:hover:text-gray-200'"
|
||||||
|
@click="showMobileMenu = false"
|
||||||
|
>
|
||||||
|
<svg class="w-5 h-5 mr-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="truncate">{{ t('admin.nav.systemConfig') }}</span>
|
||||||
|
</router-link>
|
||||||
|
|
||||||
|
<!-- 移动端快捷操作按钮 -->
|
||||||
|
<div class="pt-2 pb-2 px-3 space-y-2">
|
||||||
|
<Button variant="outline" @click="router.push('/'); showMobileMenu = false" class="w-full justify-start" size="sm">
|
||||||
|
<svg class="w-4 h-4 mr-2 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-1a1 1 0 011-1h2a1 1 0 011 1v1a1 1 0 001 1m-6 0h6"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="truncate">{{ t('admin.nav.goToFront') }}</span>
|
||||||
|
</Button>
|
||||||
|
<Button variant="destructive" @click="handleLogout" class="w-full justify-start" size="sm">
|
||||||
|
<svg class="w-4 h-4 mr-2 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="truncate">{{ t('admin.nav.logout') }}</span>
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</transition>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { Badge } from '@/components/ui/badge'
|
||||||
|
import { usePublicConfig } from '@/composables/usePublicConfig'
|
||||||
|
import ThemeSwitcher from '@/components/ui/ThemeSwitcher.vue'
|
||||||
|
import LanguageSwitcher from '@/components/ui/LanguageSwitcher.vue'
|
||||||
|
import { useI18n } from '@/composables/useI18n'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const showMobileMenu = ref(false)
|
||||||
|
const { config } = usePublicConfig()
|
||||||
|
const { t } = useI18n()
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
localStorage.removeItem('admin_token')
|
||||||
|
router.push('/admin/login')
|
||||||
|
}
|
||||||
|
</script>
|
||||||
103
webapp/src/components/ui/LanguageSwitcher.vue
Normal file
103
webapp/src/components/ui/LanguageSwitcher.vue
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
<template>
|
||||||
|
<div class="relative z-50">
|
||||||
|
<button
|
||||||
|
@click="toggleDropdown"
|
||||||
|
class="flex items-center space-x-1 px-2 py-1.5 rounded-lg text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors flex-shrink-0"
|
||||||
|
:title="t('language.switch', '切换语言')"
|
||||||
|
>
|
||||||
|
<svg class="w-4 h-4 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 5h12M9 3v2m1.048 9.5A18.022 18.022 0 016.412 9m6.088 9h7M11 21l5-10 5 10M12.751 5C11.783 10.77 8.07 15.61 3 18.129"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="text-sm font-medium hidden sm:inline">{{ currentLanguageName }}</span>
|
||||||
|
<svg class="w-3 h-3 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- 下拉菜单 - 使用最高的 z-index 确保不被任何元素覆盖 -->
|
||||||
|
<Transition
|
||||||
|
enter-active-class="transition ease-out duration-100"
|
||||||
|
enter-from-class="transform opacity-0 scale-95"
|
||||||
|
enter-to-class="transform opacity-100 scale-100"
|
||||||
|
leave-active-class="transition ease-in duration-75"
|
||||||
|
leave-from-class="transform opacity-100 scale-100"
|
||||||
|
leave-to-class="transform opacity-0 scale-95"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
v-if="isOpen"
|
||||||
|
class="absolute right-0 mt-2 w-40 bg-white dark:bg-gray-800 rounded-lg shadow-xl border border-gray-200 dark:border-gray-700 py-1"
|
||||||
|
style="z-index: 99999;"
|
||||||
|
@click="isOpen = false"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
v-for="lang in languages"
|
||||||
|
:key="lang.code"
|
||||||
|
@click="switchLanguage(lang.code)"
|
||||||
|
class="w-full px-4 py-2 text-left text-sm hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors flex items-center justify-between"
|
||||||
|
:class="{
|
||||||
|
'text-blue-600 dark:text-blue-400 font-medium': locale === lang.code,
|
||||||
|
'text-gray-700 dark:text-gray-300': locale !== lang.code
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
<span class="flex items-center">
|
||||||
|
<span class="mr-2">{{ lang.flag }}</span>
|
||||||
|
<span>{{ lang.name }}</span>
|
||||||
|
</span>
|
||||||
|
<svg
|
||||||
|
v-if="locale === lang.code"
|
||||||
|
class="w-4 h-4"
|
||||||
|
fill="currentColor"
|
||||||
|
viewBox="0 0 20 20"
|
||||||
|
>
|
||||||
|
<path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd"></path>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</Transition>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||||
|
import { useI18n } from '@/composables/useI18n'
|
||||||
|
import { languages, getLanguageName } from '@/i18n/languages'
|
||||||
|
|
||||||
|
const { locale, setLocale, t } = useI18n()
|
||||||
|
const isOpen = ref(false)
|
||||||
|
|
||||||
|
const currentLanguageName = computed(() => {
|
||||||
|
return getLanguageName(locale.value)
|
||||||
|
})
|
||||||
|
|
||||||
|
const toggleDropdown = () => {
|
||||||
|
isOpen.value = !isOpen.value
|
||||||
|
}
|
||||||
|
|
||||||
|
const switchLanguage = (langCode: string) => {
|
||||||
|
setLocale(langCode)
|
||||||
|
isOpen.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// 点击外部关闭下拉菜单
|
||||||
|
const handleClickOutside = (event: MouseEvent) => {
|
||||||
|
const target = event.target as HTMLElement
|
||||||
|
if (isOpen.value && !target.closest('.relative')) {
|
||||||
|
isOpen.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
document.addEventListener('click', handleClickOutside)
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
document.removeEventListener('click', handleClickOutside)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
/* 确保下拉菜单在其他元素之上 */
|
||||||
|
.z-50 {
|
||||||
|
z-index: 50;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
167
webapp/src/components/ui/NavBar.vue
Normal file
167
webapp/src/components/ui/NavBar.vue
Normal file
@@ -0,0 +1,167 @@
|
|||||||
|
<template>
|
||||||
|
<nav class="bg-white/75 dark:bg-gray-900/75 backdrop-blur-lg border-b border-gray-200 dark:border-gray-700 transition-colors">
|
||||||
|
<div class="container mx-auto px-3 sm:px-4">
|
||||||
|
<div class="flex justify-between items-center h-16">
|
||||||
|
<!-- 左侧:站点信息 -->
|
||||||
|
<div class="flex items-center space-x-2 sm:space-x-4">
|
||||||
|
<a href="/" class="flex items-center space-x-2 sm:space-x-3">
|
||||||
|
<!-- Logo -->
|
||||||
|
<div v-if="config.site?.logo" class="w-8 h-8 sm:w-9 sm:h-9 rounded-lg overflow-hidden flex items-center justify-center flex-shrink-0">
|
||||||
|
<img :src="config.site.logo" :alt="config.site?.name || t('site.title', '文件中转站')" class="w-full h-full object-contain" />
|
||||||
|
</div>
|
||||||
|
<div v-else class="w-8 h-8 sm:w-9 sm:h-9 bg-blue-600 rounded-lg flex items-center justify-center flex-shrink-0">
|
||||||
|
<svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<!-- 移动端隐藏文字,只保留图标 -->
|
||||||
|
<div class="hidden sm:block">
|
||||||
|
<h1 class="text-lg font-semibold text-gray-900 dark:text-gray-100">{{ config.site?.name || t('site.title', '文件中转站') }}</h1>
|
||||||
|
<p v-if="showDescription" class="text-xs text-gray-500 dark:text-gray-400">{{ config.site?.description || t('site.description', '安全、便捷的文件暂存服务') }}</p>
|
||||||
|
</div>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 右侧:导航链接 -->
|
||||||
|
<div class="flex items-center space-x-1 sm:space-x-2">
|
||||||
|
<!-- 主题切换 - 放在最左侧 -->
|
||||||
|
<ThemeSwitcher />
|
||||||
|
|
||||||
|
<!-- 取件/发送切换按钮组 -->
|
||||||
|
<div ref="buttonGroup" class="relative inline-flex items-center rounded-full bg-gray-100 dark:bg-gray-800 p-0.5 transition-colors">
|
||||||
|
<!-- 滑动指示器 -->
|
||||||
|
<div
|
||||||
|
:class="[
|
||||||
|
'absolute inset-y-0.5 bg-white dark:bg-gray-700 rounded-full shadow-sm',
|
||||||
|
isInitialized && 'transition-all duration-300 ease-in-out'
|
||||||
|
]"
|
||||||
|
:style="{
|
||||||
|
left: indicatorPosition,
|
||||||
|
width: indicatorWidth
|
||||||
|
}"
|
||||||
|
></div>
|
||||||
|
|
||||||
|
<button @click="switchTab('pickup')" ref="pickupButton">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
class="relative z-10 h-7 px-2 sm:px-4 rounded-full hover:bg-transparent"
|
||||||
|
>
|
||||||
|
<svg class="w-4 h-4 sm:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2H5a2 2 0 00-2-2z"></path>
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5l4-4 4 4"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="hidden sm:inline">{{ t('nav.pickup') }}</span>
|
||||||
|
</Button>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<button @click="switchTab('upload')" ref="uploadButton">
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
class="relative z-10 h-7 px-2 sm:px-4 rounded-full hover:bg-transparent"
|
||||||
|
>
|
||||||
|
<svg class="w-4 h-4 sm:mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"></path>
|
||||||
|
</svg>
|
||||||
|
<span class="hidden sm:inline">{{ t('nav.upload') }}</span>
|
||||||
|
</Button>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 语言切换 - 放在最右侧 -->
|
||||||
|
<LanguageSwitcher />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
|
||||||
|
import { usePublicConfig } from '@/composables/usePublicConfig'
|
||||||
|
import { useI18n } from '@/composables/useI18n'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import ThemeSwitcher from '@/components/ui/ThemeSwitcher.vue'
|
||||||
|
import LanguageSwitcher from '@/components/ui/LanguageSwitcher.vue'
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
showDescription?: boolean
|
||||||
|
activeTab?: 'pickup' | 'upload'
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const emit = defineEmits<{
|
||||||
|
'update:activeTab': [value: 'pickup' | 'upload']
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const { config } = usePublicConfig()
|
||||||
|
const { t, locale } = useI18n()
|
||||||
|
|
||||||
|
// 用于动态计算按钮位置和宽度
|
||||||
|
const buttonGroup = ref<HTMLElement | null>(null)
|
||||||
|
const pickupButton = ref<HTMLElement | null>(null)
|
||||||
|
const uploadButton = ref<HTMLElement | null>(null)
|
||||||
|
const indicatorWidth = ref('0px')
|
||||||
|
const indicatorPosition = ref('0px')
|
||||||
|
const isInitialized = ref(false)
|
||||||
|
|
||||||
|
// 切换标签页
|
||||||
|
const switchTab = (tab: 'pickup' | 'upload') => {
|
||||||
|
emit('update:activeTab', tab)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新指示器位置和宽度
|
||||||
|
const updateIndicator = async () => {
|
||||||
|
// 等待 DOM 更新完成
|
||||||
|
await nextTick()
|
||||||
|
|
||||||
|
if (!buttonGroup.value || !pickupButton.value || !uploadButton.value) return
|
||||||
|
|
||||||
|
const containerRect = buttonGroup.value.getBoundingClientRect()
|
||||||
|
let activeButton: HTMLElement | null = null
|
||||||
|
|
||||||
|
if (props.activeTab === 'pickup') {
|
||||||
|
activeButton = pickupButton.value
|
||||||
|
} else if (props.activeTab === 'upload') {
|
||||||
|
activeButton = uploadButton.value
|
||||||
|
}
|
||||||
|
|
||||||
|
if (activeButton) {
|
||||||
|
const buttonRect = activeButton.getBoundingClientRect()
|
||||||
|
indicatorWidth.value = `${buttonRect.width}px`
|
||||||
|
indicatorPosition.value = `${buttonRect.left - containerRect.left}px`
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 监听 activeTab 变化
|
||||||
|
watch(() => props.activeTab, async () => {
|
||||||
|
await updateIndicator()
|
||||||
|
})
|
||||||
|
|
||||||
|
// 监听语言变化,重新计算指示器宽度
|
||||||
|
watch(locale, async () => {
|
||||||
|
// 等待翻译更新后再计算指示器
|
||||||
|
await nextTick()
|
||||||
|
await updateIndicator()
|
||||||
|
})
|
||||||
|
|
||||||
|
// 在组件挂载后初始化
|
||||||
|
onMounted(async () => {
|
||||||
|
// 先设置位置,不显示动画
|
||||||
|
await updateIndicator()
|
||||||
|
// 使用 requestAnimationFrame 确保位置已经应用到 DOM
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
requestAnimationFrame(() => {
|
||||||
|
// 启用动画效果
|
||||||
|
isInitialized.value = true
|
||||||
|
})
|
||||||
|
})
|
||||||
|
// 监听窗口大小变化,重新计算位置
|
||||||
|
window.addEventListener('resize', updateIndicator)
|
||||||
|
})
|
||||||
|
|
||||||
|
// 组件卸载时清理事件监听
|
||||||
|
onUnmounted(() => {
|
||||||
|
window.removeEventListener('resize', updateIndicator)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
171
webapp/src/components/ui/ThemeSwitcher.vue
Normal file
171
webapp/src/components/ui/ThemeSwitcher.vue
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||||
|
import { useDarkMode, type ThemeMode } from '@/composables/useDarkMode'
|
||||||
|
|
||||||
|
const { themeMode, setTheme } = useDarkMode()
|
||||||
|
const isExpanded = ref(false)
|
||||||
|
const isMobile = ref(false)
|
||||||
|
|
||||||
|
// 检测是否为移动端
|
||||||
|
const checkMobile = () => {
|
||||||
|
isMobile.value = window.innerWidth < 768 || ('ontouchstart' in window)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
checkMobile()
|
||||||
|
window.addEventListener('resize', checkMobile)
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
window.removeEventListener('resize', checkMobile)
|
||||||
|
})
|
||||||
|
|
||||||
|
// 获取当前主题的图标
|
||||||
|
const currentIcon = computed(() => {
|
||||||
|
switch (themeMode.value) {
|
||||||
|
case 'light':
|
||||||
|
return {
|
||||||
|
svg: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32l1.41 1.41M2 12h2m16 0h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>',
|
||||||
|
color: 'text-amber-500',
|
||||||
|
index: 0
|
||||||
|
}
|
||||||
|
case 'system':
|
||||||
|
return {
|
||||||
|
svg: '<rect x="2" y="3" width="20" height="14" rx="2"/><path d="M8 21h8M12 17v4"/>',
|
||||||
|
color: 'text-blue-500 dark:text-blue-400',
|
||||||
|
index: 1
|
||||||
|
}
|
||||||
|
case 'dark':
|
||||||
|
return {
|
||||||
|
svg: '<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>',
|
||||||
|
color: 'text-indigo-500 dark:text-indigo-400',
|
||||||
|
index: 2
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 计算指示器位置(展开时)
|
||||||
|
const indicatorPosition = computed(() => {
|
||||||
|
if (themeMode.value === 'light') return '0.0625rem'
|
||||||
|
if (themeMode.value === 'system') return '1.75rem'
|
||||||
|
return '3.4375rem'
|
||||||
|
})
|
||||||
|
|
||||||
|
// 计算容器偏移(收起时让当前按钮居中显示)
|
||||||
|
const containerOffset = computed(() => {
|
||||||
|
if (isExpanded.value) return '0px'
|
||||||
|
// 收起时根据当前主题位置调整偏移
|
||||||
|
const index = currentIcon.value.index
|
||||||
|
return `${-index * 28}px` // 28px = w-7 = 1.75rem
|
||||||
|
})
|
||||||
|
|
||||||
|
// 循环切换主题(移动端)
|
||||||
|
const cycleTheme = () => {
|
||||||
|
const modes: ThemeMode[] = ['light', 'system', 'dark']
|
||||||
|
const currentIndex = modes.indexOf(themeMode.value)
|
||||||
|
const nextIndex = (currentIndex + 1) % modes.length
|
||||||
|
setTheme(modes[nextIndex] as ThemeMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理鼠标进入(仅桌面端)
|
||||||
|
const handleMouseEnter = () => {
|
||||||
|
if (!isMobile.value) {
|
||||||
|
isExpanded.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理鼠标离开(仅桌面端)
|
||||||
|
const handleMouseLeave = () => {
|
||||||
|
if (!isMobile.value) {
|
||||||
|
isExpanded.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理点击
|
||||||
|
const handleClick = () => {
|
||||||
|
if (isMobile.value) {
|
||||||
|
cycleTheme()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理按钮点击
|
||||||
|
const handleButtonClick = (mode: ThemeMode, event: Event) => {
|
||||||
|
if (isMobile.value) {
|
||||||
|
// 移动端让事件冒泡到外层处理
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// 桌面端阻止冒泡并切换到指定主题
|
||||||
|
event.stopPropagation()
|
||||||
|
setTheme(mode)
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
@mouseenter="handleMouseEnter"
|
||||||
|
@mouseleave="handleMouseLeave"
|
||||||
|
@click="handleClick"
|
||||||
|
class="relative overflow-hidden rounded-full bg-gray-200 dark:bg-gray-700 transition-all duration-300 ease-in-out cursor-pointer"
|
||||||
|
:style="{ width: isExpanded ? '5.5rem' : '2rem', padding: '0.125rem' }"
|
||||||
|
>
|
||||||
|
<!-- 容器,用于横向滑动显示当前按钮 -->
|
||||||
|
<div
|
||||||
|
class="relative flex items-center transition-transform duration-300 ease-in-out"
|
||||||
|
:style="{ transform: `translateX(${containerOffset})` }"
|
||||||
|
>
|
||||||
|
<!-- 滑动指示器(仅展开时显示) -->
|
||||||
|
<div
|
||||||
|
v-show="isExpanded"
|
||||||
|
class="absolute top-0 bottom-0 w-7 bg-white dark:bg-gray-600 rounded-full shadow-sm transition-all duration-300 ease-in-out"
|
||||||
|
:style="{ left: indicatorPosition }"
|
||||||
|
></div>
|
||||||
|
|
||||||
|
<!-- 浅色模式按钮 -->
|
||||||
|
<button
|
||||||
|
@click="(e) => handleButtonClick('light', e)"
|
||||||
|
:class="[
|
||||||
|
'relative z-10 flex items-center justify-center w-7 h-7 rounded-full transition-all duration-200 flex-shrink-0',
|
||||||
|
themeMode === 'light' ? 'text-amber-500' : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
|
||||||
|
]"
|
||||||
|
:title="isExpanded ? '浅色模式' : ''"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||||
|
<circle cx="12" cy="12" r="4"/>
|
||||||
|
<path d="M12 2v2m0 16v2M4.93 4.93l1.41 1.41m11.32 11.32l1.41 1.41M2 12h2m16 0h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- 自动模式按钮 -->
|
||||||
|
<button
|
||||||
|
@click="(e) => handleButtonClick('system', e)"
|
||||||
|
:class="[
|
||||||
|
'relative z-10 flex items-center justify-center w-7 h-7 rounded-full transition-all duration-200 flex-shrink-0',
|
||||||
|
themeMode === 'system' ? 'text-blue-500 dark:text-blue-400' : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
|
||||||
|
]"
|
||||||
|
:title="isExpanded ? '跟随系统' : ''"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||||
|
<rect x="2" y="3" width="20" height="14" rx="2"/>
|
||||||
|
<path d="M8 21h8M12 17v4"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- 深色模式按钮 -->
|
||||||
|
<button
|
||||||
|
@click="(e) => handleButtonClick('dark', e)"
|
||||||
|
:class="[
|
||||||
|
'relative z-10 flex items-center justify-center w-7 h-7 rounded-full transition-all duration-200 flex-shrink-0',
|
||||||
|
themeMode === 'dark' ? 'text-indigo-500 dark:text-indigo-400' : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 dark:hover:text-gray-300'
|
||||||
|
]"
|
||||||
|
:title="isExpanded ? '深色模式' : ''"
|
||||||
|
type="button"
|
||||||
|
>
|
||||||
|
<svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
|
||||||
|
<path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
44
webapp/src/components/ui/ThemeToggle.vue
Normal file
44
webapp/src/components/ui/ThemeToggle.vue
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<template>
|
||||||
|
<Button variant="ghost" @click="cycleTheme" size="sm" class="w-9 h-9 p-0" :title="themeTitle">
|
||||||
|
<!-- Light Mode Icon -->
|
||||||
|
<svg v-if="themeMode === 'light'" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"></path>
|
||||||
|
</svg>
|
||||||
|
<!-- Dark Mode Icon -->
|
||||||
|
<svg v-else-if="themeMode === 'dark'" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"></path>
|
||||||
|
</svg>
|
||||||
|
<!-- System Mode Icon - 半太阳半月亮融合图标 -->
|
||||||
|
<svg v-else class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||||
|
<!-- 左半边:太阳光线 -->
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1M12 20v1M5.5 5.5l.7.7M17.8 17.8l.7.7"/>
|
||||||
|
<!-- 中间圆形 - 左半边太阳(填充) -->
|
||||||
|
<path d="M12 8 A4 4 0 0 1 12 16 Z" fill="currentColor" stroke="none"/>
|
||||||
|
<!-- 中间圆形 - 右半边月亮(描边) -->
|
||||||
|
<path d="M12 8 A4 4 0 0 0 12 16" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
<!-- 右半边:月亮装饰线 -->
|
||||||
|
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.5 5.5l-.7.7M6.2 17.8l-.7.7"/>
|
||||||
|
</svg>
|
||||||
|
</Button>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { useDarkMode } from '@/composables/useDarkMode'
|
||||||
|
|
||||||
|
const { themeMode, cycleTheme } = useDarkMode()
|
||||||
|
|
||||||
|
const themeTitle = computed(() => {
|
||||||
|
switch (themeMode.value) {
|
||||||
|
case 'light':
|
||||||
|
return '当前:明亮模式,点击切换'
|
||||||
|
case 'dark':
|
||||||
|
return '当前:暗黑模式,点击切换'
|
||||||
|
case 'system':
|
||||||
|
return '当前:跟随系统,点击切换'
|
||||||
|
default:
|
||||||
|
return '切换主题'
|
||||||
|
}
|
||||||
|
})
|
||||||
|
</script>
|
||||||
15
webapp/src/components/ui/alert-dialog/AlertDialog.vue
Normal file
15
webapp/src/components/ui/alert-dialog/AlertDialog.vue
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AlertDialogEmits, AlertDialogProps } from "reka-ui"
|
||||||
|
import { AlertDialogRoot, useForwardPropsEmits } from "reka-ui"
|
||||||
|
|
||||||
|
const props = defineProps<AlertDialogProps>()
|
||||||
|
const emits = defineEmits<AlertDialogEmits>()
|
||||||
|
|
||||||
|
const forwarded = useForwardPropsEmits(props, emits)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AlertDialogRoot v-slot="slotProps" data-slot="alert-dialog" v-bind="forwarded">
|
||||||
|
<slot v-bind="slotProps" />
|
||||||
|
</AlertDialogRoot>
|
||||||
|
</template>
|
||||||
18
webapp/src/components/ui/alert-dialog/AlertDialogAction.vue
Normal file
18
webapp/src/components/ui/alert-dialog/AlertDialogAction.vue
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AlertDialogActionProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { AlertDialogAction } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { buttonVariants } from '@/components/ui/button'
|
||||||
|
|
||||||
|
const props = defineProps<AlertDialogActionProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AlertDialogAction v-bind="delegatedProps" :class="cn(buttonVariants(), props.class)">
|
||||||
|
<slot />
|
||||||
|
</AlertDialogAction>
|
||||||
|
</template>
|
||||||
25
webapp/src/components/ui/alert-dialog/AlertDialogCancel.vue
Normal file
25
webapp/src/components/ui/alert-dialog/AlertDialogCancel.vue
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AlertDialogCancelProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { AlertDialogCancel } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { buttonVariants } from '@/components/ui/button'
|
||||||
|
|
||||||
|
const props = defineProps<AlertDialogCancelProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AlertDialogCancel
|
||||||
|
v-bind="delegatedProps"
|
||||||
|
:class="cn(
|
||||||
|
buttonVariants({ variant: 'outline' }),
|
||||||
|
'mt-2 sm:mt-0',
|
||||||
|
props.class,
|
||||||
|
)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</AlertDialogCancel>
|
||||||
|
</template>
|
||||||
44
webapp/src/components/ui/alert-dialog/AlertDialogContent.vue
Normal file
44
webapp/src/components/ui/alert-dialog/AlertDialogContent.vue
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AlertDialogContentEmits, AlertDialogContentProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import {
|
||||||
|
AlertDialogContent,
|
||||||
|
AlertDialogOverlay,
|
||||||
|
AlertDialogPortal,
|
||||||
|
useForwardPropsEmits,
|
||||||
|
} from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
defineOptions({
|
||||||
|
inheritAttrs: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const props = defineProps<AlertDialogContentProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
const emits = defineEmits<AlertDialogContentEmits>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AlertDialogPortal>
|
||||||
|
<AlertDialogOverlay
|
||||||
|
data-slot="alert-dialog-overlay"
|
||||||
|
class="data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80"
|
||||||
|
/>
|
||||||
|
<AlertDialogContent
|
||||||
|
data-slot="alert-dialog-content"
|
||||||
|
v-bind="{ ...$attrs, ...forwarded }"
|
||||||
|
:class="
|
||||||
|
cn(
|
||||||
|
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg',
|
||||||
|
props.class,
|
||||||
|
)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</AlertDialogContent>
|
||||||
|
</AlertDialogPortal>
|
||||||
|
</template>
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AlertDialogDescriptionProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import {
|
||||||
|
AlertDialogDescription,
|
||||||
|
} from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<AlertDialogDescriptionProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AlertDialogDescription
|
||||||
|
data-slot="alert-dialog-description"
|
||||||
|
v-bind="delegatedProps"
|
||||||
|
:class="cn('text-muted-foreground text-sm', props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</AlertDialogDescription>
|
||||||
|
</template>
|
||||||
22
webapp/src/components/ui/alert-dialog/AlertDialogFooter.vue
Normal file
22
webapp/src/components/ui/alert-dialog/AlertDialogFooter.vue
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-footer"
|
||||||
|
:class="
|
||||||
|
cn(
|
||||||
|
'flex flex-col-reverse gap-2 sm:flex-row sm:justify-end',
|
||||||
|
props.class,
|
||||||
|
)
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
17
webapp/src/components/ui/alert-dialog/AlertDialogHeader.vue
Normal file
17
webapp/src/components/ui/alert-dialog/AlertDialogHeader.vue
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div
|
||||||
|
data-slot="alert-dialog-header"
|
||||||
|
:class="cn('flex flex-col gap-2 text-center sm:text-left', props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
21
webapp/src/components/ui/alert-dialog/AlertDialogTitle.vue
Normal file
21
webapp/src/components/ui/alert-dialog/AlertDialogTitle.vue
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AlertDialogTitleProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { AlertDialogTitle } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<AlertDialogTitleProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AlertDialogTitle
|
||||||
|
data-slot="alert-dialog-title"
|
||||||
|
v-bind="delegatedProps"
|
||||||
|
:class="cn('text-lg font-semibold', props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</AlertDialogTitle>
|
||||||
|
</template>
|
||||||
12
webapp/src/components/ui/alert-dialog/AlertDialogTrigger.vue
Normal file
12
webapp/src/components/ui/alert-dialog/AlertDialogTrigger.vue
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AlertDialogTriggerProps } from "reka-ui"
|
||||||
|
import { AlertDialogTrigger } from "reka-ui"
|
||||||
|
|
||||||
|
const props = defineProps<AlertDialogTriggerProps>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AlertDialogTrigger data-slot="alert-dialog-trigger" v-bind="props">
|
||||||
|
<slot />
|
||||||
|
</AlertDialogTrigger>
|
||||||
|
</template>
|
||||||
9
webapp/src/components/ui/alert-dialog/index.ts
Normal file
9
webapp/src/components/ui/alert-dialog/index.ts
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
export { default as AlertDialog } from "./AlertDialog.vue"
|
||||||
|
export { default as AlertDialogAction } from "./AlertDialogAction.vue"
|
||||||
|
export { default as AlertDialogCancel } from "./AlertDialogCancel.vue"
|
||||||
|
export { default as AlertDialogContent } from "./AlertDialogContent.vue"
|
||||||
|
export { default as AlertDialogDescription } from "./AlertDialogDescription.vue"
|
||||||
|
export { default as AlertDialogFooter } from "./AlertDialogFooter.vue"
|
||||||
|
export { default as AlertDialogHeader } from "./AlertDialogHeader.vue"
|
||||||
|
export { default as AlertDialogTitle } from "./AlertDialogTitle.vue"
|
||||||
|
export { default as AlertDialogTrigger } from "./AlertDialogTrigger.vue"
|
||||||
18
webapp/src/components/ui/avatar/Avatar.vue
Normal file
18
webapp/src/components/ui/avatar/Avatar.vue
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { AvatarRoot } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<{
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AvatarRoot
|
||||||
|
data-slot="avatar"
|
||||||
|
:class="cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</AvatarRoot>
|
||||||
|
</template>
|
||||||
21
webapp/src/components/ui/avatar/AvatarFallback.vue
Normal file
21
webapp/src/components/ui/avatar/AvatarFallback.vue
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AvatarFallbackProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { AvatarFallback } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<AvatarFallbackProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AvatarFallback
|
||||||
|
data-slot="avatar-fallback"
|
||||||
|
v-bind="delegatedProps"
|
||||||
|
:class="cn('bg-muted flex size-full items-center justify-center rounded-full', props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</AvatarFallback>
|
||||||
|
</template>
|
||||||
16
webapp/src/components/ui/avatar/AvatarImage.vue
Normal file
16
webapp/src/components/ui/avatar/AvatarImage.vue
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { AvatarImageProps } from "reka-ui"
|
||||||
|
import { AvatarImage } from "reka-ui"
|
||||||
|
|
||||||
|
const props = defineProps<AvatarImageProps>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<AvatarImage
|
||||||
|
data-slot="avatar-image"
|
||||||
|
v-bind="props"
|
||||||
|
class="aspect-square size-full"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</AvatarImage>
|
||||||
|
</template>
|
||||||
3
webapp/src/components/ui/avatar/index.ts
Normal file
3
webapp/src/components/ui/avatar/index.ts
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
export { default as Avatar } from "./Avatar.vue"
|
||||||
|
export { default as AvatarFallback } from "./AvatarFallback.vue"
|
||||||
|
export { default as AvatarImage } from "./AvatarImage.vue"
|
||||||
26
webapp/src/components/ui/badge/Badge.vue
Normal file
26
webapp/src/components/ui/badge/Badge.vue
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { PrimitiveProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import type { BadgeVariants } from "."
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { Primitive } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { badgeVariants } from "."
|
||||||
|
|
||||||
|
const props = defineProps<PrimitiveProps & {
|
||||||
|
variant?: BadgeVariants["variant"]
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Primitive
|
||||||
|
data-slot="badge"
|
||||||
|
:class="cn(badgeVariants({ variant }), props.class)"
|
||||||
|
v-bind="delegatedProps"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</Primitive>
|
||||||
|
</template>
|
||||||
26
webapp/src/components/ui/badge/index.ts
Normal file
26
webapp/src/components/ui/badge/index.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import type { VariantProps } from "class-variance-authority"
|
||||||
|
import { cva } from "class-variance-authority"
|
||||||
|
|
||||||
|
export { default as Badge } from "./Badge.vue"
|
||||||
|
|
||||||
|
export const badgeVariants = cva(
|
||||||
|
"inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
|
||||||
|
secondary:
|
||||||
|
"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
|
||||||
|
destructive:
|
||||||
|
"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
export type BadgeVariants = VariantProps<typeof badgeVariants>
|
||||||
29
webapp/src/components/ui/button/Button.vue
Normal file
29
webapp/src/components/ui/button/Button.vue
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
<script setup lang="ts">
|
||||||
|
import type { PrimitiveProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import type { ButtonVariants } from "."
|
||||||
|
import { Primitive } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { buttonVariants } from "."
|
||||||
|
|
||||||
|
interface Props extends PrimitiveProps {
|
||||||
|
variant?: ButtonVariants["variant"]
|
||||||
|
size?: ButtonVariants["size"]
|
||||||
|
class?: HTMLAttributes["class"]
|
||||||
|
}
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<Props>(), {
|
||||||
|
as: "button",
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<Primitive
|
||||||
|
data-slot="button"
|
||||||
|
:as="as"
|
||||||
|
:as-child="asChild"
|
||||||
|
:class="cn(buttonVariants({ variant, size }), props.class)"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</Primitive>
|
||||||
|
</template>
|
||||||
38
webapp/src/components/ui/button/index.ts
Normal file
38
webapp/src/components/ui/button/index.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import type { VariantProps } from "class-variance-authority"
|
||||||
|
import { cva } from "class-variance-authority"
|
||||||
|
|
||||||
|
export { default as Button } from "./Button.vue"
|
||||||
|
|
||||||
|
export const buttonVariants = cva(
|
||||||
|
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||||
|
{
|
||||||
|
variants: {
|
||||||
|
variant: {
|
||||||
|
default:
|
||||||
|
"bg-primary text-primary-foreground hover:bg-primary/90",
|
||||||
|
destructive:
|
||||||
|
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||||
|
outline:
|
||||||
|
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||||
|
secondary:
|
||||||
|
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||||
|
ghost:
|
||||||
|
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||||
|
link: "text-primary underline-offset-4 hover:underline",
|
||||||
|
},
|
||||||
|
size: {
|
||||||
|
"default": "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||||
|
"sm": "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||||
|
"lg": "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||||
|
"icon": "size-9",
|
||||||
|
"icon-sm": "size-8",
|
||||||
|
"icon-lg": "size-10",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
defaultVariants: {
|
||||||
|
variant: "default",
|
||||||
|
size: "default",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
export type ButtonVariants = VariantProps<typeof buttonVariants>
|
||||||
160
webapp/src/components/ui/calendar/Calendar.vue
Normal file
160
webapp/src/components/ui/calendar/Calendar.vue
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarRootEmits, CalendarRootProps, DateValue } from "reka-ui"
|
||||||
|
import type { HTMLAttributes, Ref } from "vue"
|
||||||
|
import type { LayoutTypes } from "."
|
||||||
|
import { getLocalTimeZone, today } from "@internationalized/date"
|
||||||
|
import { createReusableTemplate, reactiveOmit, useVModel } from "@vueuse/core"
|
||||||
|
import { CalendarRoot, useDateFormatter, useForwardPropsEmits } from "reka-ui"
|
||||||
|
import { createYear, createYearRange, toDate } from "reka-ui/date"
|
||||||
|
import { computed, toRaw } from "vue"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select'
|
||||||
|
import { CalendarCell, CalendarCellTrigger, CalendarGrid, CalendarGridBody, CalendarGridHead, CalendarGridRow, CalendarHeadCell, CalendarHeader, CalendarHeading, CalendarNextButton, CalendarPrevButton } from "."
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<CalendarRootProps & { class?: HTMLAttributes["class"], layout?: LayoutTypes, yearRange?: DateValue[] }>(), {
|
||||||
|
modelValue: undefined,
|
||||||
|
layout: undefined,
|
||||||
|
})
|
||||||
|
const emits = defineEmits<CalendarRootEmits>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class", "layout", "placeholder")
|
||||||
|
|
||||||
|
const placeholder = useVModel(props, "placeholder", emits, {
|
||||||
|
passive: true,
|
||||||
|
defaultValue: props.defaultPlaceholder ?? today(getLocalTimeZone()),
|
||||||
|
}) as Ref<DateValue>
|
||||||
|
|
||||||
|
const formatter = useDateFormatter(props.locale ?? "en")
|
||||||
|
|
||||||
|
const yearRange = computed(() => {
|
||||||
|
return props.yearRange ?? createYearRange({
|
||||||
|
start: props?.minValue ?? (toRaw(props.placeholder) ?? props.defaultPlaceholder ?? today(getLocalTimeZone()))
|
||||||
|
.cycle("year", -100),
|
||||||
|
|
||||||
|
end: props?.maxValue ?? (toRaw(props.placeholder) ?? props.defaultPlaceholder ?? today(getLocalTimeZone()))
|
||||||
|
.cycle("year", 10),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
const [DefineMonthTemplate, ReuseMonthTemplate] = createReusableTemplate<{ date: DateValue }>()
|
||||||
|
const [DefineYearTemplate, ReuseYearTemplate] = createReusableTemplate<{ date: DateValue }>()
|
||||||
|
|
||||||
|
const forwarded = useForwardPropsEmits(delegatedProps, emits)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<DefineMonthTemplate v-slot="{ date }">
|
||||||
|
<div class="**:data-[slot=native-select-icon]:right-1">
|
||||||
|
<div class="relative">
|
||||||
|
<div class="absolute inset-0 flex h-full items-center text-sm pl-2 pointer-events-none">
|
||||||
|
{{ formatter.custom(toDate(date), { month: 'short' }) }}
|
||||||
|
</div>
|
||||||
|
<NativeSelect
|
||||||
|
class="text-xs h-8 pr-6 pl-2 text-transparent relative"
|
||||||
|
@change="(e: Event) => {
|
||||||
|
placeholder = placeholder.set({
|
||||||
|
month: Number((e?.target as any)?.value),
|
||||||
|
})
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
<NativeSelectOption v-for="(month) in createYear({ dateObj: date })" :key="month.toString()" :value="month.month" :selected="date.month === month.month">
|
||||||
|
{{ formatter.custom(toDate(month), { month: 'short' }) }}
|
||||||
|
</NativeSelectOption>
|
||||||
|
</NativeSelect>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DefineMonthTemplate>
|
||||||
|
|
||||||
|
<DefineYearTemplate v-slot="{ date }">
|
||||||
|
<div class="**:data-[slot=native-select-icon]:right-1">
|
||||||
|
<div class="relative">
|
||||||
|
<div class="absolute inset-0 flex h-full items-center text-sm pl-2 pointer-events-none">
|
||||||
|
{{ formatter.custom(toDate(date), { year: 'numeric' }) }}
|
||||||
|
</div>
|
||||||
|
<NativeSelect
|
||||||
|
class="text-xs h-8 pr-6 pl-2 text-transparent relative"
|
||||||
|
@change="(e: Event) => {
|
||||||
|
placeholder = placeholder.set({
|
||||||
|
year: Number((e?.target as any)?.value),
|
||||||
|
})
|
||||||
|
}"
|
||||||
|
>
|
||||||
|
<NativeSelectOption v-for="(year) in yearRange" :key="year.toString()" :value="year.year" :selected="date.year === year.year">
|
||||||
|
{{ formatter.custom(toDate(year), { year: 'numeric' }) }}
|
||||||
|
</NativeSelectOption>
|
||||||
|
</NativeSelect>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</DefineYearTemplate>
|
||||||
|
|
||||||
|
<CalendarRoot
|
||||||
|
v-slot="{ grid, weekDays, date }"
|
||||||
|
v-bind="forwarded"
|
||||||
|
v-model:placeholder="placeholder"
|
||||||
|
data-slot="calendar"
|
||||||
|
:class="cn('p-3', props.class)"
|
||||||
|
>
|
||||||
|
<CalendarHeader class="pt-0">
|
||||||
|
<nav class="flex items-center gap-1 absolute top-0 inset-x-0 justify-between">
|
||||||
|
<CalendarPrevButton>
|
||||||
|
<slot name="calendar-prev-icon" />
|
||||||
|
</CalendarPrevButton>
|
||||||
|
<CalendarNextButton>
|
||||||
|
<slot name="calendar-next-icon" />
|
||||||
|
</CalendarNextButton>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<slot name="calendar-heading" :date="date" :month="ReuseMonthTemplate" :year="ReuseYearTemplate">
|
||||||
|
<template v-if="layout === 'month-and-year'">
|
||||||
|
<div class="flex items-center justify-center gap-1">
|
||||||
|
<ReuseMonthTemplate :date="date" />
|
||||||
|
<ReuseYearTemplate :date="date" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="layout === 'month-only'">
|
||||||
|
<div class="flex items-center justify-center gap-1">
|
||||||
|
<ReuseMonthTemplate :date="date" />
|
||||||
|
{{ formatter.custom(toDate(date), { year: 'numeric' }) }}
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else-if="layout === 'year-only'">
|
||||||
|
<div class="flex items-center justify-center gap-1">
|
||||||
|
{{ formatter.custom(toDate(date), { month: 'short' }) }}
|
||||||
|
<ReuseYearTemplate :date="date" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
<CalendarHeading />
|
||||||
|
</template>
|
||||||
|
</slot>
|
||||||
|
</CalendarHeader>
|
||||||
|
|
||||||
|
<div class="flex flex-col gap-y-4 mt-4 sm:flex-row sm:gap-x-4 sm:gap-y-0">
|
||||||
|
<CalendarGrid v-for="month in grid" :key="month.value.toString()">
|
||||||
|
<CalendarGridHead>
|
||||||
|
<CalendarGridRow>
|
||||||
|
<CalendarHeadCell
|
||||||
|
v-for="day in weekDays" :key="day"
|
||||||
|
>
|
||||||
|
{{ day }}
|
||||||
|
</CalendarHeadCell>
|
||||||
|
</CalendarGridRow>
|
||||||
|
</CalendarGridHead>
|
||||||
|
<CalendarGridBody>
|
||||||
|
<CalendarGridRow v-for="(weekDates, index) in month.rows" :key="`weekDate-${index}`" class="mt-2 w-full">
|
||||||
|
<CalendarCell
|
||||||
|
v-for="weekDate in weekDates"
|
||||||
|
:key="weekDate.toString()"
|
||||||
|
:date="weekDate"
|
||||||
|
>
|
||||||
|
<CalendarCellTrigger
|
||||||
|
:day="weekDate"
|
||||||
|
:month="month.value"
|
||||||
|
/>
|
||||||
|
</CalendarCell>
|
||||||
|
</CalendarGridRow>
|
||||||
|
</CalendarGridBody>
|
||||||
|
</CalendarGrid>
|
||||||
|
</div>
|
||||||
|
</CalendarRoot>
|
||||||
|
</template>
|
||||||
23
webapp/src/components/ui/calendar/CalendarCell.vue
Normal file
23
webapp/src/components/ui/calendar/CalendarCell.vue
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarCellProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { CalendarCell, useForwardProps } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarCellProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarCell
|
||||||
|
data-slot="calendar-cell"
|
||||||
|
:class="cn('relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([data-selected])]:rounded-md [&:has([data-selected])]:bg-accent', props.class)"
|
||||||
|
v-bind="forwardedProps"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarCell>
|
||||||
|
</template>
|
||||||
39
webapp/src/components/ui/calendar/CalendarCellTrigger.vue
Normal file
39
webapp/src/components/ui/calendar/CalendarCellTrigger.vue
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarCellTriggerProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { CalendarCellTrigger, useForwardProps } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
import { buttonVariants } from '@/components/ui/button'
|
||||||
|
|
||||||
|
const props = withDefaults(defineProps<CalendarCellTriggerProps & { class?: HTMLAttributes["class"] }>(), {
|
||||||
|
as: "button",
|
||||||
|
})
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarCellTrigger
|
||||||
|
data-slot="calendar-cell-trigger"
|
||||||
|
:class="cn(
|
||||||
|
buttonVariants({ variant: 'ghost' }),
|
||||||
|
'size-8 p-0 font-normal aria-selected:opacity-100 cursor-default',
|
||||||
|
'[&[data-today]:not([data-selected])]:bg-accent [&[data-today]:not([data-selected])]:text-accent-foreground',
|
||||||
|
// Selected
|
||||||
|
'data-[selected]:bg-primary data-[selected]:text-primary-foreground data-[selected]:opacity-100 data-[selected]:hover:bg-primary data-[selected]:hover:text-primary-foreground data-[selected]:focus:bg-primary data-[selected]:focus:text-primary-foreground',
|
||||||
|
// Disabled
|
||||||
|
'data-[disabled]:text-muted-foreground data-[disabled]:opacity-50',
|
||||||
|
// Unavailable
|
||||||
|
'data-[unavailable]:text-destructive-foreground data-[unavailable]:line-through',
|
||||||
|
// Outside months
|
||||||
|
'data-[outside-view]:text-muted-foreground',
|
||||||
|
props.class,
|
||||||
|
)"
|
||||||
|
v-bind="forwardedProps"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarCellTrigger>
|
||||||
|
</template>
|
||||||
23
webapp/src/components/ui/calendar/CalendarGrid.vue
Normal file
23
webapp/src/components/ui/calendar/CalendarGrid.vue
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarGridProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { CalendarGrid, useForwardProps } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarGridProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarGrid
|
||||||
|
data-slot="calendar-grid"
|
||||||
|
:class="cn('w-full border-collapse space-x-1', props.class)"
|
||||||
|
v-bind="forwardedProps"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarGrid>
|
||||||
|
</template>
|
||||||
15
webapp/src/components/ui/calendar/CalendarGridBody.vue
Normal file
15
webapp/src/components/ui/calendar/CalendarGridBody.vue
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarGridBodyProps } from "reka-ui"
|
||||||
|
import { CalendarGridBody } from "reka-ui"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarGridBodyProps>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarGridBody
|
||||||
|
data-slot="calendar-grid-body"
|
||||||
|
v-bind="props"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarGridBody>
|
||||||
|
</template>
|
||||||
16
webapp/src/components/ui/calendar/CalendarGridHead.vue
Normal file
16
webapp/src/components/ui/calendar/CalendarGridHead.vue
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarGridHeadProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { CalendarGridHead } from "reka-ui"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarGridHeadProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarGridHead
|
||||||
|
data-slot="calendar-grid-head"
|
||||||
|
v-bind="props"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarGridHead>
|
||||||
|
</template>
|
||||||
22
webapp/src/components/ui/calendar/CalendarGridRow.vue
Normal file
22
webapp/src/components/ui/calendar/CalendarGridRow.vue
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarGridRowProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { CalendarGridRow, useForwardProps } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarGridRowProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarGridRow
|
||||||
|
data-slot="calendar-grid-row"
|
||||||
|
:class="cn('flex', props.class)" v-bind="forwardedProps"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarGridRow>
|
||||||
|
</template>
|
||||||
23
webapp/src/components/ui/calendar/CalendarHeadCell.vue
Normal file
23
webapp/src/components/ui/calendar/CalendarHeadCell.vue
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarHeadCellProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { CalendarHeadCell, useForwardProps } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarHeadCellProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarHeadCell
|
||||||
|
data-slot="calendar-head-cell"
|
||||||
|
:class="cn('text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem]', props.class)"
|
||||||
|
v-bind="forwardedProps"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarHeadCell>
|
||||||
|
</template>
|
||||||
23
webapp/src/components/ui/calendar/CalendarHeader.vue
Normal file
23
webapp/src/components/ui/calendar/CalendarHeader.vue
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarHeaderProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { CalendarHeader, useForwardProps } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarHeaderProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarHeader
|
||||||
|
data-slot="calendar-header"
|
||||||
|
:class="cn('flex justify-center pt-1 relative items-center w-full px-8', props.class)"
|
||||||
|
v-bind="forwardedProps"
|
||||||
|
>
|
||||||
|
<slot />
|
||||||
|
</CalendarHeader>
|
||||||
|
</template>
|
||||||
30
webapp/src/components/ui/calendar/CalendarHeading.vue
Normal file
30
webapp/src/components/ui/calendar/CalendarHeading.vue
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
<script lang="ts" setup>
|
||||||
|
import type { CalendarHeadingProps } from "reka-ui"
|
||||||
|
import type { HTMLAttributes } from "vue"
|
||||||
|
import { reactiveOmit } from "@vueuse/core"
|
||||||
|
import { CalendarHeading, useForwardProps } from "reka-ui"
|
||||||
|
import { cn } from "@/lib/utils"
|
||||||
|
|
||||||
|
const props = defineProps<CalendarHeadingProps & { class?: HTMLAttributes["class"] }>()
|
||||||
|
|
||||||
|
defineSlots<{
|
||||||
|
default: (props: { headingValue: string }) => any
|
||||||
|
}>()
|
||||||
|
|
||||||
|
const delegatedProps = reactiveOmit(props, "class")
|
||||||
|
|
||||||
|
const forwardedProps = useForwardProps(delegatedProps)
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<CalendarHeading
|
||||||
|
v-slot="{ headingValue }"
|
||||||
|
data-slot="calendar-heading"
|
||||||
|
:class="cn('text-sm font-medium', props.class)"
|
||||||
|
v-bind="forwardedProps"
|
||||||
|
>
|
||||||
|
<slot :heading-value>
|
||||||
|
{{ headingValue }}
|
||||||
|
</slot>
|
||||||
|
</CalendarHeading>
|
||||||
|
</template>
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user