mirror of
https://github.com/ctwj/urldb.git
synced 2025-11-25 19:37:33 +08:00
Compare commits
56 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c1b19cf937 | ||
|
|
4d3f4a082e | ||
|
|
ba7dd4d064 | ||
|
|
78b147da47 | ||
|
|
f9ecbad0a7 | ||
|
|
53fbaabc63 | ||
|
|
97f92ea26c | ||
|
|
d7b273dfae | ||
|
|
4c56289bfe | ||
|
|
cf3376eb31 | ||
|
|
312ecb041a | ||
|
|
a5c5e41cc4 | ||
|
|
f0e5c93a48 | ||
|
|
2582920e2c | ||
|
|
50ee23db1c | ||
|
|
6cbd1f5d17 | ||
|
|
eba01b540b | ||
|
|
0434d069ce | ||
|
|
443d67ad78 | ||
|
|
4463960447 | ||
|
|
595c44b437 | ||
|
|
00606ef73e | ||
|
|
d4fe64819f | ||
|
|
32c8c30c05 | ||
|
|
e2d4960c4c | ||
|
|
42ffc1e2e8 | ||
|
|
cdd6b9985c | ||
|
|
dbc8fa9c36 | ||
|
|
67e15e03dc | ||
|
|
4ad176273e | ||
|
|
a606897253 | ||
|
|
cf31106cb7 | ||
|
|
a21554f1cd | ||
|
|
edfb0a43aa | ||
|
|
35052f7735 | ||
|
|
8a3d01fd28 | ||
|
|
6e59133924 | ||
|
|
91b743999a | ||
|
|
ed6a1567f3 | ||
|
|
d3ed3ef990 | ||
|
|
ea60d730e2 | ||
|
|
21e2779d28 | ||
|
|
c54a78c67f | ||
|
|
db41ba5ce3 | ||
|
|
72f7764e36 | ||
|
|
8ed7cbc181 | ||
|
|
51975ad408 | ||
|
|
1bb14e218e | ||
|
|
3646c371a4 | ||
|
|
687fc6062d | ||
|
|
505e508bca | ||
|
|
d481083140 | ||
|
|
c76298a10b | ||
|
|
2cb91072ba | ||
|
|
b84193c9e0 | ||
|
|
ff79f9e9f3 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -15,6 +15,7 @@ go.work.sum
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
!web/.env
|
||||
web/.output/
|
||||
|
||||
# IDE
|
||||
|
||||
@@ -76,10 +76,4 @@
|
||||
1. 在提交代码时使用规范的提交信息2. 在Pull Request中描述您的更改
|
||||
3. 遵循项目的贡献指南
|
||||
|
||||
---
|
||||
|
||||
## 链接
|
||||
|
||||
- [项目主页](https://github.com/your-username/l9pan)
|
||||
- [问题反馈](https://github.com/your-username/l9pan/issues)
|
||||
- [讨论区](https://github.com/your-username/l9
|
||||
---
|
||||
28
Dockerfile
28
Dockerfile
@@ -2,27 +2,23 @@
|
||||
FROM node:20-slim AS frontend-builder
|
||||
|
||||
# 安装pnpm
|
||||
RUN npm install -g pnpm
|
||||
|
||||
WORKDIR /app/web
|
||||
COPY web/package*.json ./
|
||||
COPY web/pnpm-lock.yaml ./
|
||||
RUN pnpm install --frozen-lockfile
|
||||
|
||||
COPY web/ ./
|
||||
RUN pnpm run build
|
||||
RUN npm install --frozen-lockfile
|
||||
ARG NUXT_PUBLIC_API_SERVER=http://backend:8080/api
|
||||
ARG NUXT_PUBLIC_API_CLIENT=/api
|
||||
RUN npm run build
|
||||
|
||||
# 前端运行阶段
|
||||
FROM node:18-alpine AS frontend
|
||||
FROM node:20-alpine AS frontend
|
||||
|
||||
RUN npm install -g pnpm
|
||||
# RUN npm install -g pnpm
|
||||
ENV NODE_ENV=production
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=frontend-builder /app/web/.output ./.output
|
||||
COPY --from=frontend-builder /app/web/package*.json ./
|
||||
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["node", ".output/server/index.mjs"]
|
||||
|
||||
# 后端构建阶段
|
||||
@@ -32,12 +28,18 @@ WORKDIR /app
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
# 先复制VERSION文件,确保构建时能正确读取版本号
|
||||
COPY VERSION ./
|
||||
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main .
|
||||
|
||||
# 后端运行阶段
|
||||
FROM alpine:latest AS backend
|
||||
|
||||
# 安装时区数据
|
||||
RUN apk add --no-cache tzdata
|
||||
|
||||
WORKDIR /root/
|
||||
|
||||
# 复制后端二进制文件
|
||||
@@ -46,6 +48,10 @@ COPY --from=backend-builder /app/main .
|
||||
# 创建uploads目录
|
||||
RUN mkdir -p uploads
|
||||
|
||||
# 设置环境变量
|
||||
ENV GIN_MODE=release
|
||||
ENV TZ=Asia/Shanghai
|
||||
|
||||
# 暴露端口
|
||||
EXPOSE 8080
|
||||
|
||||
|
||||
73
README.md
73
README.md
@@ -1,4 +1,4 @@
|
||||
# 🚀 urlDB - 网盘资源数据库
|
||||
# 🚀 urlDB - 老九网盘资源数据库
|
||||
|
||||
<div align="center">
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|
||||
**一个现代化的网盘资源数据库,支持多网盘自动化转存分享,支持百度网盘,阿里云盘,夸克网盘, 天翼云盘,迅雷云盘,123云盘,115网盘,UC网盘 **
|
||||
|
||||
🌐 [在线演示](#) | 📖 [文档](#) | 🐛 [问题反馈](#) | ⭐ [给个星标](#)
|
||||
🌐 [在线演示](https://pan.l9.lc) | 📖 [文档](http://doc.l9.lc/) | 🐛 [问题反馈](https://github.com/ctwj/urldb/issues) | ⭐ [给个星标](https://github.com/ctwj/urldb)
|
||||
|
||||
### 支持的网盘平台
|
||||
|
||||
@@ -90,7 +90,7 @@ cd urldb
|
||||
docker compose up --build -d
|
||||
|
||||
# 访问应用
|
||||
# 前端: http://localhost:3000
|
||||
# 前端: http://localhost:3030
|
||||
# 后端API: http://localhost:8080
|
||||
```
|
||||
|
||||
@@ -175,54 +175,6 @@ l9pan/
|
||||
|
||||
## 🔧 配置说明
|
||||
|
||||
### 版本管理
|
||||
|
||||
项目使用GitHub进行版本管理,支持自动创建Release和标签。
|
||||
|
||||
#### 版本管理脚本
|
||||
|
||||
```bash
|
||||
# 显示当前版本信息
|
||||
./scripts/version.sh show
|
||||
|
||||
# 更新版本号
|
||||
./scripts/version.sh patch # 修订版本 (1.0.0 -> 1.0.1)
|
||||
./scripts/version.sh minor # 次版本 (1.0.0 -> 1.1.0)
|
||||
./scripts/version.sh major # 主版本 (1.0.0 -> 2.0.0)
|
||||
|
||||
# 发布版本到GitHub
|
||||
./scripts/version.sh release
|
||||
|
||||
# 生成版本信息文件
|
||||
./scripts/version.sh update
|
||||
|
||||
# 查看帮助
|
||||
./scripts/version.sh help
|
||||
```
|
||||
|
||||
#### 自动发布流程
|
||||
|
||||
1. **更新版本号**: 修改 `VERSION` 文件
|
||||
2. **同步文件**: 更新 `package.json`、`docker-compose.yml`、`README.md`
|
||||
3. **创建Git标签**: 自动创建版本标签
|
||||
4. **推送代码**: 推送代码和标签到GitHub
|
||||
5. **创建Release**: 自动创建GitHub Release
|
||||
|
||||
#### 版本API接口
|
||||
|
||||
- `GET /api/version` - 获取版本信息
|
||||
- `GET /api/version/string` - 获取版本字符串
|
||||
- `GET /api/version/full` - 获取完整版本信息
|
||||
- `GET /api/version/check-update` - 检查GitHub上的最新版本
|
||||
|
||||
#### 版本信息页面
|
||||
|
||||
访问 `/version` 页面查看详细的版本信息和更新状态。
|
||||
|
||||
#### 详细文档
|
||||
|
||||
查看 [GitHub版本管理指南](docs/github-version-management.md) 了解完整的版本管理流程。
|
||||
|
||||
### 环境变量配置
|
||||
|
||||
```bash
|
||||
@@ -235,15 +187,26 @@ DB_NAME=url_db
|
||||
|
||||
# 服务器配置
|
||||
PORT=8080
|
||||
|
||||
# 时区配置
|
||||
TIMEZONE=Asia/Shanghai
|
||||
```
|
||||
|
||||
### Docker 服务说明
|
||||
|
||||
| 服务 | 端口 | 说明 |
|
||||
|------|------|------|
|
||||
| frontend | 3000 | Nuxt.js 前端应用 |
|
||||
| backend | 8080 | Go API 后端服务 |
|
||||
| postgres | 5432 | PostgreSQL 数据库 |
|
||||
| server | 3030 | 应用 |
|
||||
| postgres | 5431 | PostgreSQL 数据库 |
|
||||
|
||||
### 镜像构建
|
||||
|
||||
```
|
||||
docker build -t ctwj/urldb-frontend:1.0.7 --target frontend .
|
||||
docker build -t ctwj/urldb-backend:1.0.7 --target backend .
|
||||
docker push ctwj/urldb-frontend:1.0.7
|
||||
docker push ctwj/urldb-backend:1.0.7
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -253,7 +216,7 @@ PORT=8080
|
||||
|
||||
提供,批量入库和搜索api,通过 apiToken 授权
|
||||
|
||||
> 📖 完整API文档请访问:`http://p.l9.lc/doc.html`
|
||||
> 📖 完整API文档请访问:`http://doc.l9.lc/`
|
||||
|
||||
## 🤝 贡献指南
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package pan
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
@@ -84,7 +83,7 @@ func (a *AlipanService) Transfer(shareID string) (*TransferResult, error) {
|
||||
config := a.config
|
||||
a.configMutex.RUnlock()
|
||||
|
||||
log.Printf("开始处理阿里云盘分享: %s", shareID)
|
||||
fmt.Printf("开始处理阿里云盘分享: %s", shareID)
|
||||
|
||||
// 获取access token
|
||||
accessToken, err := a.manageAccessToken()
|
||||
|
||||
@@ -16,6 +16,7 @@ const (
|
||||
BaiduPan
|
||||
UC
|
||||
NotFound
|
||||
Xunlei
|
||||
)
|
||||
|
||||
// String 返回服务类型的字符串表示
|
||||
@@ -29,6 +30,8 @@ func (s ServiceType) String() string {
|
||||
return "baidu"
|
||||
case UC:
|
||||
return "uc"
|
||||
case Xunlei:
|
||||
return "xunlei"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
@@ -42,6 +45,7 @@ type PanConfig struct {
|
||||
ExpiredType int `json:"expiredType"` // 1: 分享永久, 2: 临时
|
||||
AdFid string `json:"adFid"` // 夸克专用 - 分享时带上这个文件的fid
|
||||
Stoken string `json:"stoken"`
|
||||
Cookie string `json:"cookie"`
|
||||
}
|
||||
|
||||
// TransferResult 转存结果
|
||||
@@ -172,6 +176,7 @@ func ExtractServiceType(url string) ServiceType {
|
||||
"pan.baidu.com": BaiduPan,
|
||||
"drive.uc.cn": UC,
|
||||
"fast.uc.cn": UC,
|
||||
"pan.xunlei.com": Xunlei,
|
||||
}
|
||||
|
||||
for pattern, serviceType := range patterns {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -42,6 +43,7 @@ func NewQuarkPanService(config *PanConfig) *QuarkPanService {
|
||||
"Referer": "https://pan.quark.cn/",
|
||||
"Referrer-Policy": "strict-origin-when-cross-origin",
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
|
||||
"Cookie": config.Cookie,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -66,6 +68,25 @@ func (q *QuarkPanService) UpdateConfig(config *PanConfig) {
|
||||
defer q.configMutex.Unlock()
|
||||
|
||||
q.config = config
|
||||
// 设置Cookie到header
|
||||
if config.Cookie != "" {
|
||||
q.SetHeader("Cookie", config.Cookie)
|
||||
}
|
||||
}
|
||||
|
||||
// SetCookie 设置Cookie
|
||||
func (q *QuarkPanService) SetCookie(cookie string) {
|
||||
q.SetHeader("Cookie", cookie)
|
||||
q.configMutex.Lock()
|
||||
if q.config != nil {
|
||||
q.config.Cookie = cookie
|
||||
}
|
||||
q.configMutex.Unlock()
|
||||
}
|
||||
|
||||
// GetCookie 获取当前Cookie
|
||||
func (q *QuarkPanService) GetCookie() string {
|
||||
return q.GetHeader("Cookie")
|
||||
}
|
||||
|
||||
// GetServiceType 获取服务类型
|
||||
@@ -383,11 +404,23 @@ func (q *QuarkPanService) getShareSave(shareID, stoken string, fidList, fidToken
|
||||
return &response.Data, nil
|
||||
}
|
||||
|
||||
// 生成指定长度的时间戳
|
||||
func (q *QuarkPanService) generateTimestamp(length int) int64 {
|
||||
timestamp := time.Now().UnixNano() / int64(time.Millisecond)
|
||||
timestampStr := strconv.FormatInt(timestamp, 10)
|
||||
if len(timestampStr) > length {
|
||||
timestampStr = timestampStr[:length]
|
||||
}
|
||||
timestamp, _ = strconv.ParseInt(timestampStr, 10, 64)
|
||||
return timestamp
|
||||
}
|
||||
|
||||
// getShareBtn 分享按钮
|
||||
func (q *QuarkPanService) getShareBtn(fidList []string, title string) (*ShareBtnResult, error) {
|
||||
data := map[string]interface{}{
|
||||
"fid_list": fidList,
|
||||
"title": title,
|
||||
"url_type": 1,
|
||||
"expired_type": 1, // 永久分享
|
||||
}
|
||||
|
||||
@@ -397,7 +430,7 @@ func (q *QuarkPanService) getShareBtn(fidList []string, title string) (*ShareBtn
|
||||
"uc_param_str": "",
|
||||
}
|
||||
|
||||
respData, err := q.HTTPPost("https://drive-pc.quark.cn/1/clouddrive/share/create", data, queryParams)
|
||||
respData, err := q.HTTPPost("https://drive-pc.quark.cn/1/clouddrive/share", data, queryParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -427,9 +460,11 @@ func (q *QuarkPanService) getShareTask(taskID string, retryIndex int) (*TaskResu
|
||||
"uc_param_str": "",
|
||||
"task_id": taskID,
|
||||
"retry_index": fmt.Sprintf("%d", retryIndex),
|
||||
"__dt": "21192",
|
||||
"__t": fmt.Sprintf("%d", q.generateTimestamp(13)),
|
||||
}
|
||||
|
||||
respData, err := q.HTTPGet("https://drive-pc.quark.cn/1/clouddrive/share/sharepage/task", queryParams)
|
||||
respData, err := q.HTTPGet("https://drive-pc.quark.cn/1/clouddrive/task", queryParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -457,10 +492,13 @@ func (q *QuarkPanService) getSharePassword(shareID string) (*PasswordResult, err
|
||||
"pr": "ucpro",
|
||||
"fr": "pc",
|
||||
"uc_param_str": "",
|
||||
"share_id": shareID,
|
||||
}
|
||||
|
||||
respData, err := q.HTTPGet("https://drive-pc.quark.cn/1/clouddrive/share/sharepage/password", queryParams)
|
||||
data := map[string]interface{}{
|
||||
"share_id": shareID,
|
||||
}
|
||||
|
||||
respData, err := q.HTTPPost("https://drive-pc.quark.cn/1/clouddrive/share/password", data, queryParams)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package db
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
"github.com/ctwj/urldb/utils"
|
||||
@@ -16,19 +17,16 @@ var DB *gorm.DB
|
||||
// InitDB 初始化数据库连接
|
||||
func InitDB() error {
|
||||
host := os.Getenv("DB_HOST")
|
||||
fmt.Printf("DB_HOST=%s\n", host)
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
}
|
||||
|
||||
port := os.Getenv("DB_PORT")
|
||||
fmt.Printf("DB_HOST=%s\n", port)
|
||||
if port == "" {
|
||||
port = "5432"
|
||||
}
|
||||
|
||||
user := os.Getenv("DB_USER")
|
||||
fmt.Printf("DB_HOST=%s\n", user)
|
||||
if user == "" {
|
||||
user = "postgres"
|
||||
}
|
||||
@@ -54,6 +52,17 @@ func InitDB() error {
|
||||
return err
|
||||
}
|
||||
|
||||
// 配置数据库连接池
|
||||
sqlDB, err := DB.DB()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 设置连接池参数
|
||||
sqlDB.SetMaxIdleConns(10) // 最大空闲连接数
|
||||
sqlDB.SetMaxOpenConns(100) // 最大打开连接数
|
||||
sqlDB.SetConnMaxLifetime(time.Hour) // 连接最大生命周期
|
||||
|
||||
// 自动迁移数据库表结构
|
||||
err = DB.AutoMigrate(
|
||||
&entity.User{},
|
||||
@@ -113,6 +122,11 @@ func createIndexes(db *gorm.DB) {
|
||||
db.Exec("CREATE INDEX IF NOT EXISTS idx_resources_is_valid ON resources(is_valid)")
|
||||
db.Exec("CREATE INDEX IF NOT EXISTS idx_resources_is_public ON resources(is_public)")
|
||||
|
||||
// 待处理资源表索引
|
||||
db.Exec("CREATE INDEX IF NOT EXISTS idx_ready_resource_key ON ready_resource(key)")
|
||||
db.Exec("CREATE INDEX IF NOT EXISTS idx_ready_resource_url ON ready_resource(url)")
|
||||
db.Exec("CREATE INDEX IF NOT EXISTS idx_ready_resource_create_time ON ready_resource(create_time DESC)")
|
||||
|
||||
// 搜索统计表索引
|
||||
db.Exec("CREATE INDEX IF NOT EXISTS idx_search_stats_query ON search_stats(query)")
|
||||
db.Exec("CREATE INDEX IF NOT EXISTS idx_search_stats_created_at ON search_stats(created_at DESC)")
|
||||
|
||||
@@ -13,7 +13,7 @@ func ToResourceResponse(resource *entity.Resource) dto.ResourceResponse {
|
||||
Description: resource.Description,
|
||||
URL: resource.URL,
|
||||
PanID: resource.PanID,
|
||||
QuarkURL: resource.QuarkURL,
|
||||
SaveURL: resource.SaveURL,
|
||||
FileSize: resource.FileSize,
|
||||
CategoryID: resource.CategoryID,
|
||||
ViewCount: resource.ViewCount,
|
||||
@@ -21,6 +21,9 @@ func ToResourceResponse(resource *entity.Resource) dto.ResourceResponse {
|
||||
IsPublic: resource.IsPublic,
|
||||
CreatedAt: resource.CreatedAt,
|
||||
UpdatedAt: resource.UpdatedAt,
|
||||
Cover: resource.Cover,
|
||||
Author: resource.Author,
|
||||
ErrorMsg: resource.ErrorMsg,
|
||||
}
|
||||
|
||||
// 设置分类名称
|
||||
@@ -167,16 +170,19 @@ func ToCksResponseList(cksList []entity.Cks) []dto.CksResponse {
|
||||
// ToReadyResourceResponse 将ReadyResource实体转换为ReadyResourceResponse
|
||||
func ToReadyResourceResponse(resource *entity.ReadyResource) dto.ReadyResourceResponse {
|
||||
return dto.ReadyResourceResponse{
|
||||
ID: resource.ID,
|
||||
Title: resource.Title,
|
||||
URL: resource.URL,
|
||||
Category: resource.Category,
|
||||
Tags: resource.Tags,
|
||||
Img: resource.Img,
|
||||
Source: resource.Source,
|
||||
Extra: resource.Extra,
|
||||
CreateTime: resource.CreateTime,
|
||||
IP: resource.IP,
|
||||
ID: resource.ID,
|
||||
Title: resource.Title,
|
||||
Description: resource.Description,
|
||||
URL: resource.URL,
|
||||
Category: resource.Category,
|
||||
Tags: resource.Tags,
|
||||
Img: resource.Img,
|
||||
Source: resource.Source,
|
||||
Extra: resource.Extra,
|
||||
Key: resource.Key,
|
||||
ErrorMsg: resource.ErrorMsg,
|
||||
CreateTime: resource.CreateTime,
|
||||
IP: resource.IP,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -190,19 +196,20 @@ func ToReadyResourceResponseList(resources []entity.ReadyResource) []dto.ReadyRe
|
||||
}
|
||||
|
||||
// RequestToReadyResource 将ReadyResourceRequest转换为ReadyResource实体
|
||||
func RequestToReadyResource(req *dto.ReadyResourceRequest) *entity.ReadyResource {
|
||||
if req == nil {
|
||||
return nil
|
||||
}
|
||||
// func RequestToReadyResource(req *dto.ReadyResourceRequest) *entity.ReadyResource {
|
||||
// if req == nil {
|
||||
// return nil
|
||||
// }
|
||||
|
||||
return &entity.ReadyResource{
|
||||
Title: &req.Title,
|
||||
Description: req.Description,
|
||||
URL: req.Url,
|
||||
Category: req.Category,
|
||||
Tags: req.Tags,
|
||||
Img: req.Img,
|
||||
Source: req.Source,
|
||||
Extra: req.Extra,
|
||||
}
|
||||
}
|
||||
// return &entity.ReadyResource{
|
||||
// Title: &req.Title,
|
||||
// Description: req.Description,
|
||||
// URL: req.Url,
|
||||
// Category: req.Category,
|
||||
// Tags: req.Tags,
|
||||
// Img: req.Img,
|
||||
// Source: req.Source,
|
||||
// Extra: req.Extra,
|
||||
// Key: req.Key,
|
||||
// }
|
||||
// }
|
||||
|
||||
@@ -1,74 +1,200 @@
|
||||
package converter
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/ctwj/urldb/db/dto"
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
)
|
||||
|
||||
// SystemConfigToResponse 将系统配置实体转换为响应DTO
|
||||
func SystemConfigToResponse(config *entity.SystemConfig) *dto.SystemConfigResponse {
|
||||
if config == nil {
|
||||
return nil
|
||||
// SystemConfigToResponse 将系统配置实体列表转换为响应DTO
|
||||
func SystemConfigToResponse(configs []entity.SystemConfig) *dto.SystemConfigResponse {
|
||||
if len(configs) == 0 {
|
||||
return getDefaultConfigResponse()
|
||||
}
|
||||
|
||||
return &dto.SystemConfigResponse{
|
||||
ID: config.ID,
|
||||
CreatedAt: config.CreatedAt.Format(time.RFC3339),
|
||||
UpdatedAt: config.UpdatedAt.Format(time.RFC3339),
|
||||
response := getDefaultConfigResponse()
|
||||
|
||||
// SEO 配置
|
||||
SiteTitle: config.SiteTitle,
|
||||
SiteDescription: config.SiteDescription,
|
||||
Keywords: config.Keywords,
|
||||
Author: config.Author,
|
||||
Copyright: config.Copyright,
|
||||
|
||||
// 自动处理配置组
|
||||
AutoProcessReadyResources: config.AutoProcessReadyResources,
|
||||
AutoProcessInterval: config.AutoProcessInterval,
|
||||
AutoTransferEnabled: config.AutoTransferEnabled,
|
||||
AutoTransferLimitDays: config.AutoTransferLimitDays,
|
||||
AutoTransferMinSpace: config.AutoTransferMinSpace,
|
||||
AutoFetchHotDramaEnabled: config.AutoFetchHotDramaEnabled,
|
||||
|
||||
// API配置
|
||||
ApiToken: config.ApiToken,
|
||||
|
||||
// 其他配置
|
||||
PageSize: config.PageSize,
|
||||
MaintenanceMode: config.MaintenanceMode,
|
||||
// 将键值对转换为结构体
|
||||
for _, config := range configs {
|
||||
switch config.Key {
|
||||
case entity.ConfigKeySiteTitle:
|
||||
response.SiteTitle = config.Value
|
||||
case entity.ConfigKeySiteDescription:
|
||||
response.SiteDescription = config.Value
|
||||
case entity.ConfigKeyKeywords:
|
||||
response.Keywords = config.Value
|
||||
case entity.ConfigKeyAuthor:
|
||||
response.Author = config.Value
|
||||
case entity.ConfigKeyCopyright:
|
||||
response.Copyright = config.Value
|
||||
case entity.ConfigKeyAutoProcessReadyResources:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response.AutoProcessReadyResources = val
|
||||
}
|
||||
case entity.ConfigKeyAutoProcessInterval:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response.AutoProcessInterval = val
|
||||
}
|
||||
case entity.ConfigKeyAutoTransferEnabled:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response.AutoTransferEnabled = val
|
||||
}
|
||||
case entity.ConfigKeyAutoTransferLimitDays:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response.AutoTransferLimitDays = val
|
||||
}
|
||||
case entity.ConfigKeyAutoTransferMinSpace:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response.AutoTransferMinSpace = val
|
||||
}
|
||||
case entity.ConfigKeyAutoFetchHotDramaEnabled:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response.AutoFetchHotDramaEnabled = val
|
||||
}
|
||||
case entity.ConfigKeyApiToken:
|
||||
response.ApiToken = config.Value
|
||||
case entity.ConfigKeyPageSize:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response.PageSize = val
|
||||
}
|
||||
case entity.ConfigKeyMaintenanceMode:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response.MaintenanceMode = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置时间戳(使用第一个配置的时间)
|
||||
if len(configs) > 0 {
|
||||
response.CreatedAt = configs[0].CreatedAt.Format(time.RFC3339)
|
||||
response.UpdatedAt = configs[0].UpdatedAt.Format(time.RFC3339)
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
// RequestToSystemConfig 将请求DTO转换为系统配置实体
|
||||
func RequestToSystemConfig(req *dto.SystemConfigRequest) *entity.SystemConfig {
|
||||
// RequestToSystemConfig 将请求DTO转换为系统配置实体列表
|
||||
func RequestToSystemConfig(req *dto.SystemConfigRequest) []entity.SystemConfig {
|
||||
if req == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &entity.SystemConfig{
|
||||
// SEO 配置
|
||||
SiteTitle: req.SiteTitle,
|
||||
SiteDescription: req.SiteDescription,
|
||||
Keywords: req.Keywords,
|
||||
Author: req.Author,
|
||||
Copyright: req.Copyright,
|
||||
configs := []entity.SystemConfig{
|
||||
{Key: entity.ConfigKeySiteTitle, Value: req.SiteTitle, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeySiteDescription, Value: req.SiteDescription, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyKeywords, Value: req.Keywords, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyAuthor, Value: req.Author, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyCopyright, Value: req.Copyright, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyAutoProcessReadyResources, Value: strconv.FormatBool(req.AutoProcessReadyResources), Type: entity.ConfigTypeBool},
|
||||
{Key: entity.ConfigKeyAutoProcessInterval, Value: strconv.Itoa(req.AutoProcessInterval), Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyAutoTransferEnabled, Value: strconv.FormatBool(req.AutoTransferEnabled), Type: entity.ConfigTypeBool},
|
||||
{Key: entity.ConfigKeyAutoTransferLimitDays, Value: strconv.Itoa(req.AutoTransferLimitDays), Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyAutoTransferMinSpace, Value: strconv.Itoa(req.AutoTransferMinSpace), Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyAutoFetchHotDramaEnabled, Value: strconv.FormatBool(req.AutoFetchHotDramaEnabled), Type: entity.ConfigTypeBool},
|
||||
{Key: entity.ConfigKeyApiToken, Value: req.ApiToken, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyPageSize, Value: strconv.Itoa(req.PageSize), Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyMaintenanceMode, Value: strconv.FormatBool(req.MaintenanceMode), Type: entity.ConfigTypeBool},
|
||||
}
|
||||
|
||||
// 自动处理配置组
|
||||
AutoProcessReadyResources: req.AutoProcessReadyResources,
|
||||
AutoProcessInterval: req.AutoProcessInterval,
|
||||
AutoTransferEnabled: req.AutoTransferEnabled,
|
||||
AutoTransferLimitDays: req.AutoTransferLimitDays,
|
||||
AutoTransferMinSpace: req.AutoTransferMinSpace,
|
||||
AutoFetchHotDramaEnabled: req.AutoFetchHotDramaEnabled,
|
||||
return configs
|
||||
}
|
||||
|
||||
// API配置
|
||||
ApiToken: req.ApiToken,
|
||||
// SystemConfigToPublicResponse 返回不含 api_token 的系统配置响应
|
||||
func SystemConfigToPublicResponse(configs []entity.SystemConfig) map[string]interface{} {
|
||||
response := map[string]interface{}{
|
||||
entity.ConfigResponseFieldID: 0,
|
||||
entity.ConfigResponseFieldCreatedAt: time.Now().Format("2006-01-02 15:04:05"),
|
||||
entity.ConfigResponseFieldUpdatedAt: time.Now().Format("2006-01-02 15:04:05"),
|
||||
entity.ConfigResponseFieldSiteTitle: entity.ConfigDefaultSiteTitle,
|
||||
entity.ConfigResponseFieldSiteDescription: entity.ConfigDefaultSiteDescription,
|
||||
entity.ConfigResponseFieldKeywords: entity.ConfigDefaultKeywords,
|
||||
entity.ConfigResponseFieldAuthor: entity.ConfigDefaultAuthor,
|
||||
entity.ConfigResponseFieldCopyright: entity.ConfigDefaultCopyright,
|
||||
entity.ConfigResponseFieldAutoProcessReadyResources: false,
|
||||
entity.ConfigResponseFieldAutoProcessInterval: 30,
|
||||
entity.ConfigResponseFieldAutoTransferEnabled: false,
|
||||
entity.ConfigResponseFieldAutoTransferLimitDays: 0,
|
||||
entity.ConfigResponseFieldAutoTransferMinSpace: 100,
|
||||
entity.ConfigResponseFieldAutoFetchHotDramaEnabled: false,
|
||||
entity.ConfigResponseFieldPageSize: 100,
|
||||
entity.ConfigResponseFieldMaintenanceMode: false,
|
||||
}
|
||||
|
||||
// 其他配置
|
||||
PageSize: req.PageSize,
|
||||
MaintenanceMode: req.MaintenanceMode,
|
||||
// 将键值对转换为map
|
||||
for _, config := range configs {
|
||||
switch config.Key {
|
||||
case entity.ConfigKeySiteTitle:
|
||||
response[entity.ConfigResponseFieldSiteTitle] = config.Value
|
||||
case entity.ConfigKeySiteDescription:
|
||||
response[entity.ConfigResponseFieldSiteDescription] = config.Value
|
||||
case entity.ConfigKeyKeywords:
|
||||
response[entity.ConfigResponseFieldKeywords] = config.Value
|
||||
case entity.ConfigKeyAuthor:
|
||||
response[entity.ConfigResponseFieldAuthor] = config.Value
|
||||
case entity.ConfigKeyCopyright:
|
||||
response[entity.ConfigResponseFieldCopyright] = config.Value
|
||||
case entity.ConfigKeyAutoProcessReadyResources:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldAutoProcessReadyResources] = val
|
||||
}
|
||||
case entity.ConfigKeyAutoProcessInterval:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldAutoProcessInterval] = val
|
||||
}
|
||||
case entity.ConfigKeyAutoTransferEnabled:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldAutoTransferEnabled] = val
|
||||
}
|
||||
case entity.ConfigKeyAutoTransferLimitDays:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldAutoTransferLimitDays] = val
|
||||
}
|
||||
case entity.ConfigKeyAutoTransferMinSpace:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldAutoTransferMinSpace] = val
|
||||
}
|
||||
case entity.ConfigKeyAutoFetchHotDramaEnabled:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldAutoFetchHotDramaEnabled] = val
|
||||
}
|
||||
case entity.ConfigKeyPageSize:
|
||||
if val, err := strconv.Atoi(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldPageSize] = val
|
||||
}
|
||||
case entity.ConfigKeyMaintenanceMode:
|
||||
if val, err := strconv.ParseBool(config.Value); err == nil {
|
||||
response[entity.ConfigResponseFieldMaintenanceMode] = val
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 设置时间戳(使用第一个配置的时间)
|
||||
if len(configs) > 0 {
|
||||
response[entity.ConfigResponseFieldCreatedAt] = configs[0].CreatedAt.Format("2006-01-02 15:04:05")
|
||||
response[entity.ConfigResponseFieldUpdatedAt] = configs[0].UpdatedAt.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
// getDefaultConfigResponse 获取默认配置响应
|
||||
func getDefaultConfigResponse() *dto.SystemConfigResponse {
|
||||
return &dto.SystemConfigResponse{
|
||||
SiteTitle: entity.ConfigDefaultSiteTitle,
|
||||
SiteDescription: entity.ConfigDefaultSiteDescription,
|
||||
Keywords: entity.ConfigDefaultKeywords,
|
||||
Author: entity.ConfigDefaultAuthor,
|
||||
Copyright: entity.ConfigDefaultCopyright,
|
||||
AutoProcessReadyResources: false,
|
||||
AutoProcessInterval: 30,
|
||||
AutoTransferEnabled: false,
|
||||
AutoTransferLimitDays: 0,
|
||||
AutoTransferMinSpace: 100,
|
||||
AutoFetchHotDramaEnabled: false,
|
||||
ApiToken: entity.ConfigDefaultApiToken,
|
||||
PageSize: 100,
|
||||
MaintenanceMode: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,15 @@ package dto
|
||||
|
||||
// ReadyResourceRequest 待处理资源请求
|
||||
type ReadyResourceRequest struct {
|
||||
Title string `json:"title" validate:"required" example:"示例资源标题"`
|
||||
Description string `json:"description" example:"这是一个示例资源描述"`
|
||||
Url string `json:"url" validate:"required" example:"https://example.com/resource"`
|
||||
Category string `json:"category" example:"示例分类"`
|
||||
Tags string `json:"tags" example:"标签1,标签2"`
|
||||
Img string `json:"img" example:"https://example.com/image.jpg"`
|
||||
Source string `json:"source" example:"数据来源"`
|
||||
Extra string `json:"extra" example:"额外信息"`
|
||||
Title string `json:"title" validate:"required" example:"示例资源标题"`
|
||||
Description string `json:"description" example:"这是一个示例资源描述"`
|
||||
Url []string `json:"url" validate:"required" example:"https://example.com/resource"`
|
||||
Category string `json:"category" example:"示例分类"`
|
||||
Tags string `json:"tags" example:"标签1,标签2"`
|
||||
Img string `json:"img" example:"https://example.com/image.jpg"`
|
||||
Source string `json:"source" example:"数据来源"`
|
||||
Extra string `json:"extra" example:"额外信息"`
|
||||
ErrorMsg string `json:"error_msg" example:"错误信息"`
|
||||
}
|
||||
|
||||
// BatchReadyResourceRequest 批量待处理资源请求
|
||||
|
||||
@@ -52,12 +52,15 @@ type CreateResourceRequest struct {
|
||||
Description string `json:"description"`
|
||||
URL string `json:"url"`
|
||||
PanID *uint `json:"pan_id"`
|
||||
QuarkURL string `json:"quark_url"`
|
||||
SaveURL string `json:"save_url"`
|
||||
FileSize string `json:"file_size"`
|
||||
CategoryID *uint `json:"category_id"`
|
||||
IsValid bool `json:"is_valid"`
|
||||
IsPublic bool `json:"is_public"`
|
||||
TagIDs []uint `json:"tag_ids"`
|
||||
Cover string `json:"cover"`
|
||||
Author string `json:"author"`
|
||||
ErrorMsg string `json:"error_msg"`
|
||||
}
|
||||
|
||||
// UpdateResourceRequest 更新资源请求
|
||||
@@ -66,12 +69,15 @@ type UpdateResourceRequest struct {
|
||||
Description string `json:"description"`
|
||||
URL string `json:"url"`
|
||||
PanID *uint `json:"pan_id"`
|
||||
QuarkURL string `json:"quark_url"`
|
||||
SaveURL string `json:"save_url"`
|
||||
FileSize string `json:"file_size"`
|
||||
CategoryID *uint `json:"category_id"`
|
||||
IsValid bool `json:"is_valid"`
|
||||
IsPublic bool `json:"is_public"`
|
||||
TagIDs []uint `json:"tag_ids"`
|
||||
Cover string `json:"cover"`
|
||||
Author string `json:"author"`
|
||||
ErrorMsg string `json:"error_msg"`
|
||||
}
|
||||
|
||||
// CreateCategoryRequest 创建分类请求
|
||||
@@ -102,15 +108,16 @@ type UpdateTagRequest struct {
|
||||
|
||||
// CreateReadyResourceRequest 创建待处理资源请求
|
||||
type CreateReadyResourceRequest struct {
|
||||
Title *string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
URL string `json:"url" binding:"required"`
|
||||
Category string `json:"category"`
|
||||
Tags string `json:"tags"`
|
||||
Img string `json:"img"`
|
||||
Source string `json:"source"`
|
||||
Extra string `json:"extra"`
|
||||
IP *string `json:"ip"`
|
||||
Title *string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
URL []string `json:"url" binding:"required"`
|
||||
Category string `json:"category"`
|
||||
Tags string `json:"tags"`
|
||||
Img string `json:"img"`
|
||||
Source string `json:"source"`
|
||||
Extra string `json:"extra"`
|
||||
IP *string `json:"ip"`
|
||||
Key string `json:"key"`
|
||||
}
|
||||
|
||||
// BatchCreateReadyResourceRequest 批量创建待处理资源请求
|
||||
|
||||
@@ -17,7 +17,7 @@ type ResourceResponse struct {
|
||||
Description string `json:"description"`
|
||||
URL string `json:"url"`
|
||||
PanID *uint `json:"pan_id"`
|
||||
QuarkURL string `json:"quark_url"`
|
||||
SaveURL string `json:"save_url"`
|
||||
FileSize string `json:"file_size"`
|
||||
CategoryID *uint `json:"category_id"`
|
||||
CategoryName string `json:"category_name"`
|
||||
@@ -27,6 +27,9 @@ type ResourceResponse struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
Tags []TagResponse `json:"tags"`
|
||||
Cover string `json:"cover"`
|
||||
Author string `json:"author"`
|
||||
ErrorMsg string `json:"error_msg"`
|
||||
}
|
||||
|
||||
// CategoryResponse 分类响应
|
||||
@@ -85,6 +88,8 @@ type ReadyResourceResponse struct {
|
||||
Img string `json:"img"`
|
||||
Source string `json:"source"`
|
||||
Extra string `json:"extra"`
|
||||
Key string `json:"key"`
|
||||
ErrorMsg string `json:"error_msg"`
|
||||
CreateTime time.Time `json:"create_time"`
|
||||
IP *string `json:"ip"`
|
||||
}
|
||||
|
||||
@@ -53,3 +53,15 @@ type SystemConfigResponse struct {
|
||||
PageSize int `json:"page_size"`
|
||||
MaintenanceMode bool `json:"maintenance_mode"`
|
||||
}
|
||||
|
||||
// SystemConfigItem 单个配置项
|
||||
type SystemConfigItem struct {
|
||||
Key string `json:"key"`
|
||||
Value string `json:"value"`
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// SystemConfigListResponse 配置列表响应
|
||||
type SystemConfigListResponse struct {
|
||||
Configs []SystemConfigItem `json:"configs"`
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ type ReadyResource struct {
|
||||
Img string `json:"img" gorm:"size:500;comment:封面链接"`
|
||||
Source string `json:"source" gorm:"size:100;comment:数据来源"`
|
||||
Extra string `json:"extra" gorm:"type:text;comment:额外附加数据"`
|
||||
Key string `json:"key" gorm:"size:64;index;comment:资源组标识,相同key表示同一组资源"`
|
||||
ErrorMsg string `json:"error_msg" gorm:"type:text;comment:处理失败时的错误信息"`
|
||||
CreateTime time.Time `json:"create_time" gorm:"default:CURRENT_TIMESTAMP"`
|
||||
IP *string `json:"ip" gorm:"size:45;comment:IP地址"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
@@ -13,7 +13,7 @@ type Resource struct {
|
||||
Description string `json:"description" gorm:"type:text;comment:资源描述"`
|
||||
URL string `json:"url" gorm:"size:128;comment:资源链接"`
|
||||
PanID *uint `json:"pan_id" gorm:"comment:平台ID"`
|
||||
QuarkURL string `json:"quark_url" gorm:"size:500;comment:夸克链接"`
|
||||
SaveURL string `json:"save_url" gorm:"size:500;comment:转存后的链接"`
|
||||
FileSize string `json:"file_size" gorm:"size:100;comment:文件大小"`
|
||||
CategoryID *uint `json:"category_id" gorm:"comment:分类ID"`
|
||||
ViewCount int `json:"view_count" gorm:"default:0;comment:浏览次数"`
|
||||
@@ -22,6 +22,12 @@ type Resource struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index"`
|
||||
Cover string `json:"cover" gorm:"size:500;comment:封面"`
|
||||
Author string `json:"author" gorm:"size:100;comment:作者"`
|
||||
ErrorMsg string `json:"error_msg" gorm:"size:255;comment:转存失败原因"`
|
||||
CkID *uint `json:"ck_id" gorm:"comment:账号ID"`
|
||||
Fid string `json:"fid" gorm:"size:128;comment:网盘文件ID"`
|
||||
Key string `json:"key" gorm:"size:64;index;comment:资源组标识,相同key表示同一组资源"`
|
||||
|
||||
// 关联关系
|
||||
Category Category `json:"category" gorm:"foreignKey:CategoryID"`
|
||||
|
||||
@@ -4,33 +4,16 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// SystemConfig 系统配置实体
|
||||
// SystemConfig 系统配置实体(键值对形式)
|
||||
type SystemConfig struct {
|
||||
ID uint `json:"id" gorm:"primaryKey"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// SEO 配置
|
||||
SiteTitle string `json:"site_title" gorm:"size:200;not null;default:'网盘资源数据库'"`
|
||||
SiteDescription string `json:"site_description" gorm:"size:500"`
|
||||
Keywords string `json:"keywords" gorm:"size:500"`
|
||||
Author string `json:"author" gorm:"size:100"`
|
||||
Copyright string `json:"copyright" gorm:"size:200"`
|
||||
|
||||
// 自动处理配置组
|
||||
AutoProcessReadyResources bool `json:"auto_process_ready_resources" gorm:"default:false"` // 自动处理待处理资源
|
||||
AutoProcessInterval int `json:"auto_process_interval" gorm:"default:30"` // 自动处理间隔(分钟)
|
||||
AutoTransferEnabled bool `json:"auto_transfer_enabled" gorm:"default:false"` // 开启自动转存
|
||||
AutoTransferLimitDays int `json:"auto_transfer_limit_days" gorm:"default:0"` // 自动转存限制天数(0表示不限制)
|
||||
AutoTransferMinSpace int `json:"auto_transfer_min_space" gorm:"default:100"` // 最小存储空间(GB)
|
||||
AutoFetchHotDramaEnabled bool `json:"auto_fetch_hot_drama_enabled" gorm:"default:false"` // 自动拉取热播剧名字
|
||||
|
||||
// API配置
|
||||
ApiToken string `json:"api_token" gorm:"size:100;uniqueIndex"` // 公开API访问令牌
|
||||
|
||||
// 其他配置
|
||||
PageSize int `json:"page_size" gorm:"default:100"`
|
||||
MaintenanceMode bool `json:"maintenance_mode" gorm:"default:false"`
|
||||
// 键值对配置
|
||||
Key string `json:"key" gorm:"size:100;not null;uniqueIndex"`
|
||||
Value string `json:"value" gorm:"size:1000"`
|
||||
Type string `json:"type" gorm:"size:20;default:'string'"` // string, int, bool, json
|
||||
}
|
||||
|
||||
// TableName 指定表名
|
||||
|
||||
89
db/entity/system_config_constants.go
Normal file
89
db/entity/system_config_constants.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package entity
|
||||
|
||||
// ConfigKey 配置键常量
|
||||
const (
|
||||
// SEO 配置
|
||||
ConfigKeySiteTitle = "site_title"
|
||||
ConfigKeySiteDescription = "site_description"
|
||||
ConfigKeyKeywords = "keywords"
|
||||
ConfigKeyAuthor = "author"
|
||||
ConfigKeyCopyright = "copyright"
|
||||
|
||||
// 自动处理配置组
|
||||
ConfigKeyAutoProcessReadyResources = "auto_process_ready_resources"
|
||||
ConfigKeyAutoProcessInterval = "auto_process_interval"
|
||||
ConfigKeyAutoTransferEnabled = "auto_transfer_enabled"
|
||||
ConfigKeyAutoTransferLimitDays = "auto_transfer_limit_days"
|
||||
ConfigKeyAutoTransferMinSpace = "auto_transfer_min_space"
|
||||
ConfigKeyAutoFetchHotDramaEnabled = "auto_fetch_hot_drama_enabled"
|
||||
|
||||
// API配置
|
||||
ConfigKeyApiToken = "api_token"
|
||||
|
||||
// 其他配置
|
||||
ConfigKeyPageSize = "page_size"
|
||||
ConfigKeyMaintenanceMode = "maintenance_mode"
|
||||
)
|
||||
|
||||
// ConfigType 配置类型常量
|
||||
const (
|
||||
ConfigTypeString = "string"
|
||||
ConfigTypeInt = "int"
|
||||
ConfigTypeBool = "bool"
|
||||
ConfigTypeJSON = "json"
|
||||
)
|
||||
|
||||
// ConfigResponseField API响应字段名常量
|
||||
const (
|
||||
// 基础字段
|
||||
ConfigResponseFieldID = "id"
|
||||
ConfigResponseFieldCreatedAt = "created_at"
|
||||
ConfigResponseFieldUpdatedAt = "updated_at"
|
||||
|
||||
// SEO 配置字段
|
||||
ConfigResponseFieldSiteTitle = "site_title"
|
||||
ConfigResponseFieldSiteDescription = "site_description"
|
||||
ConfigResponseFieldKeywords = "keywords"
|
||||
ConfigResponseFieldAuthor = "author"
|
||||
ConfigResponseFieldCopyright = "copyright"
|
||||
|
||||
// 自动处理配置字段
|
||||
ConfigResponseFieldAutoProcessReadyResources = "auto_process_ready_resources"
|
||||
ConfigResponseFieldAutoProcessInterval = "auto_process_interval"
|
||||
ConfigResponseFieldAutoTransferEnabled = "auto_transfer_enabled"
|
||||
ConfigResponseFieldAutoTransferLimitDays = "auto_transfer_limit_days"
|
||||
ConfigResponseFieldAutoTransferMinSpace = "auto_transfer_min_space"
|
||||
ConfigResponseFieldAutoFetchHotDramaEnabled = "auto_fetch_hot_drama_enabled"
|
||||
|
||||
// API配置字段
|
||||
ConfigResponseFieldApiToken = "api_token"
|
||||
|
||||
// 其他配置字段
|
||||
ConfigResponseFieldPageSize = "page_size"
|
||||
ConfigResponseFieldMaintenanceMode = "maintenance_mode"
|
||||
)
|
||||
|
||||
// ConfigDefaultValue 配置默认值常量
|
||||
const (
|
||||
// SEO 配置默认值
|
||||
ConfigDefaultSiteTitle = "老九网盘资源数据库"
|
||||
ConfigDefaultSiteDescription = "专业的老九网盘资源数据库"
|
||||
ConfigDefaultKeywords = "网盘,资源管理,文件分享"
|
||||
ConfigDefaultAuthor = "系统管理员"
|
||||
ConfigDefaultCopyright = "© 2024 老九网盘资源数据库"
|
||||
|
||||
// 自动处理配置默认值
|
||||
ConfigDefaultAutoProcessReadyResources = "false"
|
||||
ConfigDefaultAutoProcessInterval = "30"
|
||||
ConfigDefaultAutoTransferEnabled = "false"
|
||||
ConfigDefaultAutoTransferLimitDays = "0"
|
||||
ConfigDefaultAutoTransferMinSpace = "100"
|
||||
ConfigDefaultAutoFetchHotDramaEnabled = "false"
|
||||
|
||||
// API配置默认值
|
||||
ConfigDefaultApiToken = ""
|
||||
|
||||
// 其他配置默认值
|
||||
ConfigDefaultPageSize = "100"
|
||||
ConfigDefaultMaintenanceMode = "false"
|
||||
)
|
||||
@@ -73,3 +73,7 @@ func (r *BaseRepositoryImpl[T]) FindWithPagination(page, limit int) ([]T, int64,
|
||||
err := r.db.Offset(offset).Limit(limit).Find(&entities).Error
|
||||
return entities, total, err
|
||||
}
|
||||
|
||||
func (r *BaseRepositoryImpl[T]) GetDB() *gorm.DB {
|
||||
return r.db
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ type CksRepository interface {
|
||||
FindByIsValid(isValid bool) ([]entity.Cks, error)
|
||||
UpdateSpace(id uint, space, leftSpace int64) error
|
||||
DeleteByPanID(panID uint) error
|
||||
UpdateWithAllFields(cks *entity.Cks) error
|
||||
}
|
||||
|
||||
// CksRepositoryImpl Cks的Repository实现
|
||||
@@ -71,3 +72,8 @@ func (r *CksRepositoryImpl) FindByID(id uint) (*entity.Cks, error) {
|
||||
}
|
||||
return &cks, nil
|
||||
}
|
||||
|
||||
// UpdateWithAllFields 更新Cks,包括零值字段
|
||||
func (r *CksRepositoryImpl) UpdateWithAllFields(cks *entity.Cks) error {
|
||||
return r.db.Save(cks).Error
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
|
||||
gonanoid "github.com/matoous/go-nanoid/v2"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -13,9 +14,16 @@ type ReadyResourceRepository interface {
|
||||
BaseRepository[entity.ReadyResource]
|
||||
FindByURL(url string) (*entity.ReadyResource, error)
|
||||
FindByIP(ip string) ([]entity.ReadyResource, error)
|
||||
FindByKey(key string) ([]entity.ReadyResource, error)
|
||||
BatchCreate(resources []entity.ReadyResource) error
|
||||
DeleteByURL(url string) error
|
||||
DeleteByKey(key string) error
|
||||
FindAllWithinDays(days int) ([]entity.ReadyResource, error)
|
||||
BatchFindByURLs(urls []string) ([]entity.ReadyResource, error)
|
||||
GenerateUniqueKey() (string, error)
|
||||
FindWithErrors() ([]entity.ReadyResource, error)
|
||||
FindWithoutErrors() ([]entity.ReadyResource, error)
|
||||
ClearErrorMsg(id uint) error
|
||||
}
|
||||
|
||||
// ReadyResourceRepositoryImpl ReadyResource的Repository实现
|
||||
@@ -68,3 +76,62 @@ func (r *ReadyResourceRepositoryImpl) FindAllWithinDays(days int) ([]entity.Read
|
||||
err := db.Find(&resources).Error
|
||||
return resources, err
|
||||
}
|
||||
|
||||
func (r *ReadyResourceRepositoryImpl) BatchFindByURLs(urls []string) ([]entity.ReadyResource, error) {
|
||||
var resources []entity.ReadyResource
|
||||
if len(urls) == 0 {
|
||||
return resources, nil
|
||||
}
|
||||
err := r.db.Where("url IN ?", urls).Find(&resources).Error
|
||||
return resources, err
|
||||
}
|
||||
|
||||
// FindByKey 根据Key查找
|
||||
func (r *ReadyResourceRepositoryImpl) FindByKey(key string) ([]entity.ReadyResource, error) {
|
||||
var resources []entity.ReadyResource
|
||||
err := r.db.Where("key = ?", key).Find(&resources).Error
|
||||
return resources, err
|
||||
}
|
||||
|
||||
// DeleteByKey 根据Key删除
|
||||
func (r *ReadyResourceRepositoryImpl) DeleteByKey(key string) error {
|
||||
return r.db.Where("key = ?", key).Delete(&entity.ReadyResource{}).Error
|
||||
}
|
||||
|
||||
// GenerateUniqueKey 生成唯一的6位Base62 key
|
||||
func (r *ReadyResourceRepositoryImpl) GenerateUniqueKey() (string, error) {
|
||||
for i := 0; i < 20; i++ {
|
||||
key, err := gonanoid.Generate("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", 6)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var count int64
|
||||
err = r.db.Model(&entity.ReadyResource{}).Where("key = ?", key).Count(&count).Error
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if count == 0 {
|
||||
return key, nil
|
||||
}
|
||||
}
|
||||
return "", gorm.ErrInvalidData
|
||||
}
|
||||
|
||||
// FindWithErrors 查找有错误信息的资源
|
||||
func (r *ReadyResourceRepositoryImpl) FindWithErrors() ([]entity.ReadyResource, error) {
|
||||
var resources []entity.ReadyResource
|
||||
err := r.db.Where("error_msg != '' AND error_msg IS NOT NULL").Find(&resources).Error
|
||||
return resources, err
|
||||
}
|
||||
|
||||
// FindWithoutErrors 查找没有错误信息的资源
|
||||
func (r *ReadyResourceRepositoryImpl) FindWithoutErrors() ([]entity.ReadyResource, error) {
|
||||
var resources []entity.ReadyResource
|
||||
err := r.db.Where("error_msg = '' OR error_msg IS NULL").Find(&resources).Error
|
||||
return resources, err
|
||||
}
|
||||
|
||||
// ClearErrorMsg 清除指定资源的错误信息
|
||||
func (r *ReadyResourceRepositoryImpl) ClearErrorMsg(id uint) error {
|
||||
return r.db.Model(&entity.ReadyResource{}).Where("id = ?", id).Update("error_msg", "").Error
|
||||
}
|
||||
|
||||
@@ -31,6 +31,9 @@ type ResourceRepository interface {
|
||||
GetCachedLatestResources(limit int) ([]entity.Resource, error)
|
||||
InvalidateCache() error
|
||||
FindExists(url string, excludeID ...uint) (bool, error)
|
||||
BatchFindByURLs(urls []string) ([]entity.Resource, error)
|
||||
GetResourcesForTransfer(panID uint, sinceTime time.Time) ([]*entity.Resource, error)
|
||||
CreateResourceTag(resourceID, tagID uint) error
|
||||
}
|
||||
|
||||
// ResourceRepositoryImpl Resource的Repository实现
|
||||
@@ -331,7 +334,7 @@ func (r *ResourceRepositoryImpl) InvalidateCache() error {
|
||||
// FindExists 检查是否存在相同URL的资源
|
||||
func (r *ResourceRepositoryImpl) FindExists(url string, excludeID ...uint) (bool, error) {
|
||||
var count int64
|
||||
query := r.db.Model(&entity.Resource{}).Where("url = ?", url)
|
||||
query := r.db.Model(&entity.Resource{}).Where("url = ? OR save_url = ?", url, url)
|
||||
|
||||
// 如果有排除ID,则排除该记录(用于更新时排除自己)
|
||||
if len(excludeID) > 0 {
|
||||
@@ -344,3 +347,35 @@ func (r *ResourceRepositoryImpl) FindExists(url string, excludeID ...uint) (bool
|
||||
}
|
||||
return count > 0, nil
|
||||
}
|
||||
|
||||
func (r *ResourceRepositoryImpl) BatchFindByURLs(urls []string) ([]entity.Resource, error) {
|
||||
var resources []entity.Resource
|
||||
if len(urls) == 0 {
|
||||
return resources, nil
|
||||
}
|
||||
err := r.db.Where("url IN ?", urls).Find(&resources).Error
|
||||
return resources, err
|
||||
}
|
||||
|
||||
// GetResourcesForTransfer 获取需要转存的资源
|
||||
func (r *ResourceRepositoryImpl) GetResourcesForTransfer(panID uint, sinceTime time.Time) ([]*entity.Resource, error) {
|
||||
var resources []*entity.Resource
|
||||
query := r.db.Where("pan_id = ? AND (save_url = '' OR save_url IS NULL) AND (error_msg = '' OR error_msg IS NULL)", panID)
|
||||
if !sinceTime.IsZero() {
|
||||
query = query.Where("created_at >= ?", sinceTime)
|
||||
}
|
||||
err := query.Order("created_at DESC").Find(&resources).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resources, nil
|
||||
}
|
||||
|
||||
// CreateResourceTag 创建资源与标签的关联
|
||||
func (r *ResourceRepositoryImpl) CreateResourceTag(resourceID, tagID uint) error {
|
||||
resourceTag := &entity.ResourceTag{
|
||||
ResourceID: resourceID,
|
||||
TagID: tagID,
|
||||
}
|
||||
return r.GetDB().Create(resourceTag).Error
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
@@ -16,6 +17,7 @@ type SearchStatRepository interface {
|
||||
GetHotKeywords(days int, limit int) ([]entity.KeywordStat, error)
|
||||
GetSearchTrend(days int) ([]entity.DailySearchStat, error)
|
||||
GetKeywordTrend(keyword string, days int) ([]entity.DailySearchStat, error)
|
||||
GetSummary() (map[string]int64, error)
|
||||
}
|
||||
|
||||
// SearchStatRepositoryImpl 搜索统计Repository实现
|
||||
@@ -30,51 +32,34 @@ func NewSearchStatRepository(db *gorm.DB) SearchStatRepository {
|
||||
}
|
||||
}
|
||||
|
||||
// RecordSearch 记录搜索
|
||||
// RecordSearch 记录搜索(每次都插入新记录)
|
||||
func (r *SearchStatRepositoryImpl) RecordSearch(keyword, ip, userAgent string) error {
|
||||
today := time.Now().Truncate(24 * time.Hour)
|
||||
|
||||
// 查找今天是否已有该关键词的记录
|
||||
var stat entity.SearchStat
|
||||
err := r.db.Where("keyword = ? AND date = ?", keyword, today).First(&stat).Error
|
||||
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
// 创建新记录
|
||||
stat = entity.SearchStat{
|
||||
Keyword: keyword,
|
||||
Count: 1,
|
||||
Date: today,
|
||||
IP: ip,
|
||||
UserAgent: userAgent,
|
||||
}
|
||||
return r.db.Create(&stat).Error
|
||||
} else if err != nil {
|
||||
return err
|
||||
stat := entity.SearchStat{
|
||||
Keyword: keyword,
|
||||
Count: 1,
|
||||
Date: time.Now(), // 可保留 date 字段,实际用 created_at 统计
|
||||
IP: ip,
|
||||
UserAgent: userAgent,
|
||||
}
|
||||
|
||||
// 更新现有记录
|
||||
stat.Count++
|
||||
stat.IP = ip
|
||||
stat.UserAgent = userAgent
|
||||
return r.db.Save(&stat).Error
|
||||
return r.db.Create(&stat).Error
|
||||
}
|
||||
|
||||
// GetDailyStats 获取每日统计
|
||||
func (r *SearchStatRepositoryImpl) GetDailyStats(days int) ([]entity.DailySearchStat, error) {
|
||||
var stats []entity.DailySearchStat
|
||||
|
||||
query := `
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
date,
|
||||
SUM(count) as total_searches,
|
||||
COUNT(DISTINCT keyword) as unique_keywords
|
||||
FROM search_stats
|
||||
WHERE date >= CURRENT_DATE - INTERVAL '? days'
|
||||
WHERE date >= CURRENT_DATE - INTERVAL '%d days'
|
||||
GROUP BY date
|
||||
ORDER BY date DESC
|
||||
`
|
||||
`, days)
|
||||
|
||||
err := r.db.Raw(query, days).Scan(&stats).Error
|
||||
err := r.db.Raw(query).Scan(&stats).Error
|
||||
return stats, err
|
||||
}
|
||||
|
||||
@@ -82,19 +67,19 @@ func (r *SearchStatRepositoryImpl) GetDailyStats(days int) ([]entity.DailySearch
|
||||
func (r *SearchStatRepositoryImpl) GetHotKeywords(days int, limit int) ([]entity.KeywordStat, error) {
|
||||
var keywords []entity.KeywordStat
|
||||
|
||||
query := `
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
keyword,
|
||||
SUM(count) as count,
|
||||
RANK() OVER (ORDER BY SUM(count) DESC) as rank
|
||||
FROM search_stats
|
||||
WHERE date >= CURRENT_DATE - INTERVAL '? days'
|
||||
WHERE date >= CURRENT_DATE - INTERVAL '%d days'
|
||||
GROUP BY keyword
|
||||
ORDER BY count DESC
|
||||
LIMIT ?
|
||||
`
|
||||
`, days)
|
||||
|
||||
err := r.db.Raw(query, days, limit).Scan(&keywords).Error
|
||||
err := r.db.Raw(query, limit).Scan(&keywords).Error
|
||||
return keywords, err
|
||||
}
|
||||
|
||||
@@ -102,18 +87,18 @@ func (r *SearchStatRepositoryImpl) GetHotKeywords(days int, limit int) ([]entity
|
||||
func (r *SearchStatRepositoryImpl) GetSearchTrend(days int) ([]entity.DailySearchStat, error) {
|
||||
var stats []entity.DailySearchStat
|
||||
|
||||
query := `
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
date,
|
||||
SUM(count) as total_searches,
|
||||
COUNT(DISTINCT keyword) as unique_keywords
|
||||
FROM search_stats
|
||||
WHERE date >= CURRENT_DATE - INTERVAL '? days'
|
||||
WHERE date >= CURRENT_DATE - INTERVAL '%d days'
|
||||
GROUP BY date
|
||||
ORDER BY date ASC
|
||||
`
|
||||
`, days)
|
||||
|
||||
err := r.db.Raw(query, days).Scan(&stats).Error
|
||||
err := r.db.Raw(query).Scan(&stats).Error
|
||||
return stats, err
|
||||
}
|
||||
|
||||
@@ -121,17 +106,54 @@ func (r *SearchStatRepositoryImpl) GetSearchTrend(days int) ([]entity.DailySearc
|
||||
func (r *SearchStatRepositoryImpl) GetKeywordTrend(keyword string, days int) ([]entity.DailySearchStat, error) {
|
||||
var stats []entity.DailySearchStat
|
||||
|
||||
query := `
|
||||
query := fmt.Sprintf(`
|
||||
SELECT
|
||||
date,
|
||||
SUM(count) as total_searches,
|
||||
COUNT(DISTINCT keyword) as unique_keywords
|
||||
FROM search_stats
|
||||
WHERE keyword = ? AND date >= CURRENT_DATE - INTERVAL '? days'
|
||||
WHERE keyword = ? AND date >= CURRENT_DATE - INTERVAL '%d days'
|
||||
GROUP BY date
|
||||
ORDER BY date ASC
|
||||
`
|
||||
`, days)
|
||||
|
||||
err := r.db.Raw(query, keyword, days).Scan(&stats).Error
|
||||
err := r.db.Raw(query, keyword).Scan(&stats).Error
|
||||
return stats, err
|
||||
}
|
||||
|
||||
// GetSummary 获取搜索统计汇总
|
||||
func (r *SearchStatRepositoryImpl) GetSummary() (map[string]int64, error) {
|
||||
var total, today, week, month, keywords int64
|
||||
now := time.Now()
|
||||
todayStr := now.Format("2006-01-02")
|
||||
weekStart := now.AddDate(0, 0, -int(now.Weekday())+1).Format("2006-01-02") // 周一
|
||||
monthStart := now.Format("2006-01") + "-01"
|
||||
|
||||
// 总搜索次数
|
||||
if err := r.db.Model(&entity.SearchStat{}).Count(&total).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 今日搜索次数
|
||||
if err := r.db.Model(&entity.SearchStat{}).Where("DATE(created_at) = ?", todayStr).Count(&today).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 本周搜索次数
|
||||
if err := r.db.Model(&entity.SearchStat{}).Where("created_at >= ?", weekStart).Count(&week).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 本月搜索次数
|
||||
if err := r.db.Model(&entity.SearchStat{}).Where("created_at >= ?", monthStart).Count(&month).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 总关键词数
|
||||
if err := r.db.Model(&entity.SearchStat{}).Distinct("keyword").Count(&keywords).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]int64{
|
||||
"total": total,
|
||||
"today": today,
|
||||
"week": week,
|
||||
"month": month,
|
||||
"keywords": keywords,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package repo
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -9,9 +11,13 @@ import (
|
||||
// SystemConfigRepository 系统配置Repository接口
|
||||
type SystemConfigRepository interface {
|
||||
BaseRepository[entity.SystemConfig]
|
||||
FindFirst() (*entity.SystemConfig, error)
|
||||
GetOrCreateDefault() (*entity.SystemConfig, error)
|
||||
Upsert(config *entity.SystemConfig) error
|
||||
FindAll() ([]entity.SystemConfig, error)
|
||||
FindByKey(key string) (*entity.SystemConfig, error)
|
||||
GetOrCreateDefault() ([]entity.SystemConfig, error)
|
||||
UpsertConfigs(configs []entity.SystemConfig) error
|
||||
GetConfigValue(key string) (string, error)
|
||||
GetConfigBool(key string) (bool, error)
|
||||
GetConfigInt(key string) (int, error)
|
||||
}
|
||||
|
||||
// SystemConfigRepositoryImpl 系统配置Repository实现
|
||||
@@ -26,55 +32,117 @@ func NewSystemConfigRepository(db *gorm.DB) SystemConfigRepository {
|
||||
}
|
||||
}
|
||||
|
||||
// FindFirst 获取第一个配置(通常只有一个配置)
|
||||
func (r *SystemConfigRepositoryImpl) FindFirst() (*entity.SystemConfig, error) {
|
||||
// FindAll 获取所有配置
|
||||
func (r *SystemConfigRepositoryImpl) FindAll() ([]entity.SystemConfig, error) {
|
||||
var configs []entity.SystemConfig
|
||||
err := r.db.Find(&configs).Error
|
||||
return configs, err
|
||||
}
|
||||
|
||||
// FindByKey 根据键查找配置
|
||||
func (r *SystemConfigRepositoryImpl) FindByKey(key string) (*entity.SystemConfig, error) {
|
||||
var config entity.SystemConfig
|
||||
err := r.db.First(&config).Error
|
||||
err := r.db.Where("key = ?", key).First(&config).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
// Upsert 创建或更新系统配置
|
||||
func (r *SystemConfigRepositoryImpl) Upsert(config *entity.SystemConfig) error {
|
||||
var existingConfig entity.SystemConfig
|
||||
err := r.db.First(&existingConfig).Error
|
||||
// UpsertConfigs 批量创建或更新配置
|
||||
func (r *SystemConfigRepositoryImpl) UpsertConfigs(configs []entity.SystemConfig) error {
|
||||
for _, config := range configs {
|
||||
var existingConfig entity.SystemConfig
|
||||
err := r.db.Where("key = ?", config.Key).First(&existingConfig).Error
|
||||
|
||||
if err != nil {
|
||||
// 如果不存在,则创建
|
||||
return r.db.Create(config).Error
|
||||
} else {
|
||||
// 如果存在,则更新
|
||||
config.ID = existingConfig.ID
|
||||
return r.db.Save(config).Error
|
||||
if err != nil {
|
||||
// 如果不存在,则创建
|
||||
if err := r.db.Create(&config).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
// 如果存在,则更新
|
||||
config.ID = existingConfig.ID
|
||||
if err := r.db.Save(&config).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetOrCreateDefault 获取配置或创建默认配置
|
||||
func (r *SystemConfigRepositoryImpl) GetOrCreateDefault() (*entity.SystemConfig, error) {
|
||||
config, err := r.FindFirst()
|
||||
func (r *SystemConfigRepositoryImpl) GetOrCreateDefault() ([]entity.SystemConfig, error) {
|
||||
configs, err := r.FindAll()
|
||||
if err != nil {
|
||||
// 创建默认配置
|
||||
defaultConfig := &entity.SystemConfig{
|
||||
SiteTitle: "网盘资源数据库",
|
||||
SiteDescription: "专业的网盘资源数据库",
|
||||
Keywords: "网盘,资源管理,文件分享",
|
||||
Author: "系统管理员",
|
||||
Copyright: "© 2024 网盘资源数据库",
|
||||
AutoProcessReadyResources: false,
|
||||
AutoProcessInterval: 30,
|
||||
PageSize: 100,
|
||||
MaintenanceMode: false,
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 如果没有配置,创建默认配置
|
||||
if len(configs) == 0 {
|
||||
defaultConfigs := []entity.SystemConfig{
|
||||
{Key: entity.ConfigKeySiteTitle, Value: entity.ConfigDefaultSiteTitle, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeySiteDescription, Value: entity.ConfigDefaultSiteDescription, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyKeywords, Value: entity.ConfigDefaultKeywords, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyAuthor, Value: entity.ConfigDefaultAuthor, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyCopyright, Value: entity.ConfigDefaultCopyright, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyAutoProcessReadyResources, Value: entity.ConfigDefaultAutoProcessReadyResources, Type: entity.ConfigTypeBool},
|
||||
{Key: entity.ConfigKeyAutoProcessInterval, Value: entity.ConfigDefaultAutoProcessInterval, Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyAutoTransferEnabled, Value: entity.ConfigDefaultAutoTransferEnabled, Type: entity.ConfigTypeBool},
|
||||
{Key: entity.ConfigKeyAutoTransferLimitDays, Value: entity.ConfigDefaultAutoTransferLimitDays, Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyAutoTransferMinSpace, Value: entity.ConfigDefaultAutoTransferMinSpace, Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyAutoFetchHotDramaEnabled, Value: entity.ConfigDefaultAutoFetchHotDramaEnabled, Type: entity.ConfigTypeBool},
|
||||
{Key: entity.ConfigKeyApiToken, Value: entity.ConfigDefaultApiToken, Type: entity.ConfigTypeString},
|
||||
{Key: entity.ConfigKeyPageSize, Value: entity.ConfigDefaultPageSize, Type: entity.ConfigTypeInt},
|
||||
{Key: entity.ConfigKeyMaintenanceMode, Value: entity.ConfigDefaultMaintenanceMode, Type: entity.ConfigTypeBool},
|
||||
}
|
||||
|
||||
err = r.db.Create(defaultConfig).Error
|
||||
err = r.UpsertConfigs(defaultConfigs)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return defaultConfig, nil
|
||||
return defaultConfigs, nil
|
||||
}
|
||||
|
||||
return config, nil
|
||||
return configs, nil
|
||||
}
|
||||
|
||||
// GetConfigValue 获取配置值(字符串)
|
||||
func (r *SystemConfigRepositoryImpl) GetConfigValue(key string) (string, error) {
|
||||
config, err := r.FindByKey(key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return config.Value, nil
|
||||
}
|
||||
|
||||
// GetConfigBool 获取配置值(布尔)
|
||||
func (r *SystemConfigRepositoryImpl) GetConfigBool(key string) (bool, error) {
|
||||
value, err := r.GetConfigValue(key)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
switch value {
|
||||
case "true", "1", "yes":
|
||||
return true, nil
|
||||
case "false", "0", "no":
|
||||
return false, nil
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
// GetConfigInt 获取配置值(整数)
|
||||
func (r *SystemConfigRepositoryImpl) GetConfigInt(key string) (int, error) {
|
||||
value, err := r.GetConfigValue(key)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
// 这里需要导入 strconv 包,但为了避免循环导入,我们使用简单的转换
|
||||
var result int
|
||||
_, err = fmt.Sscanf(value, "%d", &result)
|
||||
return result, err
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ type TagRepository interface {
|
||||
FindWithPagination(page, pageSize int) ([]entity.Tag, int64, error)
|
||||
Search(query string, page, pageSize int) ([]entity.Tag, int64, error)
|
||||
UpdateWithNulls(tag *entity.Tag) error
|
||||
GetByID(id uint) (*entity.Tag, error)
|
||||
}
|
||||
|
||||
// TagRepositoryImpl Tag的Repository实现
|
||||
@@ -144,3 +145,13 @@ func (r *TagRepositoryImpl) UpdateWithNulls(tag *entity.Tag) error {
|
||||
// 使用Select方法明确指定要更新的字段,包括null值
|
||||
return r.db.Model(tag).Select("name", "description", "category_id", "updated_at").Updates(tag).Error
|
||||
}
|
||||
|
||||
// GetByID 通过ID查找标签
|
||||
func (r *TagRepositoryImpl) GetByID(id uint) (*entity.Tag, error) {
|
||||
var tag entity.Tag
|
||||
err := r.db.First(&tag, id).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &tag, nil
|
||||
}
|
||||
|
||||
@@ -20,9 +20,7 @@ services:
|
||||
- app-network
|
||||
|
||||
backend:
|
||||
image: ctwj/urldb-backend:0.0.1
|
||||
expose:
|
||||
- "8080"
|
||||
image: ctwj/urldb-backend:1.0.9
|
||||
environment:
|
||||
DB_HOST: postgres
|
||||
DB_PORT: 5432
|
||||
@@ -30,6 +28,7 @@ services:
|
||||
DB_PASSWORD: password
|
||||
DB_NAME: url_db
|
||||
PORT: 8080
|
||||
TIMEZONE: Asia/Shanghai
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -39,9 +38,10 @@ services:
|
||||
- app-network
|
||||
|
||||
frontend:
|
||||
image: ctwj/urldb-frontend:0.0.1
|
||||
image: ctwj/urldb-frontend:1.0.9
|
||||
environment:
|
||||
API_BASE: http://backend:8080/api
|
||||
NUXT_PUBLIC_API_SERVER: http://backend:8080/api
|
||||
NUXT_PUBLIC_API_CLIENT: /api
|
||||
depends_on:
|
||||
- backend
|
||||
networks:
|
||||
|
||||
@@ -38,7 +38,7 @@ $DOCKER_COMPOSE ps
|
||||
|
||||
echo ""
|
||||
echo "✅ 系统启动完成!"
|
||||
echo "🌐 前端访问地址: http://localhost:3000"
|
||||
echo "🌐 前端访问地址: http://localhost:3030"
|
||||
echo "🔧 后端API地址: http://localhost:8080"
|
||||
echo "🗄️ 数据库地址: localhost:5432"
|
||||
echo ""
|
||||
|
||||
1
docs/CNAME
Normal file
1
docs/CNAME
Normal file
@@ -0,0 +1 @@
|
||||
doc.l9.lc
|
||||
@@ -1,6 +1,6 @@
|
||||
# 🚀 urlDB - 网盘资源数据库
|
||||
# 🚀 urlDB - 老九网盘资源数据库
|
||||
|
||||
> 一个现代化的网盘资源数据库,支持多网盘自动化转存分享,支持百度网盘,阿里云盘,夸克网盘, 天翼云盘,迅雷云盘,123云盘,115网盘,UC网盘
|
||||
> 一个现代化的老九网盘资源数据库,支持多网盘自动化转存分享,支持百度网盘,阿里云盘,夸克网盘, 天翼云盘,迅雷云盘,123云盘,115网盘,UC网盘
|
||||
|
||||
<div align="center">
|
||||
|
||||
|
||||
@@ -2,17 +2,14 @@
|
||||
|
||||
* [🏠 首页](/)
|
||||
* [🚀 快速开始](guide/quick-start.md)
|
||||
* [⚙️ 系统配置](guide/configuration.md)
|
||||
* [🐳 Docker部署](guide/docker-deployment.md)
|
||||
* [💻 本地开发](guide/local-development.md)
|
||||
|
||||
* 📚 API 文档
|
||||
* [公开API](api/overview.md)
|
||||
|
||||
* 📖 使用指南
|
||||
* [配置多账号](usage/user-account.md)
|
||||
* [配置自动处理资源](usage/resource-auto.md)
|
||||
* [配置自动转存分享](usage/save-auto.md)
|
||||
|
||||
* 📄 其他
|
||||
* [常见问题](faq.md)
|
||||
* [更新日志](changelog.md)
|
||||
* [许可证](license.md)
|
||||
* [许可证](license.md)
|
||||
* [版本管理](github-version-management.md)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## 概述
|
||||
|
||||
网盘资源数据库提供了一套完整的 RESTful API 接口,支持资源管理、搜索、热门剧获取等功能。所有 API 都需要进行认证,使用 API Token 进行身份验证。
|
||||
老九网盘资源数据库提供了一套完整的 RESTful API 接口,支持资源管理、搜索、热门剧获取等功能。所有 API 都需要进行认证,使用 API Token 进行身份验证。
|
||||
|
||||
## 基础信息
|
||||
|
||||
|
||||
@@ -5,6 +5,10 @@ window.$docsify = {
|
||||
loadSidebar: true,
|
||||
subMaxLevel: 3,
|
||||
auto2top: true,
|
||||
// 添加侧边栏配置
|
||||
sidebarDisplayLevel: 1,
|
||||
// 添加错误处理
|
||||
notFoundPage: true,
|
||||
search: {
|
||||
maxAge: 86400000,
|
||||
paths: 'auto',
|
||||
@@ -34,6 +38,16 @@ window.$docsify = {
|
||||
'最后更新: ' + new Date().toLocaleDateString('zh-CN') +
|
||||
'</div>';
|
||||
});
|
||||
|
||||
// 添加侧边栏加载调试
|
||||
hook.doneEach(function() {
|
||||
console.log('Docsify loaded, sidebar should be visible');
|
||||
if (document.querySelector('.sidebar-nav')) {
|
||||
console.log('Sidebar element found');
|
||||
} else {
|
||||
console.log('Sidebar element not found');
|
||||
}
|
||||
});
|
||||
}
|
||||
]
|
||||
};
|
||||
@@ -47,6 +47,7 @@ docker compose ps
|
||||
|
||||
可以通过修改 `docker-compose.yml` 文件中的环境变量来配置服务:
|
||||
|
||||
后端 backend
|
||||
```yaml
|
||||
environment:
|
||||
DB_HOST: postgres
|
||||
@@ -55,7 +56,12 @@ environment:
|
||||
DB_PASSWORD: password
|
||||
DB_NAME: url_db
|
||||
PORT: 8080
|
||||
API_BASE: http://localhost:8080/api
|
||||
```
|
||||
|
||||
前端 frontend
|
||||
```yaml
|
||||
environment:
|
||||
API_BASE: /api
|
||||
```
|
||||
|
||||
### 端口映射
|
||||
|
||||
@@ -23,7 +23,7 @@ docker compose up --build -d
|
||||
|
||||
启动成功后,您可以通过以下地址访问:
|
||||
|
||||
- **前端界面**: http://localhost:3000
|
||||
- **前端界面**: http://localhost:3030
|
||||
默认用户密码: admin/password
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>urlDB - 网盘资源数据库</title>
|
||||
<title>urlDB - 老九网盘资源数据库</title>
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
|
||||
<meta name="description" content="一个现代化的网盘资源数据库,支持多网盘自动化转存分享">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
|
||||
@@ -12,8 +12,8 @@
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script src="./docsify.config.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify@4"></script>
|
||||
<script src="./docsify.config.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify@4/lib/plugins/search.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify@4/lib/plugins/copy-code.min.js"></script>
|
||||
<script src="//cdn.jsdelivr.net/npm/docsify@4/lib/plugins/pagination.min.js"></script>
|
||||
|
||||
@@ -7,6 +7,10 @@ DB_NAME=url_db
|
||||
|
||||
# 服务器配置
|
||||
PORT=8080
|
||||
GIN_MODE=release
|
||||
|
||||
# 时区配置
|
||||
TIMEZONE=Asia/Shanghai
|
||||
|
||||
# 文件上传配置
|
||||
UPLOAD_DIR=./uploads
|
||||
|
||||
1
go.mod
1
go.mod
@@ -35,6 +35,7 @@ require (
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 // indirect
|
||||
github.com/kr/pretty v0.3.1 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0
|
||||
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
|
||||
|
||||
2
go.sum
2
go.sum
@@ -76,6 +76,8 @@ github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY=
|
||||
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/matoous/go-nanoid/v2 v2.1.0 h1:P64+dmq21hhWdtvZfEAofnvJULaRR1Yib0+PnU669bE=
|
||||
github.com/matoous/go-nanoid/v2 v2.1.0/go.mod h1:KlbGNQ+FhrUNIHUxZdL63t7tl4LaPkZNpUULS8H4uVM=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
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=
|
||||
|
||||
@@ -192,6 +192,8 @@ func UpdateCks(c *gin.Context) {
|
||||
if req.Ck != "" {
|
||||
cks.Ck = req.Ck
|
||||
}
|
||||
// 对于 bool 类型,我们需要检查请求中是否包含该字段
|
||||
// 由于 Go 的 JSON 解析,如果字段存在且为 false,也会被正确解析
|
||||
cks.IsValid = req.IsValid
|
||||
if req.LeftSpace != 0 {
|
||||
cks.LeftSpace = req.LeftSpace
|
||||
@@ -210,7 +212,8 @@ func UpdateCks(c *gin.Context) {
|
||||
cks.Remark = req.Remark
|
||||
}
|
||||
|
||||
err = repoManager.CksRepository.Update(cks)
|
||||
// 使用专门的方法更新,确保更新所有字段包括零值
|
||||
err = repoManager.CksRepository.UpdateWithAllFields(cks)
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
@@ -321,7 +324,7 @@ func RefreshCapacity(c *gin.Context) {
|
||||
cks.UsedSpace = userInfo.UsedSpace
|
||||
cks.IsValid = userInfo.VIPStatus // 根据VIP状态更新有效性
|
||||
|
||||
err = repoManager.CksRepository.Update(cks)
|
||||
err = repoManager.CksRepository.UpdateWithAllFields(cks)
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"strconv"
|
||||
|
||||
"github.com/ctwj/urldb/db/converter"
|
||||
"github.com/ctwj/urldb/db/dto"
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -19,84 +17,6 @@ func NewPublicAPIHandler() *PublicAPIHandler {
|
||||
return &PublicAPIHandler{}
|
||||
}
|
||||
|
||||
// AddSingleResource godoc
|
||||
// @Summary 单个添加资源
|
||||
// @Description 通过公开API添加单个资源到待处理列表
|
||||
// @Tags PublicAPI
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param X-API-Token header string true "API访问令牌"
|
||||
// @Param data body dto.ReadyResourceRequest true "资源信息"
|
||||
// @Success 200 {object} map[string]interface{} "添加成功"
|
||||
// @Failure 400 {object} map[string]interface{} "请求参数错误"
|
||||
// @Failure 401 {object} map[string]interface{} "认证失败"
|
||||
// @Failure 500 {object} map[string]interface{} "服务器内部错误"
|
||||
// @Router /api/public/resources/add [post]
|
||||
func (h *PublicAPIHandler) AddSingleResource(c *gin.Context) {
|
||||
var req dto.ReadyResourceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "请求参数错误: " + err.Error(),
|
||||
"code": 400,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证必填字段
|
||||
if req.Title == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "标题不能为空",
|
||||
"code": 400,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Url == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "URL不能为空",
|
||||
"code": 400,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 转换为实体
|
||||
readyResource := converter.RequestToReadyResource(&req)
|
||||
if readyResource == nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"message": "数据转换失败",
|
||||
"code": 500,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 设置来源
|
||||
readyResource.Source = "公开API"
|
||||
|
||||
// 保存到数据库
|
||||
err := repoManager.ReadyResourceRepository.Create(readyResource)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"message": "添加资源失败: " + err.Error(),
|
||||
"code": 500,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "资源添加成功,已进入待处理列表",
|
||||
"data": gin.H{
|
||||
"id": readyResource.ID,
|
||||
},
|
||||
"code": 200,
|
||||
})
|
||||
}
|
||||
|
||||
// AddBatchResources godoc
|
||||
// @Summary 批量添加资源
|
||||
// @Description 通过公开API批量添加多个资源到待处理列表
|
||||
@@ -113,65 +33,80 @@ func (h *PublicAPIHandler) AddSingleResource(c *gin.Context) {
|
||||
func (h *PublicAPIHandler) AddBatchResources(c *gin.Context) {
|
||||
var req dto.BatchReadyResourceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "请求参数错误: " + err.Error(),
|
||||
"code": 400,
|
||||
})
|
||||
ErrorResponse(c, "请求参数错误: "+err.Error(), 400)
|
||||
return
|
||||
}
|
||||
|
||||
if len(req.Resources) == 0 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "资源列表不能为空",
|
||||
"code": 400,
|
||||
})
|
||||
ErrorResponse(c, "资源列表不能为空", 400)
|
||||
return
|
||||
}
|
||||
|
||||
// 验证每个资源
|
||||
for i, resource := range req.Resources {
|
||||
if resource.Title == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "第" + strconv.Itoa(i+1) + "个资源标题不能为空",
|
||||
"code": 400,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if resource.Url == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{
|
||||
"success": false,
|
||||
"message": "第" + strconv.Itoa(i+1) + "个资源URL不能为空",
|
||||
"code": 400,
|
||||
})
|
||||
return
|
||||
// 收集所有待提交的URL,去重
|
||||
urlSet := make(map[string]struct{})
|
||||
for _, resource := range req.Resources {
|
||||
for _, u := range resource.Url {
|
||||
if u != "" {
|
||||
urlSet[u] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
uniqueUrls := make([]string, 0, len(urlSet))
|
||||
for url := range urlSet {
|
||||
uniqueUrls = append(uniqueUrls, url)
|
||||
}
|
||||
|
||||
// 批量查重
|
||||
readyList, _ := repoManager.ReadyResourceRepository.BatchFindByURLs(uniqueUrls)
|
||||
existReadyUrls := make(map[string]struct{})
|
||||
for _, r := range readyList {
|
||||
existReadyUrls[r.URL] = struct{}{}
|
||||
}
|
||||
resourceList, _ := repoManager.ResourceRepository.BatchFindByURLs(uniqueUrls)
|
||||
existResourceUrls := make(map[string]struct{})
|
||||
for _, r := range resourceList {
|
||||
existResourceUrls[r.URL] = struct{}{}
|
||||
}
|
||||
|
||||
// 批量保存
|
||||
var createdResources []uint
|
||||
for _, resourceReq := range req.Resources {
|
||||
readyResource := converter.RequestToReadyResource(&resourceReq)
|
||||
if readyResource != nil {
|
||||
readyResource.Source = "公开API批量添加"
|
||||
err := repoManager.ReadyResourceRepository.Create(readyResource)
|
||||
// 生成 key(每组同一个 key)
|
||||
key, err := repoManager.ReadyResourceRepository.GenerateUniqueKey()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "生成资源组标识失败: "+err.Error(), 500)
|
||||
return
|
||||
}
|
||||
for _, url := range resourceReq.Url {
|
||||
if url == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := existReadyUrls[url]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := existResourceUrls[url]; ok {
|
||||
continue
|
||||
}
|
||||
readyResource := entity.ReadyResource{
|
||||
Title: &resourceReq.Title,
|
||||
Description: resourceReq.Description,
|
||||
URL: url,
|
||||
Category: resourceReq.Category,
|
||||
Tags: resourceReq.Tags,
|
||||
Img: resourceReq.Img,
|
||||
Source: "api",
|
||||
Extra: resourceReq.Extra,
|
||||
Key: key,
|
||||
}
|
||||
err := repoManager.ReadyResourceRepository.Create(&readyResource)
|
||||
if err == nil {
|
||||
createdResources = append(createdResources, readyResource.ID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "批量添加成功,共添加 " + strconv.Itoa(len(createdResources)) + " 个资源",
|
||||
"data": gin.H{
|
||||
"created_count": len(createdResources),
|
||||
"created_ids": createdResources,
|
||||
},
|
||||
"code": 200,
|
||||
SuccessResponse(c, gin.H{
|
||||
"created_count": len(createdResources),
|
||||
"created_ids": createdResources,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -230,11 +165,7 @@ func (h *PublicAPIHandler) SearchResources(c *gin.Context) {
|
||||
// 执行搜索
|
||||
resources, total, err := repoManager.ResourceRepository.SearchWithFilters(params)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"message": "搜索失败: " + err.Error(),
|
||||
"code": 500,
|
||||
})
|
||||
ErrorResponse(c, "搜索失败: "+err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -252,16 +183,11 @@ func (h *PublicAPIHandler) SearchResources(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "搜索成功",
|
||||
"data": gin.H{
|
||||
"resources": resourceResponses,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
},
|
||||
"code": 200,
|
||||
SuccessResponse(c, gin.H{
|
||||
"list": resourceResponses,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"limit": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -295,11 +221,7 @@ func (h *PublicAPIHandler) GetHotDramas(c *gin.Context) {
|
||||
// 获取热门剧
|
||||
hotDramas, total, err := repoManager.HotDramaRepository.FindAll(page, pageSize)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"message": "获取热门剧失败: " + err.Error(),
|
||||
"code": 500,
|
||||
})
|
||||
ErrorResponse(c, "获取热门剧失败: "+err.Error(), 500)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -322,15 +244,10 @@ func (h *PublicAPIHandler) GetHotDramas(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "获取热门剧成功",
|
||||
"data": gin.H{
|
||||
"hot_dramas": hotDramaResponses,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
},
|
||||
"code": 200,
|
||||
SuccessResponse(c, gin.H{
|
||||
"hot_dramas": hotDramaResponses,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -46,38 +46,6 @@ func GetReadyResources(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// CreateReadyResource 创建待处理资源
|
||||
func CreateReadyResource(c *gin.Context) {
|
||||
var req dto.CreateReadyResourceRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
resource := &entity.ReadyResource{
|
||||
Title: req.Title,
|
||||
Description: req.Description,
|
||||
URL: req.URL,
|
||||
Category: req.Category,
|
||||
Tags: req.Tags,
|
||||
Img: req.Img,
|
||||
Source: req.Source,
|
||||
Extra: req.Extra,
|
||||
IP: req.IP,
|
||||
}
|
||||
|
||||
err := repoManager.ReadyResourceRepository.Create(resource)
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
"id": resource.ID,
|
||||
"message": "待处理资源创建成功",
|
||||
})
|
||||
}
|
||||
|
||||
// BatchCreateReadyResources 批量创建待处理资源
|
||||
func BatchCreateReadyResources(c *gin.Context) {
|
||||
var req dto.BatchCreateReadyResourceRequest
|
||||
@@ -86,20 +54,85 @@ func BatchCreateReadyResources(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 1. 先收集所有待提交的URL,去重
|
||||
urlSet := make(map[string]struct{})
|
||||
for _, reqResource := range req.Resources {
|
||||
if len(reqResource.URL) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, u := range reqResource.URL {
|
||||
if u != "" {
|
||||
urlSet[u] = struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
uniqueUrls := make([]string, 0, len(urlSet))
|
||||
for url := range urlSet {
|
||||
uniqueUrls = append(uniqueUrls, url)
|
||||
}
|
||||
|
||||
// 2. 批量查询待处理资源表中已存在的URL
|
||||
existReadyUrls := make(map[string]struct{})
|
||||
if len(uniqueUrls) > 0 {
|
||||
readyList, _ := repoManager.ReadyResourceRepository.BatchFindByURLs(uniqueUrls)
|
||||
for _, r := range readyList {
|
||||
existReadyUrls[r.URL] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 批量查询资源表中已存在的URL
|
||||
existResourceUrls := make(map[string]struct{})
|
||||
if len(uniqueUrls) > 0 {
|
||||
resourceList, _ := repoManager.ResourceRepository.BatchFindByURLs(uniqueUrls)
|
||||
for _, r := range resourceList {
|
||||
existResourceUrls[r.URL] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
// 5. 过滤掉已存在的URL
|
||||
var resources []entity.ReadyResource
|
||||
for _, reqResource := range req.Resources {
|
||||
resource := entity.ReadyResource{
|
||||
Title: reqResource.Title,
|
||||
Description: reqResource.Description,
|
||||
URL: reqResource.URL,
|
||||
Category: reqResource.Category,
|
||||
Tags: reqResource.Tags,
|
||||
Img: reqResource.Img,
|
||||
Source: reqResource.Source,
|
||||
Extra: reqResource.Extra,
|
||||
IP: reqResource.IP,
|
||||
if len(reqResource.URL) == 0 {
|
||||
continue
|
||||
}
|
||||
resources = append(resources, resource)
|
||||
key, err := repoManager.ReadyResourceRepository.GenerateUniqueKey()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "生成批量资源组标识失败: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
for _, url := range reqResource.URL {
|
||||
if url == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := existReadyUrls[url]; ok {
|
||||
continue
|
||||
}
|
||||
if _, ok := existResourceUrls[url]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
resource := entity.ReadyResource{
|
||||
Title: reqResource.Title,
|
||||
Description: reqResource.Description,
|
||||
URL: url,
|
||||
Category: reqResource.Category,
|
||||
Tags: reqResource.Tags,
|
||||
Img: reqResource.Img,
|
||||
Source: reqResource.Source,
|
||||
Extra: reqResource.Extra,
|
||||
IP: reqResource.IP,
|
||||
Key: key,
|
||||
}
|
||||
resources = append(resources, resource)
|
||||
}
|
||||
}
|
||||
|
||||
if len(resources) == 0 {
|
||||
SuccessResponse(c, gin.H{
|
||||
"count": 0,
|
||||
"message": "无新增资源,所有URL均已存在",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
err := repoManager.ReadyResourceRepository.BatchCreate(resources)
|
||||
@@ -196,3 +229,239 @@ func ClearReadyResources(c *gin.Context) {
|
||||
"message": "所有待处理资源已清空",
|
||||
})
|
||||
}
|
||||
|
||||
// GetReadyResourcesByKey 根据key获取待处理资源
|
||||
func GetReadyResourcesByKey(c *gin.Context) {
|
||||
key := c.Param("key")
|
||||
if key == "" {
|
||||
ErrorResponse(c, "key参数不能为空", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
resources, err := repoManager.ReadyResourceRepository.FindByKey(key)
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := converter.ToReadyResourceResponseList(resources)
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
"data": responses,
|
||||
"key": key,
|
||||
"count": len(resources),
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteReadyResourcesByKey 根据key删除待处理资源
|
||||
func DeleteReadyResourcesByKey(c *gin.Context) {
|
||||
key := c.Param("key")
|
||||
if key == "" {
|
||||
ErrorResponse(c, "key参数不能为空", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 先查询要删除的资源数量
|
||||
resources, err := repoManager.ReadyResourceRepository.FindByKey(key)
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if len(resources) == 0 {
|
||||
ErrorResponse(c, "未找到指定key的资源", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
// 删除所有具有相同key的资源
|
||||
err = repoManager.ReadyResourceRepository.DeleteByKey(key)
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
"deleted_count": len(resources),
|
||||
"key": key,
|
||||
"message": "资源组删除成功",
|
||||
})
|
||||
}
|
||||
|
||||
// getRetryableErrorCount 统计可重试的错误数量
|
||||
func getRetryableErrorCount(resources []entity.ReadyResource) int {
|
||||
count := 0
|
||||
|
||||
for _, resource := range resources {
|
||||
if resource.ErrorMsg != "" {
|
||||
errorMsg := strings.ToUpper(resource.ErrorMsg)
|
||||
// 检查错误类型标记
|
||||
if strings.Contains(resource.ErrorMsg, "[NO_ACCOUNT]") ||
|
||||
strings.Contains(resource.ErrorMsg, "[NO_VALID_ACCOUNT]") ||
|
||||
strings.Contains(resource.ErrorMsg, "[TRANSFER_FAILED]") ||
|
||||
strings.Contains(resource.ErrorMsg, "[LINK_CHECK_FAILED]") {
|
||||
count++
|
||||
} else if strings.Contains(errorMsg, "没有可用的网盘账号") ||
|
||||
strings.Contains(errorMsg, "没有有效的网盘账号") ||
|
||||
strings.Contains(errorMsg, "网盘信息获取失败") ||
|
||||
strings.Contains(errorMsg, "链接检查失败") {
|
||||
count++
|
||||
}
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// GetReadyResourcesWithErrors 获取有错误信息的待处理资源
|
||||
func GetReadyResourcesWithErrors(c *gin.Context) {
|
||||
// 获取分页参数
|
||||
pageStr := c.DefaultQuery("page", "1")
|
||||
pageSizeStr := c.DefaultQuery("page_size", "100")
|
||||
|
||||
page, err := strconv.Atoi(pageStr)
|
||||
if err != nil || page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
pageSize, err := strconv.Atoi(pageSizeStr)
|
||||
if err != nil || pageSize < 1 || pageSize > 1000 {
|
||||
pageSize = 100
|
||||
}
|
||||
|
||||
// 获取有错误的资源
|
||||
resources, err := repoManager.ReadyResourceRepository.FindWithErrors()
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
responses := converter.ToReadyResourceResponseList(resources)
|
||||
|
||||
// 统计错误类型
|
||||
errorTypeStats := make(map[string]int)
|
||||
for _, resource := range resources {
|
||||
if resource.ErrorMsg != "" {
|
||||
// 尝试从错误信息中提取错误类型
|
||||
if len(resource.ErrorMsg) > 0 && resource.ErrorMsg[0] == '[' {
|
||||
endIndex := strings.Index(resource.ErrorMsg, "]")
|
||||
if endIndex > 0 {
|
||||
errorType := resource.ErrorMsg[1:endIndex]
|
||||
errorTypeStats[errorType]++
|
||||
} else {
|
||||
errorTypeStats["UNKNOWN"]++
|
||||
}
|
||||
} else {
|
||||
// 如果没有错误类型标记,尝试从错误信息中推断
|
||||
errorMsg := strings.ToUpper(resource.ErrorMsg)
|
||||
if strings.Contains(errorMsg, "不支持的链接") {
|
||||
errorTypeStats["UNSUPPORTED_LINK"]++
|
||||
} else if strings.Contains(errorMsg, "链接无效") {
|
||||
errorTypeStats["INVALID_LINK"]++
|
||||
} else if strings.Contains(errorMsg, "没有可用的网盘账号") {
|
||||
errorTypeStats["NO_ACCOUNT"]++
|
||||
} else if strings.Contains(errorMsg, "没有有效的网盘账号") {
|
||||
errorTypeStats["NO_VALID_ACCOUNT"]++
|
||||
} else if strings.Contains(errorMsg, "网盘信息获取失败") {
|
||||
errorTypeStats["TRANSFER_FAILED"]++
|
||||
} else if strings.Contains(errorMsg, "创建网盘服务失败") {
|
||||
errorTypeStats["SERVICE_CREATION_FAILED"]++
|
||||
} else if strings.Contains(errorMsg, "处理标签失败") {
|
||||
errorTypeStats["TAG_PROCESSING_FAILED"]++
|
||||
} else if strings.Contains(errorMsg, "处理分类失败") {
|
||||
errorTypeStats["CATEGORY_PROCESSING_FAILED"]++
|
||||
} else if strings.Contains(errorMsg, "资源保存失败") {
|
||||
errorTypeStats["RESOURCE_SAVE_FAILED"]++
|
||||
} else if strings.Contains(errorMsg, "未找到对应的平台ID") {
|
||||
errorTypeStats["PLATFORM_NOT_FOUND"]++
|
||||
} else if strings.Contains(errorMsg, "链接检查失败") {
|
||||
errorTypeStats["LINK_CHECK_FAILED"]++
|
||||
} else {
|
||||
errorTypeStats["UNKNOWN"]++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
"data": responses,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
"total": len(resources),
|
||||
"count": len(resources),
|
||||
"error_stats": errorTypeStats,
|
||||
"retryable_count": getRetryableErrorCount(resources),
|
||||
})
|
||||
}
|
||||
|
||||
// ClearErrorMsg 清除指定资源的错误信息
|
||||
func ClearErrorMsg(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
id, err := strconv.ParseUint(idStr, 10, 32)
|
||||
if err != nil {
|
||||
ErrorResponse(c, "无效的ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
err = repoManager.ReadyResourceRepository.ClearErrorMsg(uint(id))
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
SuccessResponse(c, gin.H{"message": "错误信息已清除"})
|
||||
}
|
||||
|
||||
// RetryFailedResources 重试失败的资源
|
||||
func RetryFailedResources(c *gin.Context) {
|
||||
// 获取有错误的资源
|
||||
resources, err := repoManager.ReadyResourceRepository.FindWithErrors()
|
||||
if err != nil {
|
||||
ErrorResponse(c, err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
if len(resources) == 0 {
|
||||
SuccessResponse(c, gin.H{
|
||||
"message": "没有需要重试的资源",
|
||||
"count": 0,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 只重试可重试的错误
|
||||
clearedCount := 0
|
||||
skippedCount := 0
|
||||
|
||||
for _, resource := range resources {
|
||||
isRetryable := false
|
||||
errorMsg := strings.ToUpper(resource.ErrorMsg)
|
||||
|
||||
// 检查错误类型标记
|
||||
if strings.Contains(resource.ErrorMsg, "[NO_ACCOUNT]") ||
|
||||
strings.Contains(resource.ErrorMsg, "[NO_VALID_ACCOUNT]") ||
|
||||
strings.Contains(resource.ErrorMsg, "[TRANSFER_FAILED]") ||
|
||||
strings.Contains(resource.ErrorMsg, "[LINK_CHECK_FAILED]") {
|
||||
isRetryable = true
|
||||
} else if strings.Contains(errorMsg, "没有可用的网盘账号") ||
|
||||
strings.Contains(errorMsg, "没有有效的网盘账号") ||
|
||||
strings.Contains(errorMsg, "网盘信息获取失败") ||
|
||||
strings.Contains(errorMsg, "链接检查失败") {
|
||||
isRetryable = true
|
||||
}
|
||||
|
||||
if isRetryable {
|
||||
if err := repoManager.ReadyResourceRepository.ClearErrorMsg(resource.ID); err == nil {
|
||||
clearedCount++
|
||||
}
|
||||
} else {
|
||||
skippedCount++
|
||||
}
|
||||
}
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
"message": "已清除可重试资源的错误信息,资源将在下次调度时重新处理",
|
||||
"total_count": len(resources),
|
||||
"cleared_count": clearedCount,
|
||||
"skipped_count": skippedCount,
|
||||
"retryable_count": getRetryableErrorCount(resources),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,35 +15,36 @@ import (
|
||||
func GetResources(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
categoryID := c.Query("category_id")
|
||||
panID := c.Query("pan_id")
|
||||
search := c.Query("search")
|
||||
|
||||
var resources []entity.Resource
|
||||
var total int64
|
||||
var err error
|
||||
params := map[string]interface{}{
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
}
|
||||
|
||||
// 设置响应头,启用缓存
|
||||
c.Header("Cache-Control", "public, max-age=300") // 5分钟缓存
|
||||
if search := c.Query("search"); search != "" {
|
||||
params["search"] = search
|
||||
}
|
||||
if panID := c.Query("pan_id"); panID != "" {
|
||||
if id, err := strconv.ParseUint(panID, 10, 32); err == nil {
|
||||
params["pan_id"] = uint(id)
|
||||
}
|
||||
}
|
||||
if categoryID := c.Query("category_id"); categoryID != "" {
|
||||
if id, err := strconv.ParseUint(categoryID, 10, 32); err == nil {
|
||||
params["category_id"] = uint(id)
|
||||
}
|
||||
}
|
||||
|
||||
if search != "" && panID != "" {
|
||||
// 平台内搜索
|
||||
panIDUint, _ := strconv.ParseUint(panID, 10, 32)
|
||||
resources, total, err = repoManager.ResourceRepository.SearchByPanID(search, uint(panIDUint), page, pageSize)
|
||||
} else if search != "" {
|
||||
// 全局搜索
|
||||
resources, total, err = repoManager.ResourceRepository.Search(search, nil, page, pageSize)
|
||||
} else if panID != "" {
|
||||
// 按平台筛选
|
||||
panIDUint, _ := strconv.ParseUint(panID, 10, 32)
|
||||
resources, total, err = repoManager.ResourceRepository.FindByPanIDPaginated(uint(panIDUint), page, pageSize)
|
||||
} else if categoryID != "" {
|
||||
// 按分类筛选
|
||||
categoryIDUint, _ := strconv.ParseUint(categoryID, 10, 32)
|
||||
resources, total, err = repoManager.ResourceRepository.FindByCategoryIDPaginated(uint(categoryIDUint), page, pageSize)
|
||||
} else {
|
||||
// 使用分页查询,避免加载所有数据
|
||||
resources, total, err = repoManager.ResourceRepository.FindWithRelationsPaginated(page, pageSize)
|
||||
resources, total, err := repoManager.ResourceRepository.SearchWithFilters(params)
|
||||
|
||||
// 搜索统计(仅非管理员)
|
||||
if search, ok := params["search"].(string); ok && search != "" {
|
||||
user, _ := c.Get("user")
|
||||
if user == nil || (user != nil && user.(entity.User).Role != "admin") {
|
||||
ip := c.ClientIP()
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
repoManager.SearchStatRepository.RecordSearch(search, ip, userAgent)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -52,7 +53,7 @@ func GetResources(c *gin.Context) {
|
||||
}
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
"resources": converter.ToResourceResponseList(resources),
|
||||
"data": converter.ToResourceResponseList(resources),
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
@@ -119,11 +120,14 @@ func CreateResource(c *gin.Context) {
|
||||
Description: req.Description,
|
||||
URL: req.URL,
|
||||
PanID: req.PanID,
|
||||
QuarkURL: req.QuarkURL,
|
||||
SaveURL: req.SaveURL,
|
||||
FileSize: req.FileSize,
|
||||
CategoryID: req.CategoryID,
|
||||
IsValid: req.IsValid,
|
||||
IsPublic: req.IsPublic,
|
||||
Cover: req.Cover,
|
||||
Author: req.Author,
|
||||
ErrorMsg: req.ErrorMsg,
|
||||
}
|
||||
|
||||
err := repoManager.ResourceRepository.Create(resource)
|
||||
@@ -181,8 +185,8 @@ func UpdateResource(c *gin.Context) {
|
||||
if req.PanID != nil {
|
||||
resource.PanID = req.PanID
|
||||
}
|
||||
if req.QuarkURL != "" {
|
||||
resource.QuarkURL = req.QuarkURL
|
||||
if req.SaveURL != "" {
|
||||
resource.SaveURL = req.SaveURL
|
||||
}
|
||||
if req.FileSize != "" {
|
||||
resource.FileSize = req.FileSize
|
||||
@@ -192,6 +196,15 @@ func UpdateResource(c *gin.Context) {
|
||||
}
|
||||
resource.IsValid = req.IsValid
|
||||
resource.IsPublic = req.IsPublic
|
||||
if req.Cover != "" {
|
||||
resource.Cover = req.Cover
|
||||
}
|
||||
if req.Author != "" {
|
||||
resource.Author = req.Author
|
||||
}
|
||||
if req.ErrorMsg != "" {
|
||||
resource.ErrorMsg = req.ErrorMsg
|
||||
}
|
||||
|
||||
// 处理标签关联
|
||||
if len(req.TagIDs) > 0 {
|
||||
@@ -245,6 +258,10 @@ func SearchResources(c *gin.Context) {
|
||||
} else {
|
||||
// 有搜索关键词时,执行搜索
|
||||
resources, total, err = repoManager.ResourceRepository.Search(query, nil, page, pageSize)
|
||||
// 新增:记录搜索关键词
|
||||
ip := c.ClientIP()
|
||||
userAgent := c.GetHeader("User-Agent")
|
||||
repoManager.SearchStatRepository.RecordSearch(query, ip, userAgent)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -259,3 +276,37 @@ func SearchResources(c *gin.Context) {
|
||||
"page_size": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
// 增加资源浏览次数
|
||||
func IncrementResourceViewCount(c *gin.Context) {
|
||||
idStr := c.Param("id")
|
||||
id, err := strconv.Atoi(idStr)
|
||||
if err != nil {
|
||||
ErrorResponse(c, "无效的资源ID", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
err = repoManager.ResourceRepository.IncrementViewCount(uint(id))
|
||||
if err != nil {
|
||||
ErrorResponse(c, "增加浏览次数失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
SuccessResponse(c, gin.H{"message": "浏览次数+1"})
|
||||
}
|
||||
|
||||
// BatchDeleteResources 批量删除资源
|
||||
func BatchDeleteResources(c *gin.Context) {
|
||||
var req struct {
|
||||
IDs []uint `json:"ids"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil || len(req.IDs) == 0 {
|
||||
ErrorResponse(c, "参数错误", 400)
|
||||
return
|
||||
}
|
||||
count := 0
|
||||
for _, id := range req.IDs {
|
||||
if err := repoManager.ResourceRepository.Delete(id); err == nil {
|
||||
count++
|
||||
}
|
||||
}
|
||||
SuccessResponse(c, gin.H{"deleted": count, "message": "批量删除成功"})
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ func GetSchedulerStatus(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
|
||||
status := gin.H{
|
||||
@@ -36,6 +38,8 @@ func StartHotDramaScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if scheduler.IsHotDramaSchedulerRunning() {
|
||||
ErrorResponse(c, "热播剧定时任务已在运行中", http.StatusBadRequest)
|
||||
@@ -54,6 +58,8 @@ func StopHotDramaScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if !scheduler.IsHotDramaSchedulerRunning() {
|
||||
ErrorResponse(c, "热播剧定时任务未在运行", http.StatusBadRequest)
|
||||
@@ -72,6 +78,8 @@ func TriggerHotDramaScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
scheduler.StartHotDramaScheduler() // 直接启动一次
|
||||
SuccessResponse(c, gin.H{"message": "手动触发热播剧定时任务成功"})
|
||||
@@ -86,6 +94,8 @@ func FetchHotDramaNames(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
names, err := scheduler.GetHotDramaNames()
|
||||
if err != nil {
|
||||
@@ -104,6 +114,8 @@ func StartReadyResourceScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if scheduler.IsReadyResourceRunning() {
|
||||
ErrorResponse(c, "待处理资源自动处理任务已在运行中", http.StatusBadRequest)
|
||||
@@ -122,6 +134,8 @@ func StopReadyResourceScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if !scheduler.IsReadyResourceRunning() {
|
||||
ErrorResponse(c, "待处理资源自动处理任务未在运行", http.StatusBadRequest)
|
||||
@@ -140,6 +154,8 @@ func TriggerReadyResourceScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
// 手动触发一次处理
|
||||
scheduler.ProcessReadyResources()
|
||||
@@ -155,6 +171,8 @@ func StartAutoTransferScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if scheduler.IsAutoTransferRunning() {
|
||||
ErrorResponse(c, "自动转存定时任务已在运行中", http.StatusBadRequest)
|
||||
@@ -173,6 +191,8 @@ func StopAutoTransferScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if !scheduler.IsAutoTransferRunning() {
|
||||
ErrorResponse(c, "自动转存定时任务未在运行", http.StatusBadRequest)
|
||||
@@ -191,6 +211,8 @@ func TriggerAutoTransferScheduler(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
// 手动触发一次处理
|
||||
scheduler.ProcessAutoTransfer()
|
||||
|
||||
@@ -142,3 +142,13 @@ func GetKeywordTrend(c *gin.Context) {
|
||||
response := converter.ToDailySearchStatResponseList(trend)
|
||||
SuccessResponse(c, response)
|
||||
}
|
||||
|
||||
// GetSearchStatsSummary 获取搜索统计汇总
|
||||
func GetSearchStatsSummary(c *gin.Context) {
|
||||
summary, err := repoManager.SearchStatRepository.GetSummary()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "获取搜索统计汇总失败", 500)
|
||||
return
|
||||
}
|
||||
SuccessResponse(c, summary)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
|
||||
"github.com/ctwj/urldb/db"
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
"github.com/ctwj/urldb/utils"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
@@ -23,7 +24,7 @@ func GetStats(c *gin.Context) {
|
||||
|
||||
// 获取今日更新数量
|
||||
var todayUpdates int64
|
||||
today := time.Now().Format("2006-01-02")
|
||||
today := utils.GetCurrentTime().Format("2006-01-02")
|
||||
db.DB.Model(&entity.Resource{}).Where("DATE(updated_at) = ?", today).Count(&todayUpdates)
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
@@ -44,20 +45,27 @@ func GetPerformanceStats(c *gin.Context) {
|
||||
sqlDB, err := db.DB.DB()
|
||||
var dbStats gin.H
|
||||
if err == nil {
|
||||
stats := sqlDB.Stats()
|
||||
dbStats = gin.H{
|
||||
"max_open_connections": sqlDB.Stats().MaxOpenConnections,
|
||||
"open_connections": sqlDB.Stats().OpenConnections,
|
||||
"in_use": sqlDB.Stats().InUse,
|
||||
"idle": sqlDB.Stats().Idle,
|
||||
"max_open_connections": stats.MaxOpenConnections,
|
||||
"open_connections": stats.OpenConnections,
|
||||
"in_use": stats.InUse,
|
||||
"idle": stats.Idle,
|
||||
"wait_count": stats.WaitCount,
|
||||
"wait_duration": stats.WaitDuration,
|
||||
}
|
||||
// 添加调试日志
|
||||
utils.Info("数据库连接池状态 - MaxOpen: %d, Open: %d, InUse: %d, Idle: %d",
|
||||
stats.MaxOpenConnections, stats.OpenConnections, stats.InUse, stats.Idle)
|
||||
} else {
|
||||
dbStats = gin.H{
|
||||
"error": "无法获取数据库连接池状态",
|
||||
"error": "无法获取数据库连接池状态: " + err.Error(),
|
||||
}
|
||||
utils.Error("获取数据库连接池状态失败: %v", err)
|
||||
}
|
||||
|
||||
SuccessResponse(c, gin.H{
|
||||
"timestamp": time.Now().Unix(),
|
||||
"timestamp": utils.GetCurrentTime().Unix(),
|
||||
"memory": gin.H{
|
||||
"alloc": m.Alloc,
|
||||
"total_alloc": m.TotalAlloc,
|
||||
@@ -81,8 +89,8 @@ func GetPerformanceStats(c *gin.Context) {
|
||||
func GetSystemInfo(c *gin.Context) {
|
||||
SuccessResponse(c, gin.H{
|
||||
"uptime": time.Since(startTime).String(),
|
||||
"start_time": startTime.Format("2006-01-02 15:04:05"),
|
||||
"version": "1.0.0",
|
||||
"start_time": utils.FormatTime(startTime, "2006-01-02 15:04:05"),
|
||||
"version": utils.Version,
|
||||
"environment": gin.H{
|
||||
"gin_mode": gin.Mode(),
|
||||
},
|
||||
@@ -90,4 +98,4 @@ func GetSystemInfo(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 记录启动时间
|
||||
var startTime = time.Now()
|
||||
var startTime = utils.GetCurrentTime()
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
|
||||
"github.com/ctwj/urldb/db/converter"
|
||||
"github.com/ctwj/urldb/db/dto"
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
"github.com/ctwj/urldb/db/repo"
|
||||
"github.com/ctwj/urldb/utils"
|
||||
|
||||
@@ -25,13 +26,13 @@ func NewSystemConfigHandler(systemConfigRepo repo.SystemConfigRepository) *Syste
|
||||
|
||||
// GetConfig 获取系统配置
|
||||
func (h *SystemConfigHandler) GetConfig(c *gin.Context) {
|
||||
config, err := h.systemConfigRepo.GetOrCreateDefault()
|
||||
configs, err := h.systemConfigRepo.GetOrCreateDefault()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "获取系统配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
configResponse := converter.SystemConfigToResponse(config)
|
||||
configResponse := converter.SystemConfigToResponse(configs)
|
||||
SuccessResponse(c, configResponse)
|
||||
}
|
||||
|
||||
@@ -71,39 +72,39 @@ func (h *SystemConfigHandler) UpdateConfig(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 转换为实体
|
||||
config := converter.RequestToSystemConfig(&req)
|
||||
if config == nil {
|
||||
configs := converter.RequestToSystemConfig(&req)
|
||||
if configs == nil {
|
||||
ErrorResponse(c, "数据转换失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// 保存配置
|
||||
err := h.systemConfigRepo.Upsert(config)
|
||||
err := h.systemConfigRepo.UpsertConfigs(configs)
|
||||
if err != nil {
|
||||
ErrorResponse(c, "保存系统配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// 返回更新后的配置
|
||||
updatedConfig, err := h.systemConfigRepo.FindFirst()
|
||||
updatedConfigs, err := h.systemConfigRepo.FindAll()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "获取更新后的配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
configResponse := converter.SystemConfigToResponse(updatedConfig)
|
||||
configResponse := converter.SystemConfigToResponse(updatedConfigs)
|
||||
SuccessResponse(c, configResponse)
|
||||
}
|
||||
|
||||
// GetSystemConfig 获取系统配置(使用全局repoManager)
|
||||
func GetSystemConfig(c *gin.Context) {
|
||||
config, err := repoManager.SystemConfigRepository.GetOrCreateDefault()
|
||||
configs, err := repoManager.SystemConfigRepository.GetOrCreateDefault()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "获取系统配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
configResponse := converter.SystemConfigToResponse(config)
|
||||
configResponse := converter.SystemConfigToResponse(configs)
|
||||
SuccessResponse(c, configResponse)
|
||||
}
|
||||
|
||||
@@ -143,14 +144,14 @@ func UpdateSystemConfig(c *gin.Context) {
|
||||
}
|
||||
|
||||
// 转换为实体
|
||||
config := converter.RequestToSystemConfig(&req)
|
||||
if config == nil {
|
||||
configs := converter.RequestToSystemConfig(&req)
|
||||
if configs == nil {
|
||||
ErrorResponse(c, "数据转换失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// 保存配置
|
||||
err := repoManager.SystemConfigRepository.Upsert(config)
|
||||
err := repoManager.SystemConfigRepository.UpsertConfigs(configs)
|
||||
if err != nil {
|
||||
ErrorResponse(c, "保存系统配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
@@ -164,18 +165,94 @@ func UpdateSystemConfig(c *gin.Context) {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if scheduler != nil {
|
||||
scheduler.UpdateSchedulerStatusWithAutoTransfer(req.AutoFetchHotDramaEnabled, req.AutoProcessReadyResources, req.AutoTransferEnabled)
|
||||
}
|
||||
|
||||
// 返回更新后的配置
|
||||
updatedConfig, err := repoManager.SystemConfigRepository.FindFirst()
|
||||
updatedConfigs, err := repoManager.SystemConfigRepository.FindAll()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "获取更新后的配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
configResponse := converter.SystemConfigToResponse(updatedConfig)
|
||||
configResponse := converter.SystemConfigToResponse(updatedConfigs)
|
||||
SuccessResponse(c, configResponse)
|
||||
}
|
||||
|
||||
// 新增:公开获取系统配置(不含api_token)
|
||||
func GetPublicSystemConfig(c *gin.Context) {
|
||||
configs, err := repoManager.SystemConfigRepository.GetOrCreateDefault()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "获取系统配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
configResponse := converter.SystemConfigToPublicResponse(configs)
|
||||
SuccessResponse(c, configResponse)
|
||||
}
|
||||
|
||||
// 新增:切换自动处理配置
|
||||
func ToggleAutoProcess(c *gin.Context) {
|
||||
var req struct {
|
||||
AutoProcessReadyResources bool `json:"auto_process_ready_resources"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
ErrorResponse(c, "请求参数错误", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// 获取当前配置
|
||||
configs, err := repoManager.SystemConfigRepository.GetOrCreateDefault()
|
||||
if err != nil {
|
||||
ErrorResponse(c, "获取系统配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// 更新自动处理配置
|
||||
for i, config := range configs {
|
||||
if config.Key == entity.ConfigKeyAutoProcessReadyResources {
|
||||
configs[i].Value = "true"
|
||||
if !req.AutoProcessReadyResources {
|
||||
configs[i].Value = "false"
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 保存配置
|
||||
err = repoManager.SystemConfigRepository.UpsertConfigs(configs)
|
||||
if err != nil {
|
||||
ErrorResponse(c, "保存系统配置失败", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
// 更新定时任务状态
|
||||
scheduler := utils.GetGlobalScheduler(
|
||||
repoManager.HotDramaRepository,
|
||||
repoManager.ReadyResourceRepository,
|
||||
repoManager.ResourceRepository,
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
if scheduler != nil {
|
||||
// 获取其他配置值
|
||||
autoFetchHotDrama, _ := repoManager.SystemConfigRepository.GetConfigBool(entity.ConfigKeyAutoFetchHotDramaEnabled)
|
||||
autoTransfer, _ := repoManager.SystemConfigRepository.GetConfigBool(entity.ConfigKeyAutoTransferEnabled)
|
||||
|
||||
scheduler.UpdateSchedulerStatusWithAutoTransfer(
|
||||
autoFetchHotDrama,
|
||||
req.AutoProcessReadyResources,
|
||||
autoTransfer,
|
||||
)
|
||||
}
|
||||
|
||||
// 返回更新后的配置
|
||||
configResponse := converter.SystemConfigToResponse(configs)
|
||||
SuccessResponse(c, configResponse)
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -27,7 +28,7 @@ func GetVersion(c *gin.Context) {
|
||||
Success: true,
|
||||
Data: versionInfo,
|
||||
Message: "版本信息获取成功",
|
||||
Time: time.Now(),
|
||||
Time: utils.GetCurrentTime(),
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response)
|
||||
@@ -43,7 +44,7 @@ func GetVersionString(c *gin.Context) {
|
||||
"version": versionString,
|
||||
},
|
||||
Message: "版本字符串获取成功",
|
||||
Time: time.Now(),
|
||||
Time: utils.GetCurrentTime(),
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response)
|
||||
@@ -59,7 +60,7 @@ func GetFullVersionInfo(c *gin.Context) {
|
||||
"version_info": fullInfo,
|
||||
},
|
||||
Message: "完整版本信息获取成功",
|
||||
Time: time.Now(),
|
||||
Time: utils.GetCurrentTime(),
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response)
|
||||
@@ -72,8 +73,8 @@ func CheckUpdate(c *gin.Context) {
|
||||
// 从GitHub API获取最新版本信息
|
||||
latestVersion, err := getLatestVersionFromGitHub()
|
||||
if err != nil {
|
||||
// 如果GitHub API失败,使用模拟数据
|
||||
latestVersion = "1.0.0"
|
||||
// 如果GitHub API失败,使用当前版本作为最新版本
|
||||
latestVersion = currentVersion
|
||||
}
|
||||
|
||||
hasUpdate := utils.IsVersionNewer(latestVersion, currentVersion)
|
||||
@@ -88,7 +89,7 @@ func CheckUpdate(c *gin.Context) {
|
||||
"update_url": "https://github.com/ctwj/urldb/releases/latest",
|
||||
},
|
||||
Message: "更新检查完成",
|
||||
Time: time.Now(),
|
||||
Time: utils.GetCurrentTime(),
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, response)
|
||||
@@ -96,10 +97,25 @@ func CheckUpdate(c *gin.Context) {
|
||||
|
||||
// getLatestVersionFromGitHub 从GitHub获取最新版本
|
||||
func getLatestVersionFromGitHub() (string, error) {
|
||||
// 使用GitHub API获取最新Release
|
||||
// 首先尝试从VERSION文件URL获取最新版本
|
||||
versionURL := "https://raw.githubusercontent.com/ctwj/urldb/refs/heads/main/VERSION"
|
||||
|
||||
resp, err := http.Get(versionURL)
|
||||
if err == nil && resp.StatusCode == http.StatusOK {
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err == nil {
|
||||
version := strings.TrimSpace(string(body))
|
||||
if version != "" {
|
||||
return version, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 如果VERSION文件获取失败,尝试GitHub API获取最新Release
|
||||
url := "https://api.github.com/repos/ctwj/urldb/releases/latest"
|
||||
|
||||
resp, err := http.Get(url)
|
||||
resp, err = http.Get(url)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
98
main.go
98
main.go
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/ctwj/urldb/utils"
|
||||
|
||||
"github.com/ctwj/urldb/db"
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
"github.com/ctwj/urldb/db/repo"
|
||||
"github.com/ctwj/urldb/handlers"
|
||||
"github.com/ctwj/urldb/middleware"
|
||||
@@ -28,6 +29,38 @@ func main() {
|
||||
utils.Info("未找到.env文件,使用默认配置")
|
||||
}
|
||||
|
||||
// 初始化时区设置
|
||||
utils.InitTimezone()
|
||||
|
||||
// 设置Gin运行模式
|
||||
ginMode := os.Getenv("GIN_MODE")
|
||||
if ginMode == "" {
|
||||
// 如果没有设置GIN_MODE,根据环境判断
|
||||
if os.Getenv("ENV") == "production" {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
utils.Info("设置Gin为Release模式")
|
||||
} else {
|
||||
gin.SetMode(gin.DebugMode)
|
||||
utils.Info("设置Gin为Debug模式")
|
||||
}
|
||||
} else {
|
||||
// 如果已经设置了GIN_MODE,根据值设置模式
|
||||
switch ginMode {
|
||||
case "release":
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
utils.Info("设置Gin为Release模式 (来自环境变量)")
|
||||
case "debug":
|
||||
gin.SetMode(gin.DebugMode)
|
||||
utils.Info("设置Gin为Debug模式 (来自环境变量)")
|
||||
case "test":
|
||||
gin.SetMode(gin.TestMode)
|
||||
utils.Info("设置Gin为Test模式 (来自环境变量)")
|
||||
default:
|
||||
gin.SetMode(gin.DebugMode)
|
||||
utils.Info("未知的GIN_MODE值: %s,使用Debug模式", ginMode)
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化数据库
|
||||
if err := db.InitDB(); err != nil {
|
||||
utils.Fatal("数据库连接失败: %v", err)
|
||||
@@ -44,36 +77,39 @@ func main() {
|
||||
repoManager.SystemConfigRepository,
|
||||
repoManager.PanRepository,
|
||||
repoManager.CksRepository,
|
||||
repoManager.TagRepository,
|
||||
repoManager.CategoryRepository,
|
||||
)
|
||||
|
||||
// 检查系统配置,决定是否启动各种自动任务
|
||||
systemConfig, err := repoManager.SystemConfigRepository.GetOrCreateDefault()
|
||||
autoProcessReadyResources, err := repoManager.SystemConfigRepository.GetConfigBool(entity.ConfigKeyAutoProcessReadyResources)
|
||||
if err != nil {
|
||||
utils.Error("获取系统配置失败: %v", err)
|
||||
utils.Error("获取自动处理待处理资源配置失败: %v", err)
|
||||
} else if autoProcessReadyResources {
|
||||
scheduler.StartReadyResourceScheduler()
|
||||
utils.Info("已启动待处理资源自动处理任务")
|
||||
} else {
|
||||
// 检查是否启动待处理资源自动处理任务
|
||||
if systemConfig.AutoProcessReadyResources {
|
||||
scheduler.StartReadyResourceScheduler()
|
||||
utils.Info("已启动待处理资源自动处理任务")
|
||||
} else {
|
||||
utils.Info("系统配置中自动处理待处理资源功能已禁用,跳过启动定时任务")
|
||||
}
|
||||
utils.Info("系统配置中自动处理待处理资源功能已禁用,跳过启动定时任务")
|
||||
}
|
||||
|
||||
// 检查是否启动热播剧自动拉取任务
|
||||
if systemConfig.AutoFetchHotDramaEnabled {
|
||||
scheduler.StartHotDramaScheduler()
|
||||
utils.Info("已启动热播剧自动拉取任务")
|
||||
} else {
|
||||
utils.Info("系统配置中自动拉取热播剧功能已禁用,跳过启动定时任务")
|
||||
}
|
||||
autoFetchHotDramaEnabled, err := repoManager.SystemConfigRepository.GetConfigBool(entity.ConfigKeyAutoFetchHotDramaEnabled)
|
||||
if err != nil {
|
||||
utils.Error("获取自动拉取热播剧配置失败: %v", err)
|
||||
} else if autoFetchHotDramaEnabled {
|
||||
scheduler.StartHotDramaScheduler()
|
||||
utils.Info("已启动热播剧自动拉取任务")
|
||||
} else {
|
||||
utils.Info("系统配置中自动拉取热播剧功能已禁用,跳过启动定时任务")
|
||||
}
|
||||
|
||||
// 检查是否启动自动转存任务
|
||||
if systemConfig.AutoTransferEnabled {
|
||||
scheduler.StartAutoTransferScheduler()
|
||||
utils.Info("已启动自动转存任务")
|
||||
} else {
|
||||
utils.Info("系统配置中自动转存功能已禁用,跳过启动定时任务")
|
||||
}
|
||||
autoTransferEnabled, err := repoManager.SystemConfigRepository.GetConfigBool(entity.ConfigKeyAutoTransferEnabled)
|
||||
if err != nil {
|
||||
utils.Error("获取自动转存配置失败: %v", err)
|
||||
} else if autoTransferEnabled {
|
||||
scheduler.StartAutoTransferScheduler()
|
||||
utils.Info("已启动自动转存任务")
|
||||
} else {
|
||||
utils.Info("系统配置中自动转存功能已禁用,跳过启动定时任务")
|
||||
}
|
||||
|
||||
// 创建Gin实例
|
||||
@@ -102,8 +138,6 @@ func main() {
|
||||
publicAPI := api.Group("/public")
|
||||
publicAPI.Use(middleware.PublicAPIAuth())
|
||||
{
|
||||
// 单个添加资源
|
||||
publicAPI.POST("/resources/add", publicAPIHandler.AddSingleResource)
|
||||
// 批量添加资源
|
||||
publicAPI.POST("/resources/batch-add", publicAPIHandler.AddBatchResources)
|
||||
// 资源搜索
|
||||
@@ -124,6 +158,8 @@ func main() {
|
||||
api.DELETE("/resources/:id", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.DeleteResource)
|
||||
api.GET("/resources/:id", handlers.GetResourceByID)
|
||||
api.GET("/resources/check-exists", handlers.CheckResourceExists)
|
||||
api.POST("/resources/:id/view", handlers.IncrementResourceViewCount)
|
||||
api.DELETE("/resources/batch", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.BatchDeleteResources)
|
||||
|
||||
// 分类管理
|
||||
api.GET("/categories", handlers.GetCategories)
|
||||
@@ -164,11 +200,15 @@ func main() {
|
||||
|
||||
// 待处理资源管理
|
||||
api.GET("/ready-resources", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.GetReadyResources)
|
||||
api.POST("/ready-resources", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.CreateReadyResource)
|
||||
api.POST("/ready-resources/batch", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.BatchCreateReadyResources)
|
||||
api.POST("/ready-resources/text", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.CreateReadyResourcesFromText)
|
||||
api.DELETE("/ready-resources/:id", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.DeleteReadyResource)
|
||||
api.DELETE("/ready-resources", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.ClearReadyResources)
|
||||
api.GET("/ready-resources/key/:key", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.GetReadyResourcesByKey)
|
||||
api.DELETE("/ready-resources/key/:key", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.DeleteReadyResourcesByKey)
|
||||
api.GET("/ready-resources/errors", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.GetReadyResourcesWithErrors)
|
||||
api.POST("/ready-resources/:id/clear-error", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.ClearErrorMsg)
|
||||
api.POST("/ready-resources/retry-failed", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.RetryFailedResources)
|
||||
|
||||
// 用户管理(仅管理员)
|
||||
api.GET("/users", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.GetUsers)
|
||||
@@ -183,11 +223,15 @@ func main() {
|
||||
api.GET("/search-stats/daily", handlers.GetDailyStats)
|
||||
api.GET("/search-stats/trend", handlers.GetSearchTrend)
|
||||
api.GET("/search-stats/keyword/:keyword/trend", handlers.GetKeywordTrend)
|
||||
api.POST("/search-stats", handlers.RecordSearch)
|
||||
api.POST("/search-stats/record", handlers.RecordSearch)
|
||||
api.GET("/search-stats/summary", handlers.GetSearchStatsSummary)
|
||||
|
||||
// 系统配置路由
|
||||
api.GET("/system/config", handlers.GetSystemConfig)
|
||||
api.GET("/system/config", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.GetSystemConfig)
|
||||
api.POST("/system/config", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.UpdateSystemConfig)
|
||||
api.POST("/system/config/toggle-auto-process", middleware.AuthMiddleware(), middleware.AdminMiddleware(), handlers.ToggleAutoProcess)
|
||||
api.GET("/public/system-config", handlers.GetPublicSystemConfig)
|
||||
|
||||
// 热播剧管理路由(查询接口无需认证)
|
||||
api.GET("/hot-dramas", handlers.GetHotDramaList)
|
||||
|
||||
@@ -94,9 +94,9 @@ func GenerateToken(user *entity.User) (string, error) {
|
||||
Username: user.Username,
|
||||
Role: user.Role,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(24 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
ExpiresAt: jwt.NewNumericDate(utils.GetCurrentTime().Add(30 * 24 * time.Hour)), // 30天有效期
|
||||
IssuedAt: jwt.NewNumericDate(utils.GetCurrentTime()),
|
||||
NotBefore: jwt.NewNumericDate(utils.GetCurrentTime()),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package middleware
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
"github.com/ctwj/urldb/db/repo"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -45,7 +46,8 @@ func PublicAPIAuth() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
config, err := repoManager.SystemConfigRepository.FindFirst()
|
||||
// 验证API Token
|
||||
apiTokenConfig, err := repoManager.SystemConfigRepository.GetConfigValue(entity.ConfigKeyApiToken)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
@@ -56,7 +58,7 @@ func PublicAPIAuth() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
if config.ApiToken == "" {
|
||||
if apiTokenConfig == "" {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||||
"success": false,
|
||||
"message": "API Token未配置",
|
||||
@@ -66,7 +68,7 @@ func PublicAPIAuth() gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
if config.ApiToken != apiToken {
|
||||
if apiTokenConfig != apiToken {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{
|
||||
"success": false,
|
||||
"message": "API Token无效",
|
||||
@@ -77,7 +79,18 @@ func PublicAPIAuth() gin.HandlerFunc {
|
||||
}
|
||||
|
||||
// 检查维护模式
|
||||
if config.MaintenanceMode {
|
||||
maintenanceMode, err := repoManager.SystemConfigRepository.GetConfigBool(entity.ConfigKeyMaintenanceMode)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{
|
||||
"success": false,
|
||||
"message": "系统配置获取失败",
|
||||
"code": 500,
|
||||
})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if maintenanceMode {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{
|
||||
"success": false,
|
||||
"message": "系统维护中,请稍后再试",
|
||||
|
||||
@@ -95,11 +95,37 @@ update_version_in_files() {
|
||||
echo -e " ✅ 更新 web/package.json"
|
||||
fi
|
||||
|
||||
# 更新useVersion.ts中的默认版本
|
||||
if [ -f "web/composables/useVersion.ts" ]; then
|
||||
# 使用更简单的模式匹配,先获取当前版本号
|
||||
current_use_version=$(grep -o "version: '[0-9]\+\.[0-9]\+\.[0-9]\+'" web/composables/useVersion.ts | head -1)
|
||||
if [ -n "$current_use_version" ]; then
|
||||
sed -i.bak "s/$current_use_version/version: '${new_version}'/" web/composables/useVersion.ts
|
||||
rm -f web/composables/useVersion.ts.bak
|
||||
echo -e " ✅ 更新 web/composables/useVersion.ts"
|
||||
else
|
||||
echo -e " ⚠️ 未找到useVersion.ts中的版本号"
|
||||
fi
|
||||
fi
|
||||
|
||||
# 更新Docker镜像标签
|
||||
if [ -f "docker-compose.yml" ]; then
|
||||
sed -i.bak "s/image:.*:.*/image: urldb:${new_version}/" docker-compose.yml
|
||||
# 获取当前镜像版本
|
||||
current_backend_version=$(grep -o "ctwj/urldb-backend:[0-9]\+\.[0-9]\+\.[0-9]\+" docker-compose.yml | head -1)
|
||||
current_frontend_version=$(grep -o "ctwj/urldb-frontend:[0-9]\+\.[0-9]\+\.[0-9]\+" docker-compose.yml | head -1)
|
||||
|
||||
if [ -n "$current_backend_version" ]; then
|
||||
sed -i.bak "s|$current_backend_version|ctwj/urldb-backend:${new_version}|" docker-compose.yml
|
||||
echo -e " ✅ 更新 backend 镜像: ${current_backend_version} -> ctwj/urldb-backend:${new_version}"
|
||||
fi
|
||||
|
||||
if [ -n "$current_frontend_version" ]; then
|
||||
sed -i.bak "s|$current_frontend_version|ctwj/urldb-frontend:${new_version}|" docker-compose.yml
|
||||
echo -e " ✅ 更新 frontend 镜像: ${current_frontend_version} -> ctwj/urldb-frontend:${new_version}"
|
||||
fi
|
||||
|
||||
rm -f docker-compose.yml.bak
|
||||
echo -e " ✅ 更新 docker-compose.yml"
|
||||
echo -e " ✅ 更新 docker-compose.yml 完成"
|
||||
fi
|
||||
|
||||
# 更新README中的版本信息
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
// 测试新的AdminHeader样式是否与首页完全对齐
|
||||
const testAdminHeaderStyle = async () => {
|
||||
console.log('测试新的AdminHeader样式是否与首页完全对齐...')
|
||||
|
||||
// 测试前端页面AdminHeader
|
||||
console.log('\n1. 测试前端页面AdminHeader:')
|
||||
|
||||
const adminPages = [
|
||||
{ name: '管理后台', url: 'http://localhost:3000/admin' },
|
||||
{ name: '用户管理', url: 'http://localhost:3000/users' },
|
||||
{ name: '分类管理', url: 'http://localhost:3000/categories' },
|
||||
{ name: '标签管理', url: 'http://localhost:3000/tags' },
|
||||
{ name: '系统配置', url: 'http://localhost:3000/system-config' },
|
||||
{ name: '资源管理', url: 'http://localhost:3000/resources' }
|
||||
]
|
||||
|
||||
for (const page of adminPages) {
|
||||
try {
|
||||
const response = await fetch(page.url)
|
||||
const html = await response.text()
|
||||
|
||||
console.log(`\n${page.name}页面:`)
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
// 检查是否包含AdminHeader组件
|
||||
if (html.includes('AdminHeader')) {
|
||||
console.log('✅ 包含AdminHeader组件')
|
||||
} else {
|
||||
console.log('❌ 未找到AdminHeader组件')
|
||||
}
|
||||
|
||||
// 检查是否包含首页样式(深色背景)
|
||||
if (html.includes('bg-slate-800') && html.includes('dark:bg-gray-800')) {
|
||||
console.log('✅ 包含首页样式(深色背景)')
|
||||
} else {
|
||||
console.log('❌ 未找到首页样式')
|
||||
}
|
||||
|
||||
// 检查是否包含首页标题样式
|
||||
if (html.includes('text-2xl sm:text-3xl font-bold mb-4')) {
|
||||
console.log('✅ 包含首页标题样式')
|
||||
} else {
|
||||
console.log('❌ 未找到首页标题样式')
|
||||
}
|
||||
|
||||
// 检查是否包含n-button组件(与首页一致)
|
||||
if (html.includes('n-button') && html.includes('size="tiny"') && html.includes('type="tertiary"')) {
|
||||
console.log('✅ 包含n-button组件(与首页一致)')
|
||||
} else {
|
||||
console.log('❌ 未找到n-button组件')
|
||||
}
|
||||
|
||||
// 检查是否包含右上角绝对定位的按钮
|
||||
if (html.includes('absolute right-4 top-4')) {
|
||||
console.log('✅ 包含右上角绝对定位的按钮')
|
||||
} else {
|
||||
console.log('❌ 未找到右上角绝对定位的按钮')
|
||||
}
|
||||
|
||||
// 检查是否包含首页、添加、退出按钮
|
||||
if (html.includes('fa-home') && html.includes('fa-plus') && html.includes('fa-sign-out-alt')) {
|
||||
console.log('✅ 包含首页、添加、退出按钮')
|
||||
} else {
|
||||
console.log('❌ 未找到完整的按钮组')
|
||||
}
|
||||
|
||||
// 检查是否包含用户信息
|
||||
if (html.includes('欢迎') && html.includes('管理员')) {
|
||||
console.log('✅ 包含用户信息')
|
||||
} else {
|
||||
console.log('❌ 未找到用户信息')
|
||||
}
|
||||
|
||||
// 检查是否包含移动端适配
|
||||
if (html.includes('sm:hidden') && html.includes('hidden sm:flex')) {
|
||||
console.log('✅ 包含移动端适配')
|
||||
} else {
|
||||
console.log('❌ 未找到移动端适配')
|
||||
}
|
||||
|
||||
// 检查是否不包含导航链接(除了首页和添加资源)
|
||||
if (!html.includes('用户管理') && !html.includes('分类管理') && !html.includes('标签管理')) {
|
||||
console.log('✅ 不包含导航链接(符合预期)')
|
||||
} else {
|
||||
console.log('❌ 包含导航链接(不符合预期)')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ ${page.name}页面测试失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试首页样式对比
|
||||
console.log('\n2. 测试首页样式对比:')
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:3000/')
|
||||
const html = await response.text()
|
||||
|
||||
console.log('首页页面:')
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
// 检查首页是否包含相同的样式
|
||||
if (html.includes('bg-slate-800') && html.includes('dark:bg-gray-800')) {
|
||||
console.log('✅ 首页包含相同的深色背景样式')
|
||||
} else {
|
||||
console.log('❌ 首页不包含相同的深色背景样式')
|
||||
}
|
||||
|
||||
// 检查首页是否包含相同的布局结构
|
||||
if (html.includes('text-2xl sm:text-3xl font-bold mb-4')) {
|
||||
console.log('✅ 首页包含相同的标题样式')
|
||||
} else {
|
||||
console.log('❌ 首页不包含相同的标题样式')
|
||||
}
|
||||
|
||||
// 检查首页是否包含相同的n-button样式
|
||||
if (html.includes('n-button') && html.includes('size="tiny"') && html.includes('type="tertiary"')) {
|
||||
console.log('✅ 首页包含相同的n-button样式')
|
||||
} else {
|
||||
console.log('❌ 首页不包含相同的n-button样式')
|
||||
}
|
||||
|
||||
// 检查首页是否包含相同的绝对定位
|
||||
if (html.includes('absolute right-4 top-0')) {
|
||||
console.log('✅ 首页包含相同的绝对定位')
|
||||
} else {
|
||||
console.log('❌ 首页不包含相同的绝对定位')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 首页测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试系统配置API
|
||||
console.log('\n3. 测试系统配置API:')
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:8080/api/system-config')
|
||||
const data = await response.json()
|
||||
|
||||
console.log('系统配置API响应:')
|
||||
console.log(`状态: ${data.success ? '✅ 成功' : '❌ 失败'}`)
|
||||
if (data.success) {
|
||||
console.log(`网站标题: ${data.data?.site_title || 'N/A'}`)
|
||||
console.log(`版权信息: ${data.data?.copyright || 'N/A'}`)
|
||||
}
|
||||
|
||||
if (data.success) {
|
||||
console.log('✅ 系统配置API测试通过')
|
||||
} else {
|
||||
console.log('❌ 系统配置API测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 系统配置API测试失败:', error.message)
|
||||
}
|
||||
|
||||
console.log('\n✅ AdminHeader样式测试完成')
|
||||
console.log('\n总结:')
|
||||
console.log('- ✅ AdminHeader样式与首页完全一致')
|
||||
console.log('- ✅ 使用相同的深色背景和圆角设计')
|
||||
console.log('- ✅ 使用相同的n-button组件样式')
|
||||
console.log('- ✅ 按钮位于右上角绝对定位')
|
||||
console.log('- ✅ 包含首页、添加、退出按钮')
|
||||
console.log('- ✅ 包含用户信息和角色显示')
|
||||
console.log('- ✅ 响应式设计,适配移动端')
|
||||
console.log('- ✅ 移除了导航链接,只保留必要操作')
|
||||
console.log('- ✅ 系统配置集成正常')
|
||||
}
|
||||
|
||||
// 运行测试
|
||||
testAdminHeaderStyle()
|
||||
@@ -1,188 +0,0 @@
|
||||
// 测试AdminHeader组件和版本显示功能
|
||||
const testAdminHeader = async () => {
|
||||
console.log('测试AdminHeader组件和版本显示功能...')
|
||||
|
||||
const { exec } = require('child_process')
|
||||
const { promisify } = require('util')
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
// 测试后端版本接口
|
||||
console.log('\n1. 测试后端版本接口:')
|
||||
|
||||
try {
|
||||
const { stdout: versionOutput } = await execAsync('curl -s http://localhost:8080/api/version')
|
||||
const versionData = JSON.parse(versionOutput)
|
||||
|
||||
console.log('版本接口响应:')
|
||||
console.log(`状态: ${versionData.success ? '✅ 成功' : '❌ 失败'}`)
|
||||
console.log(`版本号: ${versionData.data.version}`)
|
||||
console.log(`Git提交: ${versionData.data.git_commit}`)
|
||||
console.log(`构建时间: ${versionData.data.build_time}`)
|
||||
|
||||
if (versionData.success) {
|
||||
console.log('✅ 后端版本接口测试通过')
|
||||
} else {
|
||||
console.log('❌ 后端版本接口测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 后端版本接口测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试版本字符串接口
|
||||
console.log('\n2. 测试版本字符串接口:')
|
||||
|
||||
try {
|
||||
const { stdout: versionStringOutput } = await execAsync('curl -s http://localhost:8080/api/version/string')
|
||||
const versionStringData = JSON.parse(versionStringOutput)
|
||||
|
||||
console.log('版本字符串接口响应:')
|
||||
console.log(`状态: ${versionStringData.success ? '✅ 成功' : '❌ 失败'}`)
|
||||
console.log(`版本字符串: ${versionStringData.data.version}`)
|
||||
|
||||
if (versionStringData.success) {
|
||||
console.log('✅ 版本字符串接口测试通过')
|
||||
} else {
|
||||
console.log('❌ 版本字符串接口测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 版本字符串接口测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试完整版本信息接口
|
||||
console.log('\n3. 测试完整版本信息接口:')
|
||||
|
||||
try {
|
||||
const { stdout: fullVersionOutput } = await execAsync('curl -s http://localhost:8080/api/version/full')
|
||||
const fullVersionData = JSON.parse(fullVersionOutput)
|
||||
|
||||
console.log('完整版本信息接口响应:')
|
||||
console.log(`状态: ${fullVersionData.success ? '✅ 成功' : '❌ 失败'}`)
|
||||
if (fullVersionData.success) {
|
||||
console.log(`版本信息:`, JSON.stringify(fullVersionData.data.version_info, null, 2))
|
||||
}
|
||||
|
||||
if (fullVersionData.success) {
|
||||
console.log('✅ 完整版本信息接口测试通过')
|
||||
} else {
|
||||
console.log('❌ 完整版本信息接口测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 完整版本信息接口测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试版本更新检查接口
|
||||
console.log('\n4. 测试版本更新检查接口:')
|
||||
|
||||
try {
|
||||
const { stdout: updateCheckOutput } = await execAsync('curl -s http://localhost:8080/api/version/check-update')
|
||||
const updateCheckData = JSON.parse(updateCheckOutput)
|
||||
|
||||
console.log('版本更新检查接口响应:')
|
||||
console.log(`状态: ${updateCheckData.success ? '✅ 成功' : '❌ 失败'}`)
|
||||
if (updateCheckData.success) {
|
||||
console.log(`当前版本: ${updateCheckData.data.current_version}`)
|
||||
console.log(`最新版本: ${updateCheckData.data.latest_version}`)
|
||||
console.log(`有更新: ${updateCheckData.data.has_update}`)
|
||||
console.log(`下载链接: ${updateCheckData.data.download_url || 'N/A'}`)
|
||||
}
|
||||
|
||||
if (updateCheckData.success) {
|
||||
console.log('✅ 版本更新检查接口测试通过')
|
||||
} else {
|
||||
console.log('❌ 版本更新检查接口测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 版本更新检查接口测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试前端页面
|
||||
console.log('\n5. 测试前端页面:')
|
||||
|
||||
const testPages = [
|
||||
{ name: '管理后台', url: 'http://localhost:3000/admin' },
|
||||
{ name: '用户管理', url: 'http://localhost:3000/users' },
|
||||
{ name: '分类管理', url: 'http://localhost:3000/categories' },
|
||||
{ name: '标签管理', url: 'http://localhost:3000/tags' },
|
||||
{ name: '系统配置', url: 'http://localhost:3000/system-config' },
|
||||
{ name: '资源管理', url: 'http://localhost:3000/resources' }
|
||||
]
|
||||
|
||||
for (const page of testPages) {
|
||||
try {
|
||||
const response = await fetch(page.url)
|
||||
const html = await response.text()
|
||||
|
||||
console.log(`\n${page.name}页面:`)
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
// 检查是否包含AdminHeader组件
|
||||
if (html.includes('AdminHeader') || html.includes('版本管理')) {
|
||||
console.log('✅ 包含AdminHeader组件')
|
||||
} else {
|
||||
console.log('❌ 未找到AdminHeader组件')
|
||||
}
|
||||
|
||||
// 检查是否包含版本信息
|
||||
if (html.includes('版本') || html.includes('version')) {
|
||||
console.log('✅ 包含版本信息')
|
||||
} else {
|
||||
console.log('❌ 未找到版本信息')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ ${page.name}页面测试失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试版本管理脚本
|
||||
console.log('\n6. 测试版本管理脚本:')
|
||||
|
||||
try {
|
||||
const { stdout: scriptHelp } = await execAsync('./scripts/version.sh help')
|
||||
console.log('版本管理脚本帮助信息:')
|
||||
console.log(scriptHelp)
|
||||
|
||||
const { stdout: scriptShow } = await execAsync('./scripts/version.sh show')
|
||||
console.log('当前版本信息:')
|
||||
console.log(scriptShow)
|
||||
|
||||
console.log('✅ 版本管理脚本测试通过')
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 版本管理脚本测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试Git标签
|
||||
console.log('\n7. 测试Git标签:')
|
||||
|
||||
try {
|
||||
const { stdout: tagOutput } = await execAsync('git tag -l')
|
||||
console.log('当前Git标签:')
|
||||
console.log(tagOutput || '暂无标签')
|
||||
|
||||
const { stdout: logOutput } = await execAsync('git log --oneline -3')
|
||||
console.log('最近3次提交:')
|
||||
console.log(logOutput)
|
||||
|
||||
console.log('✅ Git标签测试通过')
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Git标签测试失败:', error.message)
|
||||
}
|
||||
|
||||
console.log('\n✅ AdminHeader组件和版本显示功能测试完成')
|
||||
console.log('\n总结:')
|
||||
console.log('- ✅ 后端版本接口正常工作')
|
||||
console.log('- ✅ 前端AdminHeader组件已集成')
|
||||
console.log('- ✅ 版本信息在管理页面右下角显示')
|
||||
console.log('- ✅ 首页已移除版本显示')
|
||||
console.log('- ✅ 版本管理脚本功能完整')
|
||||
console.log('- ✅ Git标签管理正常')
|
||||
}
|
||||
|
||||
// 运行测试
|
||||
testAdminHeader()
|
||||
@@ -1,155 +0,0 @@
|
||||
// 测试admin layout功能
|
||||
const testAdminLayout = async () => {
|
||||
console.log('测试admin layout功能...')
|
||||
|
||||
// 测试前端页面admin layout
|
||||
console.log('\n1. 测试前端页面admin layout:')
|
||||
|
||||
const adminPages = [
|
||||
{ name: '管理后台', url: 'http://localhost:3000/admin' },
|
||||
{ name: '用户管理', url: 'http://localhost:3000/users' },
|
||||
{ name: '分类管理', url: 'http://localhost:3000/categories' },
|
||||
{ name: '标签管理', url: 'http://localhost:3000/tags' },
|
||||
{ name: '系统配置', url: 'http://localhost:3000/system-config' },
|
||||
{ name: '资源管理', url: 'http://localhost:3000/resources' }
|
||||
]
|
||||
|
||||
for (const page of adminPages) {
|
||||
try {
|
||||
const response = await fetch(page.url)
|
||||
const html = await response.text()
|
||||
|
||||
console.log(`\n${page.name}页面:`)
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
// 检查是否包含AdminHeader组件
|
||||
if (html.includes('AdminHeader')) {
|
||||
console.log('✅ 包含AdminHeader组件')
|
||||
} else {
|
||||
console.log('❌ 未找到AdminHeader组件')
|
||||
}
|
||||
|
||||
// 检查是否包含AppFooter组件
|
||||
if (html.includes('AppFooter')) {
|
||||
console.log('✅ 包含AppFooter组件')
|
||||
} else {
|
||||
console.log('❌ 未找到AppFooter组件')
|
||||
}
|
||||
|
||||
// 检查是否包含admin layout的样式
|
||||
if (html.includes('bg-gray-50 dark:bg-gray-900')) {
|
||||
console.log('✅ 包含admin layout样式')
|
||||
} else {
|
||||
console.log('❌ 未找到admin layout样式')
|
||||
}
|
||||
|
||||
// 检查是否包含页面加载状态
|
||||
if (html.includes('正在加载') || html.includes('初始化管理后台')) {
|
||||
console.log('✅ 包含页面加载状态')
|
||||
} else {
|
||||
console.log('❌ 未找到页面加载状态')
|
||||
}
|
||||
|
||||
// 检查是否包含max-w-7xl mx-auto容器
|
||||
if (html.includes('max-w-7xl mx-auto')) {
|
||||
console.log('✅ 包含标准容器布局')
|
||||
} else {
|
||||
console.log('❌ 未找到标准容器布局')
|
||||
}
|
||||
|
||||
// 检查是否不包含重复的布局代码
|
||||
const adminHeaderCount = (html.match(/AdminHeader/g) || []).length
|
||||
if (adminHeaderCount === 1) {
|
||||
console.log('✅ AdminHeader组件只出现一次(无重复)')
|
||||
} else {
|
||||
console.log(`❌ AdminHeader组件出现${adminHeaderCount}次(可能有重复)`)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ ${page.name}页面测试失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试admin layout文件是否存在
|
||||
console.log('\n2. 测试admin layout文件:')
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:3000/layouts/admin.vue')
|
||||
console.log('admin layout文件状态:', response.status)
|
||||
|
||||
if (response.status === 200) {
|
||||
console.log('✅ admin layout文件存在')
|
||||
} else {
|
||||
console.log('❌ admin layout文件不存在或无法访问')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ admin layout文件测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试definePageMeta是否正确设置
|
||||
console.log('\n3. 测试definePageMeta设置:')
|
||||
|
||||
const pagesWithLayout = [
|
||||
{ name: '管理后台', file: 'web/pages/admin.vue' },
|
||||
{ name: '用户管理', file: 'web/pages/users.vue' },
|
||||
{ name: '分类管理', file: 'web/pages/categories.vue' }
|
||||
]
|
||||
|
||||
for (const page of pagesWithLayout) {
|
||||
try {
|
||||
const fs = require('fs')
|
||||
const content = fs.readFileSync(page.file, 'utf8')
|
||||
|
||||
if (content.includes("definePageMeta({") && content.includes("layout: 'admin'")) {
|
||||
console.log(`✅ ${page.name}页面正确设置了admin layout`)
|
||||
} else {
|
||||
console.log(`❌ ${page.name}页面未正确设置admin layout`)
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ ${page.name}页面文件读取失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试首页不使用admin layout
|
||||
console.log('\n4. 测试首页不使用admin layout:')
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:3000/')
|
||||
const html = await response.text()
|
||||
|
||||
console.log('首页页面:')
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
// 检查首页是否不包含AdminHeader
|
||||
if (!html.includes('AdminHeader')) {
|
||||
console.log('✅ 首页不包含AdminHeader(符合预期)')
|
||||
} else {
|
||||
console.log('❌ 首页包含AdminHeader(不符合预期)')
|
||||
}
|
||||
|
||||
// 检查首页是否使用默认layout
|
||||
if (html.includes('bg-gray-50 dark:bg-gray-900') && html.includes('AppFooter')) {
|
||||
console.log('✅ 首页使用默认layout')
|
||||
} else {
|
||||
console.log('❌ 首页可能使用了错误的layout')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 首页测试失败:', error.message)
|
||||
}
|
||||
|
||||
console.log('\n✅ admin layout测试完成')
|
||||
console.log('\n总结:')
|
||||
console.log('- ✅ 创建了admin layout文件')
|
||||
console.log('- ✅ 管理页面使用admin layout')
|
||||
console.log('- ✅ 移除了重复的布局代码')
|
||||
console.log('- ✅ 统一了管理页面的样式和结构')
|
||||
console.log('- ✅ 首页继续使用默认layout')
|
||||
console.log('- ✅ 页面加载状态和错误处理统一')
|
||||
console.log('- ✅ 响应式设计和容器布局统一')
|
||||
}
|
||||
|
||||
// 运行测试
|
||||
testAdminLayout()
|
||||
@@ -1,140 +0,0 @@
|
||||
// 测试Footer中的版本信息显示
|
||||
const testFooterVersion = async () => {
|
||||
console.log('测试Footer中的版本信息显示...')
|
||||
|
||||
const { exec } = require('child_process')
|
||||
const { promisify } = require('util')
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
// 测试后端版本接口
|
||||
console.log('\n1. 测试后端版本接口:')
|
||||
|
||||
try {
|
||||
const { stdout: versionOutput } = await execAsync('curl -s http://localhost:8080/api/version')
|
||||
const versionData = JSON.parse(versionOutput)
|
||||
|
||||
console.log('版本接口响应:')
|
||||
console.log(`状态: ${versionData.success ? '✅ 成功' : '❌ 失败'}`)
|
||||
console.log(`版本号: ${versionData.data.version}`)
|
||||
console.log(`Git提交: ${versionData.data.git_commit}`)
|
||||
console.log(`构建时间: ${versionData.data.build_time}`)
|
||||
|
||||
if (versionData.success) {
|
||||
console.log('✅ 后端版本接口测试通过')
|
||||
} else {
|
||||
console.log('❌ 后端版本接口测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 后端版本接口测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试前端页面Footer
|
||||
console.log('\n2. 测试前端页面Footer:')
|
||||
|
||||
const testPages = [
|
||||
{ name: '首页', url: 'http://localhost:3000/' },
|
||||
{ name: '热播剧', url: 'http://localhost:3000/hot-dramas' },
|
||||
{ name: '系统监控', url: 'http://localhost:3000/monitor' },
|
||||
{ name: 'API文档', url: 'http://localhost:3000/api-docs' }
|
||||
]
|
||||
|
||||
for (const page of testPages) {
|
||||
try {
|
||||
const response = await fetch(page.url)
|
||||
const html = await response.text()
|
||||
|
||||
console.log(`\n${page.name}页面:`)
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
// 检查是否包含AppFooter组件
|
||||
if (html.includes('AppFooter')) {
|
||||
console.log('✅ 包含AppFooter组件')
|
||||
} else {
|
||||
console.log('❌ 未找到AppFooter组件')
|
||||
}
|
||||
|
||||
// 检查是否包含版本信息
|
||||
if (html.includes('v1.0.0') || html.includes('version')) {
|
||||
console.log('✅ 包含版本信息')
|
||||
} else {
|
||||
console.log('❌ 未找到版本信息')
|
||||
}
|
||||
|
||||
// 检查是否包含版权信息
|
||||
if (html.includes('© 2025') || html.includes('网盘资源数据库')) {
|
||||
console.log('✅ 包含版权信息')
|
||||
} else {
|
||||
console.log('❌ 未找到版权信息')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ ${page.name}页面测试失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试管理页面(应该没有版本信息)
|
||||
console.log('\n3. 测试管理页面(应该没有版本信息):')
|
||||
|
||||
const adminPages = [
|
||||
{ name: '管理后台', url: 'http://localhost:3000/admin' },
|
||||
{ name: '用户管理', url: 'http://localhost:3000/users' },
|
||||
{ name: '分类管理', url: 'http://localhost:3000/categories' },
|
||||
{ name: '标签管理', url: 'http://localhost:3000/tags' },
|
||||
{ name: '系统配置', url: 'http://localhost:3000/system-config' },
|
||||
{ name: '资源管理', url: 'http://localhost:3000/resources' }
|
||||
]
|
||||
|
||||
for (const page of adminPages) {
|
||||
try {
|
||||
const response = await fetch(page.url)
|
||||
const html = await response.text()
|
||||
|
||||
console.log(`\n${page.name}页面:`)
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
// 检查是否包含AdminHeader组件
|
||||
if (html.includes('AdminHeader')) {
|
||||
console.log('✅ 包含AdminHeader组件')
|
||||
} else {
|
||||
console.log('❌ 未找到AdminHeader组件')
|
||||
}
|
||||
|
||||
// 检查是否不包含版本信息(管理页面应该没有版本显示)
|
||||
if (!html.includes('v1.0.0') && !html.includes('version')) {
|
||||
console.log('✅ 不包含版本信息(符合预期)')
|
||||
} else {
|
||||
console.log('❌ 包含版本信息(不符合预期)')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ ${page.name}页面测试失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试版本管理脚本
|
||||
console.log('\n4. 测试版本管理脚本:')
|
||||
|
||||
try {
|
||||
const { stdout: scriptShow } = await execAsync('./scripts/version.sh show')
|
||||
console.log('当前版本信息:')
|
||||
console.log(scriptShow)
|
||||
|
||||
console.log('✅ 版本管理脚本测试通过')
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 版本管理脚本测试失败:', error.message)
|
||||
}
|
||||
|
||||
console.log('\n✅ Footer版本信息显示测试完成')
|
||||
console.log('\n总结:')
|
||||
console.log('- ✅ 后端版本接口正常工作')
|
||||
console.log('- ✅ 前端AppFooter组件已集成')
|
||||
console.log('- ✅ 版本信息在Footer中显示')
|
||||
console.log('- ✅ 管理页面已移除版本显示')
|
||||
console.log('- ✅ 版本信息显示格式:版权信息 | v版本号')
|
||||
console.log('- ✅ 版本管理脚本功能完整')
|
||||
}
|
||||
|
||||
// 运行测试
|
||||
testFooterVersion()
|
||||
@@ -1,123 +0,0 @@
|
||||
// 测试GitHub版本系统
|
||||
const testGitHubVersion = async () => {
|
||||
console.log('测试GitHub版本系统...')
|
||||
|
||||
const { exec } = require('child_process')
|
||||
const { promisify } = require('util')
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
// 测试版本管理脚本
|
||||
console.log('\n1. 测试版本管理脚本:')
|
||||
|
||||
try {
|
||||
// 显示版本信息
|
||||
const { stdout: showOutput } = await execAsync('./scripts/version.sh show')
|
||||
console.log('版本信息:')
|
||||
console.log(showOutput)
|
||||
|
||||
// 显示帮助信息
|
||||
const { stdout: helpOutput } = await execAsync('./scripts/version.sh help')
|
||||
console.log('帮助信息:')
|
||||
console.log(helpOutput)
|
||||
|
||||
console.log('✅ 版本管理脚本测试通过')
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 版本管理脚本测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试版本API接口
|
||||
console.log('\n2. 测试版本API接口:')
|
||||
|
||||
const baseUrl = 'http://localhost:8080'
|
||||
const testEndpoints = [
|
||||
'/api/version',
|
||||
'/api/version/string',
|
||||
'/api/version/full',
|
||||
'/api/version/check-update'
|
||||
]
|
||||
|
||||
for (const endpoint of testEndpoints) {
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}${endpoint}`)
|
||||
const data = await response.json()
|
||||
|
||||
console.log(`\n接口: ${endpoint}`)
|
||||
console.log(`状态码: ${response.status}`)
|
||||
console.log(`响应:`, JSON.stringify(data, null, 2))
|
||||
|
||||
if (data.success) {
|
||||
console.log('✅ 接口测试通过')
|
||||
} else {
|
||||
console.log('❌ 接口测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ 接口 ${endpoint} 测试失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试GitHub版本检查
|
||||
console.log('\n3. 测试GitHub版本检查:')
|
||||
|
||||
try {
|
||||
const response = await fetch('https://api.github.com/repos/ctwj/urldb/releases/latest')
|
||||
const data = await response.json()
|
||||
|
||||
console.log('GitHub API响应:')
|
||||
console.log(`状态码: ${response.status}`)
|
||||
console.log(`最新版本: ${data.tag_name || 'N/A'}`)
|
||||
console.log(`发布日期: ${data.published_at || 'N/A'}`)
|
||||
|
||||
if (data.tag_name) {
|
||||
console.log('✅ GitHub版本检查测试通过')
|
||||
} else {
|
||||
console.log('⚠️ GitHub上暂无Release')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ GitHub版本检查测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试前端版本页面
|
||||
console.log('\n4. 测试前端版本页面:')
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:3000/version')
|
||||
const html = await response.text()
|
||||
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
if (html.includes('版本信息') && html.includes('VersionInfo')) {
|
||||
console.log('✅ 前端版本页面测试通过')
|
||||
} else {
|
||||
console.log('❌ 前端版本页面测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 前端版本页面测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试Git标签
|
||||
console.log('\n5. 测试Git标签:')
|
||||
|
||||
try {
|
||||
const { stdout: tagOutput } = await execAsync('git tag -l')
|
||||
console.log('当前Git标签:')
|
||||
console.log(tagOutput || '暂无标签')
|
||||
|
||||
const { stdout: logOutput } = await execAsync('git log --oneline -5')
|
||||
console.log('最近5次提交:')
|
||||
console.log(logOutput)
|
||||
|
||||
console.log('✅ Git标签测试通过')
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ Git标签测试失败:', error.message)
|
||||
}
|
||||
|
||||
console.log('\n✅ GitHub版本系统测试完成')
|
||||
}
|
||||
|
||||
// 运行测试
|
||||
testGitHubVersion()
|
||||
@@ -1,83 +0,0 @@
|
||||
// 测试版本系统
|
||||
const testVersionSystem = async () => {
|
||||
console.log('测试版本系统...')
|
||||
|
||||
const baseUrl = 'http://localhost:8080'
|
||||
|
||||
// 测试版本API接口
|
||||
const testEndpoints = [
|
||||
'/api/version',
|
||||
'/api/version/string',
|
||||
'/api/version/full',
|
||||
'/api/version/check-update'
|
||||
]
|
||||
|
||||
for (const endpoint of testEndpoints) {
|
||||
console.log(`\n测试接口: ${endpoint}`)
|
||||
|
||||
try {
|
||||
const response = await fetch(`${baseUrl}${endpoint}`)
|
||||
const data = await response.json()
|
||||
|
||||
console.log(`状态码: ${response.status}`)
|
||||
console.log(`响应:`, JSON.stringify(data, null, 2))
|
||||
|
||||
if (data.success) {
|
||||
console.log('✅ 接口测试通过')
|
||||
} else {
|
||||
console.log('❌ 接口测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error(`❌ 请求失败:`, error.message)
|
||||
}
|
||||
}
|
||||
|
||||
// 测试版本管理脚本
|
||||
console.log('\n测试版本管理脚本...')
|
||||
|
||||
const { exec } = require('child_process')
|
||||
const { promisify } = require('util')
|
||||
const execAsync = promisify(exec)
|
||||
|
||||
try {
|
||||
// 显示版本信息
|
||||
const { stdout: showOutput } = await execAsync('./scripts/version.sh show')
|
||||
console.log('版本信息:')
|
||||
console.log(showOutput)
|
||||
|
||||
// 生成版本信息文件
|
||||
const { stdout: updateOutput } = await execAsync('./scripts/version.sh update')
|
||||
console.log('生成版本信息文件:')
|
||||
console.log(updateOutput)
|
||||
|
||||
console.log('✅ 版本管理脚本测试通过')
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 版本管理脚本测试失败:', error.message)
|
||||
}
|
||||
|
||||
// 测试前端版本页面
|
||||
console.log('\n测试前端版本页面...')
|
||||
|
||||
try {
|
||||
const response = await fetch('http://localhost:3000/version')
|
||||
const html = await response.text()
|
||||
|
||||
console.log(`状态码: ${response.status}`)
|
||||
|
||||
if (html.includes('版本信息') && html.includes('VersionInfo')) {
|
||||
console.log('✅ 前端版本页面测试通过')
|
||||
} else {
|
||||
console.log('❌ 前端版本页面测试失败')
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('❌ 前端版本页面测试失败:', error.message)
|
||||
}
|
||||
|
||||
console.log('\n✅ 版本系统测试完成')
|
||||
}
|
||||
|
||||
// 运行测试
|
||||
testVersionSystem()
|
||||
153
utils/errors.go
Normal file
153
utils/errors.go
Normal file
@@ -0,0 +1,153 @@
|
||||
package utils
|
||||
|
||||
import "fmt"
|
||||
|
||||
// ErrorType 错误类型枚举
|
||||
type ErrorType string
|
||||
|
||||
const (
|
||||
// ErrorTypeUnsupportedLink 不支持的链接
|
||||
ErrorTypeUnsupportedLink ErrorType = "UNSUPPORTED_LINK"
|
||||
// ErrorTypeInvalidLink 无效链接
|
||||
ErrorTypeInvalidLink ErrorType = "INVALID_LINK"
|
||||
// ErrorTypeNoAccount 没有可用账号
|
||||
ErrorTypeNoAccount ErrorType = "NO_ACCOUNT"
|
||||
// ErrorTypeNoValidAccount 没有有效账号
|
||||
ErrorTypeNoValidAccount ErrorType = "NO_VALID_ACCOUNT"
|
||||
// ErrorTypeServiceCreation 服务创建失败
|
||||
ErrorTypeServiceCreation ErrorType = "SERVICE_CREATION_FAILED"
|
||||
// ErrorTypeTransferFailed 转存失败
|
||||
ErrorTypeTransferFailed ErrorType = "TRANSFER_FAILED"
|
||||
// ErrorTypeTagProcessing 标签处理失败
|
||||
ErrorTypeTagProcessing ErrorType = "TAG_PROCESSING_FAILED"
|
||||
// ErrorTypeCategoryProcessing 分类处理失败
|
||||
ErrorTypeCategoryProcessing ErrorType = "CATEGORY_PROCESSING_FAILED"
|
||||
// ErrorTypeResourceSave 资源保存失败
|
||||
ErrorTypeResourceSave ErrorType = "RESOURCE_SAVE_FAILED"
|
||||
// ErrorTypePlatformNotFound 平台未找到
|
||||
ErrorTypePlatformNotFound ErrorType = "PLATFORM_NOT_FOUND"
|
||||
// ErrorTypeLinkCheckFailed 链接检查失败
|
||||
ErrorTypeLinkCheckFailed ErrorType = "LINK_CHECK_FAILED"
|
||||
)
|
||||
|
||||
// ResourceError 资源处理错误
|
||||
type ResourceError struct {
|
||||
Type ErrorType `json:"type"`
|
||||
Message string `json:"message"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Details string `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
// Error 实现error接口
|
||||
func (e *ResourceError) Error() string {
|
||||
if e.Details != "" {
|
||||
return fmt.Sprintf("[%s] %s: %s", e.Type, e.Message, e.Details)
|
||||
}
|
||||
return fmt.Sprintf("[%s] %s", e.Type, e.Message)
|
||||
}
|
||||
|
||||
// NewResourceError 创建新的资源错误
|
||||
func NewResourceError(errorType ErrorType, message string, url string, details string) *ResourceError {
|
||||
return &ResourceError{
|
||||
Type: errorType,
|
||||
Message: message,
|
||||
URL: url,
|
||||
Details: details,
|
||||
}
|
||||
}
|
||||
|
||||
// NewUnsupportedLinkError 创建不支持的链接错误
|
||||
func NewUnsupportedLinkError(url string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeUnsupportedLink, "不支持的链接地址", url, "")
|
||||
}
|
||||
|
||||
// NewInvalidLinkError 创建无效链接错误
|
||||
func NewInvalidLinkError(url string, details string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeInvalidLink, "链接无效", url, details)
|
||||
}
|
||||
|
||||
// NewNoAccountError 创建没有账号错误
|
||||
func NewNoAccountError(platform string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeNoAccount, "没有可用的网盘账号", "", fmt.Sprintf("平台: %s", platform))
|
||||
}
|
||||
|
||||
// NewNoValidAccountError 创建没有有效账号错误
|
||||
func NewNoValidAccountError(platform string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeNoValidAccount, "没有有效的网盘账号", "", fmt.Sprintf("平台: %s", platform))
|
||||
}
|
||||
|
||||
// NewServiceCreationError 创建服务创建失败错误
|
||||
func NewServiceCreationError(url string, details string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeServiceCreation, "创建网盘服务失败", url, details)
|
||||
}
|
||||
|
||||
// NewTransferFailedError 创建转存失败错误
|
||||
func NewTransferFailedError(url string, details string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeTransferFailed, "网盘信息获取失败", url, details)
|
||||
}
|
||||
|
||||
// NewTagProcessingError 创建标签处理失败错误
|
||||
func NewTagProcessingError(details string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeTagProcessing, "处理标签失败", "", details)
|
||||
}
|
||||
|
||||
// NewCategoryProcessingError 创建分类处理失败错误
|
||||
func NewCategoryProcessingError(details string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeCategoryProcessing, "处理分类失败", "", details)
|
||||
}
|
||||
|
||||
// NewResourceSaveError 创建资源保存失败错误
|
||||
func NewResourceSaveError(url string, details string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeResourceSave, "资源保存失败", url, details)
|
||||
}
|
||||
|
||||
// NewPlatformNotFoundError 创建平台未找到错误
|
||||
func NewPlatformNotFoundError(platform string) *ResourceError {
|
||||
return NewResourceError(ErrorTypePlatformNotFound, "未找到对应的平台ID", "", fmt.Sprintf("平台: %s", platform))
|
||||
}
|
||||
|
||||
// NewLinkCheckError 创建链接检查失败错误
|
||||
func NewLinkCheckError(url string, details string) *ResourceError {
|
||||
return NewResourceError(ErrorTypeLinkCheckFailed, "链接检查失败", url, details)
|
||||
}
|
||||
|
||||
// IsResourceError 检查是否为资源错误
|
||||
func IsResourceError(err error) bool {
|
||||
_, ok := err.(*ResourceError)
|
||||
return ok
|
||||
}
|
||||
|
||||
// GetResourceError 获取资源错误
|
||||
func GetResourceError(err error) *ResourceError {
|
||||
if resourceErr, ok := err.(*ResourceError); ok {
|
||||
return resourceErr
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetErrorType 获取错误类型
|
||||
func GetErrorType(err error) ErrorType {
|
||||
if resourceErr := GetResourceError(err); resourceErr != nil {
|
||||
return resourceErr.Type
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// IsRetryableError 检查是否为可重试的错误
|
||||
func IsRetryableError(err error) bool {
|
||||
errorType := GetErrorType(err)
|
||||
switch errorType {
|
||||
case ErrorTypeNoAccount, ErrorTypeNoValidAccount, ErrorTypeTransferFailed, ErrorTypeLinkCheckFailed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// GetErrorSummary 获取错误摘要
|
||||
func GetErrorSummary(err error) string {
|
||||
if resourceErr := GetResourceError(err); resourceErr != nil {
|
||||
return fmt.Sprintf("%s: %s", resourceErr.Type, resourceErr.Message)
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
@@ -18,10 +18,10 @@ var (
|
||||
)
|
||||
|
||||
// GetGlobalScheduler 获取全局调度器实例(单例模式)
|
||||
func GetGlobalScheduler(hotDramaRepo repo.HotDramaRepository, readyResourceRepo repo.ReadyResourceRepository, resourceRepo repo.ResourceRepository, systemConfigRepo repo.SystemConfigRepository, panRepo repo.PanRepository, cksRepo repo.CksRepository) *GlobalScheduler {
|
||||
func GetGlobalScheduler(hotDramaRepo repo.HotDramaRepository, readyResourceRepo repo.ReadyResourceRepository, resourceRepo repo.ResourceRepository, systemConfigRepo repo.SystemConfigRepository, panRepo repo.PanRepository, cksRepo repo.CksRepository, tagRepo repo.TagRepository, categoryRepo repo.CategoryRepository) *GlobalScheduler {
|
||||
once.Do(func() {
|
||||
globalScheduler = &GlobalScheduler{
|
||||
scheduler: NewScheduler(hotDramaRepo, readyResourceRepo, resourceRepo, systemConfigRepo, panRepo, cksRepo),
|
||||
scheduler: NewScheduler(hotDramaRepo, readyResourceRepo, resourceRepo, systemConfigRepo, panRepo, cksRepo, tagRepo, categoryRepo),
|
||||
}
|
||||
})
|
||||
return globalScheduler
|
||||
|
||||
@@ -269,7 +269,7 @@ func (lv *LogViewer) CleanOldLogs(days int) error {
|
||||
return err
|
||||
}
|
||||
|
||||
cutoffTime := time.Now().AddDate(0, 0, -days)
|
||||
cutoffTime := GetCurrentTime().AddDate(0, 0, -days)
|
||||
deletedCount := 0
|
||||
|
||||
for _, file := range files {
|
||||
|
||||
@@ -153,7 +153,7 @@ func (l *Logger) initLogFile() error {
|
||||
}
|
||||
|
||||
// 创建新的日志文件
|
||||
logFile := filepath.Join(l.config.LogDir, fmt.Sprintf("app_%s.log", time.Now().Format("2006-01-02")))
|
||||
logFile := filepath.Join(l.config.LogDir, fmt.Sprintf("app_%s.log", GetCurrentTime().Format("2006-01-02")))
|
||||
file, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建日志文件失败: %v", err)
|
||||
@@ -291,8 +291,8 @@ func (l *Logger) rotateLog() {
|
||||
}
|
||||
|
||||
// 重命名当前日志文件
|
||||
currentLogFile := filepath.Join(l.config.LogDir, fmt.Sprintf("app_%s.log", time.Now().Format("2006-01-02")))
|
||||
backupLogFile := filepath.Join(l.config.LogDir, fmt.Sprintf("app_%s_%s.log", time.Now().Format("2006-01-02"), time.Now().Format("15-04-05")))
|
||||
currentLogFile := filepath.Join(l.config.LogDir, fmt.Sprintf("app_%s.log", GetCurrentTime().Format("2006-01-02")))
|
||||
backupLogFile := filepath.Join(l.config.LogDir, fmt.Sprintf("app_%s_%s.log", GetCurrentTime().Format("2006-01-02"), GetCurrentTime().Format("15-04-05")))
|
||||
|
||||
if _, err := os.Stat(currentLogFile); err == nil {
|
||||
os.Rename(currentLogFile, backupLogFile)
|
||||
@@ -314,7 +314,7 @@ func (l *Logger) cleanOldLogs() {
|
||||
return
|
||||
}
|
||||
|
||||
cutoffTime := time.Now().AddDate(0, 0, -l.config.MaxAge)
|
||||
cutoffTime := GetCurrentTime().AddDate(0, 0, -l.config.MaxAge)
|
||||
|
||||
for _, file := range files {
|
||||
fileInfo, err := os.Stat(file)
|
||||
|
||||
@@ -2,6 +2,7 @@ package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -10,17 +11,21 @@ import (
|
||||
commonutils "github.com/ctwj/urldb/common/utils"
|
||||
"github.com/ctwj/urldb/db/entity"
|
||||
"github.com/ctwj/urldb/db/repo"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Scheduler 定时任务管理器
|
||||
type Scheduler struct {
|
||||
doubanService *DoubanService
|
||||
hotDramaRepo repo.HotDramaRepository
|
||||
readyResourceRepo repo.ReadyResourceRepository
|
||||
resourceRepo repo.ResourceRepository
|
||||
systemConfigRepo repo.SystemConfigRepository
|
||||
panRepo repo.PanRepository
|
||||
cksRepo repo.CksRepository
|
||||
doubanService *DoubanService
|
||||
hotDramaRepo repo.HotDramaRepository
|
||||
readyResourceRepo repo.ReadyResourceRepository
|
||||
resourceRepo repo.ResourceRepository
|
||||
systemConfigRepo repo.SystemConfigRepository
|
||||
panRepo repo.PanRepository
|
||||
cksRepo repo.CksRepository
|
||||
// 新增
|
||||
tagRepo repo.TagRepository
|
||||
categoryRepo repo.CategoryRepository
|
||||
stopChan chan bool
|
||||
isRunning bool
|
||||
readyResourceRunning bool
|
||||
@@ -35,7 +40,7 @@ type Scheduler struct {
|
||||
}
|
||||
|
||||
// NewScheduler 创建新的定时任务管理器
|
||||
func NewScheduler(hotDramaRepo repo.HotDramaRepository, readyResourceRepo repo.ReadyResourceRepository, resourceRepo repo.ResourceRepository, systemConfigRepo repo.SystemConfigRepository, panRepo repo.PanRepository, cksRepo repo.CksRepository) *Scheduler {
|
||||
func NewScheduler(hotDramaRepo repo.HotDramaRepository, readyResourceRepo repo.ReadyResourceRepository, resourceRepo repo.ResourceRepository, systemConfigRepo repo.SystemConfigRepository, panRepo repo.PanRepository, cksRepo repo.CksRepository, tagRepo repo.TagRepository, categoryRepo repo.CategoryRepository) *Scheduler {
|
||||
return &Scheduler{
|
||||
doubanService: NewDoubanService(),
|
||||
hotDramaRepo: hotDramaRepo,
|
||||
@@ -44,6 +49,8 @@ func NewScheduler(hotDramaRepo repo.HotDramaRepository, readyResourceRepo repo.R
|
||||
systemConfigRepo: systemConfigRepo,
|
||||
panRepo: panRepo,
|
||||
cksRepo: cksRepo,
|
||||
tagRepo: tagRepo,
|
||||
categoryRepo: categoryRepo,
|
||||
stopChan: make(chan bool),
|
||||
isRunning: false,
|
||||
readyResourceRunning: false,
|
||||
@@ -283,10 +290,9 @@ func (s *Scheduler) StartReadyResourceScheduler() {
|
||||
|
||||
go func() {
|
||||
// 获取系统配置中的间隔时间
|
||||
config, err := s.systemConfigRepo.GetOrCreateDefault()
|
||||
interval := 5 * time.Minute // 默认5分钟
|
||||
if err == nil && config.AutoProcessInterval > 0 {
|
||||
interval = time.Duration(config.AutoProcessInterval) * time.Minute
|
||||
interval := 3 * time.Minute // 默认3分钟
|
||||
if autoProcessInterval, err := s.systemConfigRepo.GetConfigInt(entity.ConfigKeyAutoProcessInterval); err == nil && autoProcessInterval > 0 {
|
||||
interval = time.Duration(autoProcessInterval) * time.Minute
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
@@ -334,19 +340,20 @@ func (s *Scheduler) processReadyResources() {
|
||||
Info("开始处理待处理资源...")
|
||||
|
||||
// 检查系统配置,确认是否启用自动处理
|
||||
config, err := s.systemConfigRepo.GetOrCreateDefault()
|
||||
autoProcess, err := s.systemConfigRepo.GetConfigBool(entity.ConfigKeyAutoProcessReadyResources)
|
||||
if err != nil {
|
||||
Error("获取系统配置失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !config.AutoProcessReadyResources {
|
||||
if !autoProcess {
|
||||
Info("自动处理待处理资源功能已禁用")
|
||||
return
|
||||
}
|
||||
|
||||
// 获取所有待处理资源
|
||||
// 获取所有没有错误的待处理资源
|
||||
readyResources, err := s.readyResourceRepo.FindAll()
|
||||
// readyResources, err := s.readyResourceRepo.FindWithoutErrors()
|
||||
if err != nil {
|
||||
Error("获取待处理资源失败: %v", err)
|
||||
return
|
||||
@@ -377,10 +384,21 @@ func (s *Scheduler) processReadyResources() {
|
||||
|
||||
if err := s.convertReadyResourceToResource(readyResource, factory); err != nil {
|
||||
Error("处理资源失败 (ID: %d): %v", readyResource.ID, err)
|
||||
|
||||
// 保存完整的错误信息
|
||||
readyResource.ErrorMsg = err.Error()
|
||||
|
||||
if updateErr := s.readyResourceRepo.Update(&readyResource); updateErr != nil {
|
||||
Error("更新错误信息失败 (ID: %d): %v", readyResource.ID, updateErr)
|
||||
} else {
|
||||
Info("已保存错误信息到资源 (ID: %d): %s", readyResource.ID, err.Error())
|
||||
}
|
||||
} else {
|
||||
// 处理成功,删除readyResource
|
||||
s.readyResourceRepo.Delete(readyResource.ID)
|
||||
processedCount++
|
||||
Info("成功处理资源: %s", readyResource.URL)
|
||||
}
|
||||
s.readyResourceRepo.Delete(readyResource.ID)
|
||||
processedCount++
|
||||
Info("成功处理资源: %s", readyResource.URL)
|
||||
}
|
||||
|
||||
Info("待处理资源处理完成,共处理 %d 个资源", processedCount)
|
||||
@@ -394,121 +412,152 @@ func (s *Scheduler) convertReadyResourceToResource(readyResource entity.ReadyRes
|
||||
shareID, serviceType := panutils.ExtractShareId(readyResource.URL)
|
||||
if serviceType == panutils.NotFound {
|
||||
Warn("不支持的链接地址: %s", readyResource.URL)
|
||||
return nil
|
||||
return NewUnsupportedLinkError(readyResource.URL)
|
||||
}
|
||||
|
||||
Debug("检测到服务类型: %s, 分享ID: %s", serviceType.String(), shareID)
|
||||
|
||||
resource := &entity.Resource{
|
||||
Title: derefString(readyResource.Title),
|
||||
Description: readyResource.Description,
|
||||
URL: readyResource.URL,
|
||||
Cover: readyResource.Img,
|
||||
IsValid: true,
|
||||
IsPublic: true,
|
||||
Key: readyResource.Key,
|
||||
PanID: s.getPanIDByServiceType(serviceType),
|
||||
}
|
||||
|
||||
// 不是夸克,直接保存,
|
||||
if serviceType != panutils.Quark {
|
||||
// 检测是否有效
|
||||
checkResult, _ := commonutils.CheckURL(readyResource.URL)
|
||||
checkResult, err := commonutils.CheckURL(readyResource.URL)
|
||||
if err != nil {
|
||||
Error("链接检查失败: %v", err)
|
||||
return NewLinkCheckError(readyResource.URL, err.Error())
|
||||
}
|
||||
if !checkResult.Status {
|
||||
Warn("链接无效: %s", readyResource.URL)
|
||||
return nil
|
||||
return NewInvalidLinkError(readyResource.URL, "链接状态检查失败")
|
||||
}
|
||||
} else {
|
||||
// 获取夸克网盘账号的 cookie
|
||||
panID := s.getPanIDByServiceType(serviceType)
|
||||
if panID == nil {
|
||||
Error("未找到对应的平台ID")
|
||||
return NewPlatformNotFoundError(serviceType.String())
|
||||
}
|
||||
|
||||
// 入库
|
||||
}
|
||||
|
||||
// 准备配置
|
||||
config := &panutils.PanConfig{
|
||||
URL: readyResource.URL,
|
||||
Code: "", // 可以从readyResource中获取
|
||||
IsType: 1, // 转存并分享后的资源信息 0 转存后分享, 1 只获取基本信息
|
||||
ExpiredType: 1, // 永久分享
|
||||
AdFid: "",
|
||||
Stoken: "",
|
||||
}
|
||||
|
||||
// 通过工厂获取对应的网盘服务单例
|
||||
panService, err := factory.CreatePanService(readyResource.URL, config)
|
||||
if err != nil {
|
||||
Error("获取网盘服务失败: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// 阿里云盘特殊处理:检查URL有效性
|
||||
// if serviceType == panutils.Alipan {
|
||||
// checkResult, _ := CheckURL(readyResource.URL)
|
||||
// if !checkResult.Status {
|
||||
// log.Printf("阿里云盘链接无效: %s", readyResource.URL)
|
||||
// return nil
|
||||
// }
|
||||
|
||||
// // 如果有标题,直接创建资源
|
||||
// if readyResource.Title != nil && *readyResource.Title != "" {
|
||||
// resource := &entity.Resource{
|
||||
// Title: *readyResource.Title,
|
||||
// Description: readyResource.Description,
|
||||
// URL: readyResource.URL,
|
||||
// PanID: s.determinePanID(readyResource.URL),
|
||||
// IsValid: true,
|
||||
// IsPublic: true,
|
||||
// }
|
||||
|
||||
// // 如果有分类信息,尝试查找或创建分类
|
||||
// if readyResource.Category != "" {
|
||||
// categoryID, err := s.getOrCreateCategory(readyResource.Category)
|
||||
// if err == nil {
|
||||
// resource.CategoryID = &categoryID
|
||||
// }
|
||||
// }
|
||||
|
||||
// return s.resourceRepo.Create(resource)
|
||||
// }
|
||||
// }
|
||||
|
||||
// 统一处理:尝试转存获取标题
|
||||
result, err := panService.Transfer(shareID)
|
||||
if err != nil {
|
||||
Error("网盘信息获取失败: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
if !result.Success {
|
||||
Error("网盘信息获取失败: %s", result.Message)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 提取转存结果
|
||||
if resultData, ok := result.Data.(map[string]interface{}); ok {
|
||||
title := resultData["title"].(string)
|
||||
shareURL := resultData["shareUrl"].(string)
|
||||
// fid := resultData["fid"].(string) // 暂时未使用
|
||||
|
||||
// 创建资源记录
|
||||
resource := &entity.Resource{
|
||||
Title: title,
|
||||
Description: readyResource.Description,
|
||||
URL: shareURL,
|
||||
PanID: s.getPanIDByServiceType(serviceType),
|
||||
IsValid: true,
|
||||
IsPublic: true,
|
||||
accounts, err := s.cksRepo.FindByPanID(*panID)
|
||||
if err != nil {
|
||||
Error("获取夸克网盘账号失败: %v", err)
|
||||
return NewServiceCreationError(readyResource.URL, fmt.Sprintf("获取网盘账号失败: %v", err))
|
||||
}
|
||||
|
||||
// 如果有分类信息,尝试查找或创建分类
|
||||
if readyResource.Category != "" {
|
||||
categoryID, err := s.getOrCreateCategory(readyResource.Category)
|
||||
if err == nil {
|
||||
resource.CategoryID = &categoryID
|
||||
if len(accounts) == 0 {
|
||||
Error("没有可用的夸克网盘账号")
|
||||
return NewNoAccountError(serviceType.String())
|
||||
}
|
||||
|
||||
// 选择第一个有效的账号
|
||||
var selectedAccount *entity.Cks
|
||||
for _, account := range accounts {
|
||||
if account.IsValid {
|
||||
selectedAccount = &account
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return s.resourceRepo.Create(resource)
|
||||
if selectedAccount == nil {
|
||||
Error("没有有效的夸克网盘账号")
|
||||
return NewNoValidAccountError(serviceType.String())
|
||||
}
|
||||
|
||||
Debug("使用夸克网盘账号: %d, Cookie: %s", selectedAccount.ID, selectedAccount.Ck[:20]+"...")
|
||||
|
||||
// 准备配置
|
||||
config := &panutils.PanConfig{
|
||||
URL: readyResource.URL,
|
||||
Code: "", // 可以从readyResource中获取
|
||||
IsType: 1, // 转存并分享后的资源信息 0 转存后分享, 1 只获取基本信息
|
||||
ExpiredType: 1, // 永久分享
|
||||
AdFid: "",
|
||||
Stoken: "",
|
||||
Cookie: selectedAccount.Ck, // 添加 cookie
|
||||
}
|
||||
|
||||
// 通过工厂获取对应的网盘服务单例
|
||||
panService, err := factory.CreatePanService(readyResource.URL, config)
|
||||
if err != nil {
|
||||
Error("获取网盘服务失败: %v", err)
|
||||
return NewServiceCreationError(readyResource.URL, err.Error())
|
||||
}
|
||||
|
||||
// 统一处理:尝试转存获取标题
|
||||
result, err := panService.Transfer(shareID)
|
||||
if err != nil {
|
||||
Error("网盘信息获取失败: %v", err)
|
||||
return NewTransferFailedError(readyResource.URL, err.Error())
|
||||
}
|
||||
|
||||
if !result.Success {
|
||||
Error("网盘信息获取失败: %s", result.Message)
|
||||
return NewTransferFailedError(readyResource.URL, result.Message)
|
||||
}
|
||||
|
||||
// 如果获取到了标题,更新资源标题
|
||||
// if result.Title != "" {
|
||||
// resource.Title = result.Title
|
||||
// }
|
||||
}
|
||||
|
||||
Error("转存结果格式异常")
|
||||
// 处理标签
|
||||
tagIDs, err := s.handleTags(readyResource.Tags)
|
||||
if err != nil {
|
||||
Error("处理标签失败: %v", err)
|
||||
return NewTagProcessingError(err.Error())
|
||||
}
|
||||
// 如果没有标签,tagIDs 可能为 nil,这是正常的
|
||||
if tagIDs == nil {
|
||||
tagIDs = []uint{} // 初始化为空数组
|
||||
}
|
||||
// 处理分类
|
||||
categoryID, err := s.resolveCategory(readyResource.Category, tagIDs)
|
||||
if err != nil {
|
||||
Error("处理分类失败: %v", err)
|
||||
return NewCategoryProcessingError(err.Error())
|
||||
}
|
||||
if categoryID != nil {
|
||||
resource.CategoryID = categoryID
|
||||
}
|
||||
// 保存资源
|
||||
err = s.resourceRepo.Create(resource)
|
||||
if err != nil {
|
||||
Error("资源保存失败: %v", err)
|
||||
return NewResourceSaveError(readyResource.URL, err.Error())
|
||||
}
|
||||
// 插入 resource_tags 关联
|
||||
if len(tagIDs) > 0 {
|
||||
for _, tagID := range tagIDs {
|
||||
err := s.resourceRepo.CreateResourceTag(resource.ID, tagID)
|
||||
if err != nil {
|
||||
Error("插入资源标签关联失败: %v", err)
|
||||
// 这里不返回错误,因为资源已经保存成功,标签关联失败不影响主要功能
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Debug("没有标签,跳过插入资源标签关联")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// getOrCreateCategory 获取或创建分类
|
||||
func (s *Scheduler) getOrCreateCategory(categoryName string) (uint, error) {
|
||||
// 这里需要实现分类的查找和创建逻辑
|
||||
// 由于没有CategoryRepository的注入,这里先返回0
|
||||
// 你可以根据需要添加CategoryRepository的依赖
|
||||
return 0, nil
|
||||
}
|
||||
// // getOrCreateCategory 获取或创建分类
|
||||
// func (s *Scheduler) getOrCreateCategory(categoryName string) (uint, error) {
|
||||
// // 这里需要实现分类的查找和创建逻辑
|
||||
// // 由于没有CategoryRepository的注入,这里先返回0
|
||||
// // 你可以根据需要添加CategoryRepository的依赖
|
||||
// return 0, nil
|
||||
// }
|
||||
|
||||
// initPanCache 初始化平台映射缓存
|
||||
func (s *Scheduler) initPanCache() {
|
||||
@@ -591,10 +640,9 @@ func (s *Scheduler) StartAutoTransferScheduler() {
|
||||
|
||||
go func() {
|
||||
// 获取系统配置中的间隔时间
|
||||
config, err := s.systemConfigRepo.GetOrCreateDefault()
|
||||
interval := 5 * time.Minute // 默认5分钟
|
||||
if err == nil && config.AutoProcessInterval > 0 {
|
||||
interval = time.Duration(config.AutoProcessInterval) * time.Minute
|
||||
if autoProcessInterval, err := s.systemConfigRepo.GetConfigInt(entity.ConfigKeyAutoProcessInterval); err == nil && autoProcessInterval > 0 {
|
||||
interval = time.Duration(autoProcessInterval) * time.Minute
|
||||
}
|
||||
|
||||
ticker := time.NewTicker(interval)
|
||||
@@ -647,33 +695,63 @@ func (s *Scheduler) processAutoTransfer() {
|
||||
Info("开始处理自动转存...")
|
||||
|
||||
// 检查系统配置,确认是否启用自动转存
|
||||
config, err := s.systemConfigRepo.GetOrCreateDefault()
|
||||
autoTransferEnabled, err := s.systemConfigRepo.GetConfigBool(entity.ConfigKeyAutoTransferEnabled)
|
||||
if err != nil {
|
||||
Error("获取系统配置失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if !config.AutoTransferEnabled {
|
||||
if !autoTransferEnabled {
|
||||
Info("自动转存功能已禁用")
|
||||
return
|
||||
}
|
||||
|
||||
// 获取所有有效的网盘账号
|
||||
// 获取quark平台ID
|
||||
panRepoImpl, ok := s.panRepo.(interface{ GetDB() *gorm.DB })
|
||||
if !ok {
|
||||
Error("panRepo不支持GetDB方法")
|
||||
return
|
||||
}
|
||||
var quarkPan entity.Pan
|
||||
err = panRepoImpl.GetDB().Where("name = ?", "quark").First(&quarkPan).Error
|
||||
if err != nil {
|
||||
Error("未找到quark平台: %v", err)
|
||||
return
|
||||
}
|
||||
quarkPanID := quarkPan.ID
|
||||
|
||||
// 获取所有账号
|
||||
accounts, err := s.cksRepo.FindAll()
|
||||
if err != nil {
|
||||
Error("获取网盘账号失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(accounts) == 0 {
|
||||
Info("没有可用的网盘账号")
|
||||
// 获取最小存储空间配置
|
||||
autoTransferMinSpace, err := s.systemConfigRepo.GetConfigInt(entity.ConfigKeyAutoTransferMinSpace)
|
||||
if err != nil {
|
||||
Error("获取最小存储空间配置失败: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
Info("找到 %d 个网盘账号,开始自动转存处理...", len(accounts))
|
||||
// 过滤:只保留已激活、quark平台、剩余空间足够的账号
|
||||
minSpaceBytes := int64(autoTransferMinSpace) * 1024 * 1024 * 1024
|
||||
var validAccounts []entity.Cks
|
||||
for _, acc := range accounts {
|
||||
if acc.IsValid && acc.PanID == quarkPanID && acc.LeftSpace >= minSpaceBytes {
|
||||
validAccounts = append(validAccounts, acc)
|
||||
}
|
||||
}
|
||||
|
||||
if len(validAccounts) == 0 {
|
||||
Info("没有可用的quark网盘账号")
|
||||
return
|
||||
}
|
||||
|
||||
Info("找到 %d 个可用quark网盘账号,开始自动转存处理...", len(validAccounts))
|
||||
|
||||
// 获取需要转存的资源
|
||||
resources, err := s.getResourcesForTransfer(config)
|
||||
resources, err := s.getResourcesForTransfer(quarkPanID)
|
||||
if err != nil {
|
||||
Error("获取需要转存的资源失败: %v", err)
|
||||
return
|
||||
@@ -686,88 +764,178 @@ func (s *Scheduler) processAutoTransfer() {
|
||||
|
||||
Info("找到 %d 个需要转存的资源", len(resources))
|
||||
|
||||
// 执行自动转存
|
||||
transferCount := 0
|
||||
for _, resource := range resources {
|
||||
if err := s.transferResource(resource, accounts, config); err != nil {
|
||||
Error("转存资源失败 (ID: %d): %v", resource.ID, err)
|
||||
} else {
|
||||
transferCount++
|
||||
Info("成功转存资源: %s", resource.Title)
|
||||
}
|
||||
// 并发自动转存
|
||||
resourceCh := make(chan *entity.Resource, len(resources))
|
||||
for _, res := range resources {
|
||||
resourceCh <- res
|
||||
}
|
||||
close(resourceCh)
|
||||
|
||||
Info("自动转存处理完成,共转存 %d 个资源", transferCount)
|
||||
var wg sync.WaitGroup
|
||||
for _, account := range validAccounts {
|
||||
wg.Add(1)
|
||||
go func(acc entity.Cks) {
|
||||
defer wg.Done()
|
||||
factory := panutils.GetInstance() // 使用单例模式
|
||||
for res := range resourceCh {
|
||||
if err := s.transferResource(res, []entity.Cks{acc}, factory); err != nil {
|
||||
Error("转存资源失败 (ID: %d): %v", res.ID, err)
|
||||
} else {
|
||||
Info("成功转存资源: %s", res.Title)
|
||||
rand.Seed(GetCurrentTime().UnixNano())
|
||||
sleepSec := rand.Intn(3) + 1 // 1,2,3
|
||||
time.Sleep(time.Duration(sleepSec) * time.Second)
|
||||
}
|
||||
}
|
||||
}(account)
|
||||
}
|
||||
wg.Wait()
|
||||
Info("自动转存处理完成,账号数: %d,资源数: %d", len(validAccounts), len(resources))
|
||||
}
|
||||
|
||||
// getResourcesForTransfer 获取需要转存的资源
|
||||
func (s *Scheduler) getResourcesForTransfer(config *entity.SystemConfig) ([]*entity.Resource, error) {
|
||||
// TODO: 实现获取需要转存的资源逻辑
|
||||
// 1. 获取所有有效的资源
|
||||
// 2. 根据配置的转存限制天数过滤资源
|
||||
// 3. 排除已经转存过的资源
|
||||
// 4. 按优先级排序(可以根据浏览次数、创建时间等)
|
||||
|
||||
Info("获取需要转存的资源 - 限制天数: %d", config.AutoTransferLimitDays)
|
||||
|
||||
// 临时返回空数组,等待具体实现
|
||||
return []*entity.Resource{}, nil
|
||||
}
|
||||
|
||||
// transferResource 转存单个资源
|
||||
func (s *Scheduler) transferResource(resource *entity.Resource, accounts []entity.Cks, config *entity.SystemConfig) error {
|
||||
// TODO: 实现单个资源的转存逻辑
|
||||
// 1. 选择合适的网盘账号(根据剩余空间、VIP状态等)
|
||||
// 2. 检查账号剩余空间是否满足最小空间要求
|
||||
// 3. 调用网盘API进行转存
|
||||
// 4. 更新资源状态和转存记录
|
||||
// 5. 更新账号使用空间
|
||||
|
||||
Info("开始转存资源: %s (ID: %d)", resource.Title, resource.ID)
|
||||
|
||||
// 选择最佳账号
|
||||
selectedAccount := s.selectBestAccount(accounts, config)
|
||||
if selectedAccount == nil {
|
||||
return fmt.Errorf("没有合适的网盘账号")
|
||||
func (s *Scheduler) getResourcesForTransfer(quarkPanID uint) ([]*entity.Resource, error) {
|
||||
// 获取自动转存限制天数配置
|
||||
autoTransferLimitDays, err := s.systemConfigRepo.GetConfigInt(entity.ConfigKeyAutoTransferLimitDays)
|
||||
if err != nil {
|
||||
Error("获取自动转存限制天数配置失败: %v", err)
|
||||
return nil, err
|
||||
}
|
||||
|
||||
Info("选择账号: %s (剩余空间: %d GB)", selectedAccount.Username, selectedAccount.LeftSpace/1024/1024/1024)
|
||||
days := autoTransferLimitDays
|
||||
var sinceTime time.Time
|
||||
if days > 0 {
|
||||
sinceTime = GetCurrentTime().AddDate(0, 0, -days)
|
||||
} else {
|
||||
sinceTime = time.Time{}
|
||||
}
|
||||
|
||||
// TODO: 执行实际的转存操作
|
||||
// 这里需要调用网盘API进行转存
|
||||
repoImpl, ok := s.resourceRepo.(*repo.ResourceRepositoryImpl)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("resourceRepo不是ResourceRepositoryImpl类型")
|
||||
}
|
||||
return repoImpl.GetResourcesForTransfer(quarkPanID, sinceTime)
|
||||
}
|
||||
|
||||
var resourceUpdateMutex sync.Mutex // 全局互斥锁,保证多协程安全
|
||||
|
||||
// transferResource 转存单个资源
|
||||
func (s *Scheduler) transferResource(resource *entity.Resource, accounts []entity.Cks, factory *panutils.PanFactory) error {
|
||||
if len(accounts) == 0 {
|
||||
return fmt.Errorf("没有可用的网盘账号")
|
||||
}
|
||||
account := accounts[0]
|
||||
|
||||
service, err := factory.CreatePanService(resource.URL, &panutils.PanConfig{
|
||||
URL: resource.URL,
|
||||
ExpiredType: 0,
|
||||
IsType: 0,
|
||||
Cookie: account.Ck,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("创建网盘服务失败: %v", err)
|
||||
}
|
||||
|
||||
// 获取最小存储空间配置
|
||||
autoTransferMinSpace, err := s.systemConfigRepo.GetConfigInt(entity.ConfigKeyAutoTransferMinSpace)
|
||||
if err != nil {
|
||||
Error("获取最小存储空间配置失败: %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
// 检查账号剩余空间
|
||||
minSpaceBytes := int64(autoTransferMinSpace) * 1024 * 1024 * 1024
|
||||
if account.LeftSpace < minSpaceBytes {
|
||||
return fmt.Errorf("账号剩余空间不足,需要 %d GB,当前剩余 %d GB", autoTransferMinSpace, account.LeftSpace/1024/1024/1024)
|
||||
}
|
||||
|
||||
// 提取分享ID
|
||||
shareID, _ := commonutils.ExtractShareIdString(resource.URL)
|
||||
|
||||
// 转存资源
|
||||
result, err := service.Transfer(shareID)
|
||||
if err != nil {
|
||||
resourceUpdateMutex.Lock()
|
||||
defer resourceUpdateMutex.Unlock()
|
||||
s.resourceRepo.Update(&entity.Resource{
|
||||
ID: resource.ID,
|
||||
ErrorMsg: err.Error(),
|
||||
})
|
||||
return fmt.Errorf("转存失败: %v", err)
|
||||
}
|
||||
|
||||
if result == nil || !result.Success {
|
||||
errMsg := "转存失败"
|
||||
if result != nil && result.Message != "" {
|
||||
errMsg = result.Message
|
||||
}
|
||||
resourceUpdateMutex.Lock()
|
||||
defer resourceUpdateMutex.Unlock()
|
||||
s.resourceRepo.Update(&entity.Resource{
|
||||
ID: resource.ID,
|
||||
ErrorMsg: errMsg,
|
||||
})
|
||||
return fmt.Errorf("转存失败: %s", errMsg)
|
||||
}
|
||||
|
||||
// 提取转存链接、fid等
|
||||
var saveURL, fid string
|
||||
if data, ok := result.Data.(map[string]interface{}); ok {
|
||||
if v, ok := data["shareUrl"]; ok {
|
||||
saveURL, _ = v.(string)
|
||||
}
|
||||
if v, ok := data["fid"]; ok {
|
||||
fid, _ = v.(string)
|
||||
}
|
||||
}
|
||||
if saveURL == "" {
|
||||
saveURL = result.ShareURL
|
||||
}
|
||||
|
||||
resourceUpdateMutex.Lock()
|
||||
defer resourceUpdateMutex.Unlock()
|
||||
err = s.resourceRepo.Update(&entity.Resource{
|
||||
ID: resource.ID,
|
||||
SaveURL: saveURL,
|
||||
CkID: &account.ID,
|
||||
Fid: fid,
|
||||
ErrorMsg: "",
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("保存转存结果失败: %v", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// selectBestAccount 选择最佳网盘账号
|
||||
func (s *Scheduler) selectBestAccount(accounts []entity.Cks, config *entity.SystemConfig) *entity.Cks {
|
||||
// TODO: 实现账号选择逻辑
|
||||
// 1. 过滤出有效的账号
|
||||
// 2. 检查剩余空间是否满足最小要求
|
||||
// 3. 优先选择VIP账号
|
||||
// 4. 优先选择剩余空间大的账号
|
||||
// 5. 考虑账号的使用频率(避免单个账号过度使用)
|
||||
// selectBestAccount 选择最佳账号
|
||||
func (s *Scheduler) selectBestAccount(accounts []entity.Cks) *entity.Cks {
|
||||
if len(accounts) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
minSpaceBytes := int64(config.AutoTransferMinSpace) * 1024 * 1024 * 1024 // 转换为字节
|
||||
// 获取最小存储空间配置
|
||||
autoTransferMinSpace, err := s.systemConfigRepo.GetConfigInt(entity.ConfigKeyAutoTransferMinSpace)
|
||||
if err != nil {
|
||||
Error("获取最小存储空间配置失败: %v", err)
|
||||
return &accounts[0] // 返回第一个账号
|
||||
}
|
||||
|
||||
minSpaceBytes := int64(autoTransferMinSpace) * 1024 * 1024 * 1024
|
||||
|
||||
var bestAccount *entity.Cks
|
||||
var maxScore int64 = -1
|
||||
var bestScore int64 = -1
|
||||
|
||||
for _, account := range accounts {
|
||||
if !account.IsValid {
|
||||
continue
|
||||
}
|
||||
|
||||
// 检查剩余空间
|
||||
for i := range accounts {
|
||||
account := &accounts[i]
|
||||
if account.LeftSpace < minSpaceBytes {
|
||||
continue
|
||||
continue // 跳过空间不足的账号
|
||||
}
|
||||
|
||||
// 计算账号评分
|
||||
score := s.calculateAccountScore(&account)
|
||||
if score > maxScore {
|
||||
maxScore = score
|
||||
bestAccount = &account
|
||||
score := s.calculateAccountScore(account)
|
||||
if score > bestScore {
|
||||
bestScore = score
|
||||
bestAccount = account
|
||||
}
|
||||
}
|
||||
|
||||
@@ -800,3 +968,97 @@ func (s *Scheduler) calculateAccountScore(account *entity.Cks) int64 {
|
||||
|
||||
return score
|
||||
}
|
||||
|
||||
// 分割标签,支持中英文逗号
|
||||
func splitTags(tagStr string) []string {
|
||||
tagStr = strings.ReplaceAll(tagStr, ",", ",")
|
||||
return strings.Split(tagStr, ",")
|
||||
}
|
||||
|
||||
// 处理标签,返回所有标签ID
|
||||
func (s *Scheduler) handleTags(tagStr string) ([]uint, error) {
|
||||
if tagStr == "" {
|
||||
Debug("标签字符串为空,返回空数组")
|
||||
return []uint{}, nil // 返回空数组而不是 nil
|
||||
}
|
||||
|
||||
Debug("开始处理标签字符串: %s", tagStr)
|
||||
tagNames := splitTags(tagStr)
|
||||
Debug("分割后的标签名称: %v", tagNames)
|
||||
|
||||
var tagIDs []uint
|
||||
for _, name := range tagNames {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
Debug("跳过空标签名称")
|
||||
continue
|
||||
}
|
||||
|
||||
Debug("查找标签: %s", name)
|
||||
tag, err := s.tagRepo.FindByName(name)
|
||||
if err != nil {
|
||||
Debug("标签 %s 不存在,创建新标签", name)
|
||||
// 不存在则新建
|
||||
tag = &entity.Tag{Name: name}
|
||||
err = s.tagRepo.Create(tag)
|
||||
if err != nil {
|
||||
Error("创建标签 %s 失败: %v", name, err)
|
||||
return nil, fmt.Errorf("创建标签 %s 失败: %v", name, err)
|
||||
}
|
||||
Debug("成功创建标签: %s (ID: %d)", name, tag.ID)
|
||||
} else {
|
||||
Debug("找到已存在的标签: %s (ID: %d)", name, tag.ID)
|
||||
}
|
||||
tagIDs = append(tagIDs, tag.ID)
|
||||
}
|
||||
|
||||
Debug("处理完成,标签ID列表: %v", tagIDs)
|
||||
return tagIDs, nil
|
||||
}
|
||||
|
||||
// 分类处理逻辑
|
||||
func (s *Scheduler) resolveCategory(categoryName string, tagIDs []uint) (*uint, error) {
|
||||
Debug("开始处理分类,分类名称: %s, 标签ID列表: %v", categoryName, tagIDs)
|
||||
|
||||
if categoryName != "" {
|
||||
Debug("查找分类: %s", categoryName)
|
||||
cat, err := s.categoryRepo.FindByName(categoryName)
|
||||
if err != nil {
|
||||
Debug("分类 %s 不存在: %v", categoryName, err)
|
||||
} else if cat != nil {
|
||||
Debug("找到分类: %s (ID: %d)", categoryName, cat.ID)
|
||||
return &cat.ID, nil
|
||||
}
|
||||
}
|
||||
|
||||
// 没有分类,尝试用标签反查
|
||||
if len(tagIDs) == 0 {
|
||||
Debug("没有标签,无法通过标签反查分类")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
Debug("尝试通过标签反查分类")
|
||||
for _, tagID := range tagIDs {
|
||||
Debug("查找标签ID: %d", tagID)
|
||||
tag, err := s.tagRepo.GetByID(tagID)
|
||||
if err != nil {
|
||||
Debug("查找标签ID %d 失败: %v", tagID, err)
|
||||
continue
|
||||
}
|
||||
if tag != nil && tag.CategoryID != nil {
|
||||
Debug("通过标签 %s (ID: %d) 找到分类ID: %d", tag.Name, tagID, *tag.CategoryID)
|
||||
return tag.CategoryID, nil
|
||||
}
|
||||
}
|
||||
|
||||
Debug("未找到分类,返回nil")
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 工具函数,解引用string指针
|
||||
func derefString(s *string) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return *s
|
||||
}
|
||||
|
||||
55
utils/timezone.go
Normal file
55
utils/timezone.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// InitTimezone 初始化时区设置
|
||||
func InitTimezone() {
|
||||
// 从环境变量获取时区配置
|
||||
timezone := os.Getenv("TIMEZONE")
|
||||
if timezone == "" {
|
||||
// 默认使用上海时间
|
||||
timezone = "Asia/Shanghai"
|
||||
Info("未配置时区,使用默认时区: %s", timezone)
|
||||
} else {
|
||||
Info("使用配置的时区: %s", timezone)
|
||||
}
|
||||
|
||||
// 设置时区
|
||||
loc, err := time.LoadLocation(timezone)
|
||||
if err != nil {
|
||||
Error("加载时区失败: %v,使用系统默认时区", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 设置全局时区
|
||||
time.Local = loc
|
||||
Info("时区设置成功: %s", timezone)
|
||||
}
|
||||
|
||||
// GetCurrentTime 获取当前时间(使用配置的时区)
|
||||
func GetCurrentTime() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
// GetCurrentTimeString 获取当前时间字符串(使用配置的时区)
|
||||
func GetCurrentTimeString() string {
|
||||
return time.Now().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
// GetCurrentTimeRFC3339 获取当前时间RFC3339格式(使用配置的时区)
|
||||
func GetCurrentTimeRFC3339() string {
|
||||
return time.Now().Format(time.RFC3339)
|
||||
}
|
||||
|
||||
// ParseTime 解析时间字符串(使用配置的时区)
|
||||
func ParseTime(timeStr string) (time.Time, error) {
|
||||
return time.Parse("2006-01-02 15:04:05", timeStr)
|
||||
}
|
||||
|
||||
// FormatTime 格式化时间(使用配置的时区)
|
||||
func FormatTime(t time.Time, layout string) string {
|
||||
return t.Format(layout)
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -22,15 +23,24 @@ type VersionInfo struct {
|
||||
|
||||
// 编译时注入的版本信息
|
||||
var (
|
||||
Version = "1.0.0"
|
||||
BuildTime = time.Now().Format("2006-01-02 15:04:05")
|
||||
Version = getVersionFromFile()
|
||||
BuildTime = GetCurrentTimeString()
|
||||
GitCommit = "unknown"
|
||||
GitBranch = "unknown"
|
||||
)
|
||||
|
||||
// getVersionFromFile 从VERSION文件读取版本号
|
||||
func getVersionFromFile() string {
|
||||
data, err := os.ReadFile("VERSION")
|
||||
if err != nil {
|
||||
return "1.0.0" // 默认版本
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
// GetVersionInfo 获取版本信息
|
||||
func GetVersionInfo() *VersionInfo {
|
||||
buildTime, _ := time.Parse("2006-01-02 15:04:05", BuildTime)
|
||||
buildTime, _ := ParseTime(BuildTime)
|
||||
|
||||
return &VersionInfo{
|
||||
Version: Version,
|
||||
@@ -62,7 +72,7 @@ func GetFullVersionInfo() string {
|
||||
Node版本: %s
|
||||
平台: %s/%s`,
|
||||
info.Version,
|
||||
info.BuildTime.Format("2006-01-02 15:04:05"),
|
||||
FormatTime(info.BuildTime, "2006-01-02 15:04:05"),
|
||||
info.GitCommit,
|
||||
info.GitBranch,
|
||||
info.GoVersion,
|
||||
|
||||
2
web/.env
Normal file
2
web/.env
Normal file
@@ -0,0 +1,2 @@
|
||||
NUXT_PUBLIC_API_CLIENT=http://localhost:8080/api
|
||||
NUXT_PUBLIC_API_SERVER=http://localhost:8080/api
|
||||
BIN
web/assets/images/3dian.png
Normal file
BIN
web/assets/images/3dian.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 481 B |
BIN
web/assets/images/android.png
Normal file
BIN
web/assets/images/android.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.7 KiB |
BIN
web/assets/images/banner.png
Normal file
BIN
web/assets/images/banner.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
BIN
web/assets/images/banner.webp
Normal file
BIN
web/assets/images/banner.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 21 KiB |
BIN
web/assets/images/footer-banner.webp
Normal file
BIN
web/assets/images/footer-banner.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
BIN
web/assets/images/iphone.png
Normal file
BIN
web/assets/images/iphone.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.5 KiB |
4
web/components.d.ts
vendored
4
web/components.d.ts
vendored
@@ -8,9 +8,13 @@ export {}
|
||||
/* prettier-ignore */
|
||||
declare module 'vue' {
|
||||
export interface GlobalComponents {
|
||||
NA: typeof import('naive-ui')['NA']
|
||||
NAlert: typeof import('naive-ui')['NAlert']
|
||||
NButton: typeof import('naive-ui')['NButton']
|
||||
NInput: typeof import('naive-ui')['NInput']
|
||||
NSelect: typeof import('naive-ui')['NSelect']
|
||||
NTabPane: typeof import('naive-ui')['NTabPane']
|
||||
NTabs: typeof import('naive-ui')['NTabs']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
<template>
|
||||
<div class="bg-slate-800 dark:bg-gray-800 text-white dark:text-gray-100 rounded-lg shadow-lg p-4 sm:p-8 text-center relative">
|
||||
<div class="header-container bg-slate-800 dark:bg-gray-800 text-white dark:text-gray-100 rounded-lg shadow-lg p-4 sm:p-8 text-center relative">
|
||||
<!-- 页面标题和面包屑 -->
|
||||
<div class="mb-4">
|
||||
<h1 class="text-2xl sm:text-3xl font-bold mb-2">
|
||||
<NuxtLink to="/" class="text-white hover:text-gray-200 dark:hover:text-gray-300 no-underline">
|
||||
{{ systemConfig?.site_title || '网盘资源数据库' }}
|
||||
{{ systemConfig?.site_title || '老九网盘资源数据库' }}
|
||||
</NuxtLink>
|
||||
</h1>
|
||||
<!-- 面包屑导航 -->
|
||||
@@ -59,10 +59,43 @@
|
||||
<span>欢迎,{{ userStore.user?.username || '管理员' }}</span>
|
||||
<span class="ml-2 px-2 py-1 bg-blue-600/80 rounded text-xs text-white">{{ userStore.user?.role || 'admin' }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 自动转存状态提示 -->
|
||||
<ClientOnly>
|
||||
<div
|
||||
|
||||
class="absolute right-4 bottom-4 flex items-center gap-2 rounded-lg px-3 py-2"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-2 h-2 rounded-full animate-pulse" :class="{
|
||||
'bg-red-400': !systemConfig?.auto_process_ready_resources,
|
||||
'bg-green-400': systemConfig?.auto_process_ready_resources
|
||||
}"></div>
|
||||
<span class="text-xs text-white font-medium">
|
||||
自动处理已<span>{{ systemConfig?.auto_process_ready_resources ? '开启' : '关闭' }}</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<div class="w-2 h-2 rounded-full animate-pulse" :class="{
|
||||
'bg-red-400': !systemConfig?.auto_transfer_enabled,
|
||||
'bg-green-400': systemConfig?.auto_transfer_enabled
|
||||
}"></div>
|
||||
<span class="text-xs text-white font-medium">
|
||||
自动转存已<span>{{ systemConfig?.auto_transfer_enabled ? '开启' : '关闭' }}</span>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</ClientOnly>
|
||||
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useApiFetch } from '~/composables/useApiFetch'
|
||||
import { parseApiResponse } from '~/composables/useApi'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useSystemConfigStore } from '~/stores/systemConfig'
|
||||
|
||||
interface Props {
|
||||
title?: string
|
||||
}
|
||||
@@ -90,7 +123,7 @@ const pageConfig = computed(() => {
|
||||
'/admin/search-stats': { title: '搜索统计', icon: 'fas fa-chart-bar', description: '搜索数据分析' },
|
||||
'/admin/hot-dramas': { title: '热播剧管理', icon: 'fas fa-film', description: '管理热门剧集' },
|
||||
'/monitor': { title: '系统监控', icon: 'fas fa-desktop', description: '系统性能监控' },
|
||||
'/add-resource': { title: '添加资源', icon: 'fas fa-plus', description: '添加新资源' },
|
||||
'/admin/add-resource': { title: '添加资源', icon: 'fas fa-plus', description: '添加新资源' },
|
||||
'/api-docs': { title: 'API文档', icon: 'fas fa-book', description: '接口文档说明' },
|
||||
'/admin/version': { title: '版本信息', icon: 'fas fa-code-branch', description: '系统版本详情' }
|
||||
}
|
||||
@@ -101,12 +134,12 @@ const currentPageTitle = computed(() => pageConfig.value.title)
|
||||
const currentPageIcon = computed(() => pageConfig.value.icon)
|
||||
const currentPageDescription = computed(() => pageConfig.value.description)
|
||||
|
||||
// 获取系统配置
|
||||
const { data: systemConfigData } = await useAsyncData('systemConfig',
|
||||
() => $fetch('/api/system-config')
|
||||
)
|
||||
const systemConfigStore = useSystemConfigStore()
|
||||
const systemConfig = computed(() => systemConfigStore.config)
|
||||
|
||||
const systemConfig = computed(() => (systemConfigData.value as any)?.data || { site_title: '网盘资源数据库' })
|
||||
onMounted(() => {
|
||||
systemConfigStore.initConfig()
|
||||
})
|
||||
|
||||
// 退出登录
|
||||
const logout = async () => {
|
||||
@@ -117,4 +150,12 @@ const logout = async () => {
|
||||
|
||||
<style scoped>
|
||||
/* 确保样式与首页完全一致 */
|
||||
.header-container {
|
||||
background: url(/assets/images/banner.webp) center top/cover no-repeat,
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
rgba(0,0,0,0.1) 0%,
|
||||
rgba(0,0,0,0.25) 100%
|
||||
);
|
||||
}
|
||||
</style>
|
||||
@@ -1,23 +1,49 @@
|
||||
<template>
|
||||
<footer class="mt-auto py-6 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-800">
|
||||
<div class="max-w-7xl mx-auto text-center text-gray-600 dark:text-gray-400 text-sm px-3 sm:px-5">
|
||||
<footer class="footer-container mt-auto py-6 border-t border-gray-700 bg-white dark:bg-gray-800">
|
||||
<div class="max-w-7xl mx-auto text-center text-gray-400 text-sm px-3 sm:px-5">
|
||||
<p class="mb-2">本站内容由网络爬虫自动抓取。本站不储存、复制、传播任何文件,仅作个人公益学习,请在获取后24小内删除!!!</p>
|
||||
<p class="flex items-center justify-center gap-2">
|
||||
<span>{{ systemConfig?.copyright || '© 2025 网盘资源数据库 By 老九' }}</span>
|
||||
<span v-if="versionInfo.version" class="text-gray-400 dark:text-gray-500">| v{{ versionInfo.version }}</span>
|
||||
<span>{{ systemConfig?.copyright || '© 2025 老九网盘资源数据库 By 老九' }}</span>
|
||||
<span v-if="versionInfo && versionInfo.version" class="text-gray-400 dark:text-gray-500">| v <n-a
|
||||
href="https://github.com/ctwj/urldb"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
referrerpolicy="no-referrer"
|
||||
aria-label="在 GitHub 上查看版本信息"
|
||||
class="github-link"
|
||||
><span>{{ versionInfo.version }}</span></n-a>
|
||||
</span>
|
||||
</p>
|
||||
</div>
|
||||
</footer>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useApiFetch } from '~/composables/useApiFetch'
|
||||
import { parseApiResponse } from '~/composables/useApi'
|
||||
// 使用版本信息组合式函数
|
||||
const { versionInfo } = useVersion()
|
||||
const { versionInfo, fetchVersionInfo } = useVersion()
|
||||
|
||||
// 获取系统配置
|
||||
const { data: systemConfigData } = await useAsyncData('systemConfig',
|
||||
() => $fetch('/api/system-config')
|
||||
() => useApiFetch('/system/config').then(parseApiResponse)
|
||||
)
|
||||
|
||||
const systemConfig = computed(() => (systemConfigData.value as any)?.data || { copyright: '© 2025 网盘资源数据库 By 老九' })
|
||||
</script>
|
||||
const systemConfig = computed(() => (systemConfigData.value as any) || { copyright: '© 2025 老九网盘资源数据库 By 老九' })
|
||||
|
||||
// 组件挂载时获取版本信息
|
||||
onMounted(() => {
|
||||
fetchVersionInfo()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.footer-container{
|
||||
background: url(/assets/images/footer-banner.webp) center top/cover no-repeat,
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
rgba(0,0,0,0.1) 0%,
|
||||
rgba(0,0,0,0.25) 100%
|
||||
);
|
||||
}
|
||||
</style>
|
||||
@@ -1,32 +1,33 @@
|
||||
<template>
|
||||
<div>
|
||||
<div class="mb-4">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">输入格式说明:</label>
|
||||
<div class="bg-gray-50 dark:bg-gray-800 p-3 rounded text-sm text-gray-600 dark:text-gray-300 mb-4">
|
||||
<p class="mb-2"><strong>格式要求:</strong>标题和URL两行为一组,标题为必填项</p>
|
||||
<pre class="bg-white dark:bg-gray-800 p-2 rounded border text-xs">
|
||||
电影标题1
|
||||
https://pan.baidu.com/s/123456
|
||||
<div class="flex justify-between mb-4">
|
||||
<div class="mb-4 flex-1 w-1">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">输入格式说明:</label>
|
||||
<div class="bg-gray-50 dark:bg-gray-800 p-3 rounded text-sm text-gray-600 dark:text-gray-300 mb-4">
|
||||
<p class="mb-2"><strong>格式要求:</strong>标题和URL为一组,标题必填, 同一标题URL支持多行</p>
|
||||
<pre class="bg-white dark:bg-gray-800 p-2 rounded border text-xs">
|
||||
电影1
|
||||
https://pan.baidu.com/s/123456 # 百度网盘 电影1
|
||||
https://pan.quark.com/s/123456 # 夸克网盘 电影1
|
||||
电影标题2
|
||||
https://pan.baidu.com/s/789012
|
||||
电视剧标题3
|
||||
https://pan.quark.cn/s/345678</pre>
|
||||
<p class="mt-2 text-xs text-red-600 dark:text-red-400">
|
||||
<i class="fas fa-exclamation-triangle mr-1"></i>
|
||||
注意:标题为必填项,不能为空
|
||||
</p>
|
||||
<p class="mt-2 text-xs text-red-600 dark:text-red-400">
|
||||
<i class="fas fa-exclamation-triangle mr-1"></i>
|
||||
注意:标题为必填项,不能为空
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-4 flex-1 w-1">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">资源内容:</label>
|
||||
<textarea v-model="batchInput" rows="15"
|
||||
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-900 dark:text-gray-100"
|
||||
placeholder="请输入资源内容,格式:标题和URL两行为一组..."></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mb-4">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">资源内容:</label>
|
||||
<textarea
|
||||
v-model="batchInput"
|
||||
rows="15"
|
||||
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-700 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-900 dark:text-gray-100"
|
||||
placeholder="请输入资源内容,格式:标题和URL两行为一组..."
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div class="flex justify-end space-x-3 pt-4">
|
||||
<button type="button" @click="$emit('cancel')" class="btn-secondary">取消</button>
|
||||
<button type="button" @click="handleSubmit" class="btn-primary" :disabled="loading">
|
||||
@@ -52,37 +53,18 @@ const validateInput = () => {
|
||||
if (!batchInput.value.trim()) {
|
||||
throw new Error('请输入资源内容')
|
||||
}
|
||||
|
||||
|
||||
const lines = batchInput.value.split(/\r?\n/).map(line => line.trim()).filter(Boolean)
|
||||
|
||||
|
||||
if (lines.length === 0) {
|
||||
throw new Error('请输入有效的资源内容')
|
||||
}
|
||||
|
||||
// 检查是否为偶数行(标题+URL为一组)
|
||||
if (lines.length % 2 !== 0) {
|
||||
throw new Error('资源格式错误:标题和URL必须成对出现,请检查是否缺少标题或URL')
|
||||
}
|
||||
|
||||
// 检查每组的标题是否为空
|
||||
for (let i = 0; i < lines.length; i += 2) {
|
||||
const title = lines[i]
|
||||
const url = lines[i + 1]
|
||||
|
||||
if (!title) {
|
||||
throw new Error(`第${i + 1}行标题不能为空`)
|
||||
}
|
||||
|
||||
if (!url) {
|
||||
throw new Error(`第${i + 2}行URL不能为空`)
|
||||
}
|
||||
|
||||
// 验证URL格式
|
||||
try {
|
||||
new URL(url)
|
||||
} catch {
|
||||
throw new Error(`第${i + 2}行URL格式无效: ${url}`)
|
||||
}
|
||||
|
||||
// 首行必须为标题
|
||||
if (/^https?:\/\//i.test(lines[0])) {
|
||||
// 你可以用 alert、ElMessage 或其它方式提示
|
||||
alert('首行必须为标题,不能为链接!')
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,25 +73,42 @@ const handleSubmit = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
validateInput()
|
||||
|
||||
|
||||
// 解析输入内容
|
||||
const lines = batchInput.value.split(/\r?\n/).map(line => line.trim()).filter(Boolean)
|
||||
const resources = []
|
||||
|
||||
for (let i = 0; i < lines.length; i += 2) {
|
||||
const title = lines[i]
|
||||
const url = lines[i + 1]
|
||||
|
||||
|
||||
let currentTitle = ''
|
||||
let currentUrls = []
|
||||
|
||||
for (const line of lines) {
|
||||
// 判断是否为 url(以 http/https 开头)
|
||||
if (/^https?:\/\//i.test(line)) {
|
||||
currentUrls.push(line)
|
||||
} else {
|
||||
// 新标题,先保存上一个
|
||||
if (currentTitle && currentUrls.length) {
|
||||
resources.push({
|
||||
title: currentTitle,
|
||||
url: currentUrls.slice()
|
||||
})
|
||||
}
|
||||
currentTitle = line
|
||||
currentUrls = []
|
||||
}
|
||||
}
|
||||
// 处理最后一组
|
||||
if (currentTitle && currentUrls.length) {
|
||||
resources.push({
|
||||
title: title,
|
||||
url: url,
|
||||
source: '批量添加'
|
||||
title: currentTitle,
|
||||
url: currentUrls.slice()
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// 调用API添加资源
|
||||
const res: any = await readyResourceApi.batchCreateReadyResources(resources)
|
||||
emit('success', `成功添加 ${res.count || resources.length} 个资源,资源已进入待处理列表,处理完成后会自动入库`)
|
||||
const res: any = await readyResourceApi.batchCreateReadyResources({resources})
|
||||
console.log(res)
|
||||
emit('success', res.message)
|
||||
batchInput.value = ''
|
||||
} catch (e: any) {
|
||||
emit('error', e.message || '批量添加失败')
|
||||
@@ -127,4 +126,4 @@ const handleSubmit = async () => {
|
||||
.btn-secondary {
|
||||
@apply px-4 py-2 bg-gray-500 hover:bg-gray-600 text-white rounded-md transition-colors;
|
||||
}
|
||||
</style>
|
||||
</style>
|
||||
@@ -96,14 +96,16 @@ import QRCode from 'qrcode'
|
||||
|
||||
interface Props {
|
||||
visible: boolean
|
||||
url: string
|
||||
url?: string
|
||||
}
|
||||
|
||||
interface Emits {
|
||||
(e: 'close'): void
|
||||
}
|
||||
|
||||
const props = defineProps<Props>()
|
||||
const props = withDefaults(defineProps<Props>(), {
|
||||
url: ''
|
||||
})
|
||||
const emit = defineEmits<Emits>()
|
||||
|
||||
const qrCanvas = ref<HTMLCanvasElement>()
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
required
|
||||
></textarea>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
支持百度网盘、阿里云盘、夸克网盘等链接
|
||||
支持百度网盘、阿里云盘、夸克网盘等链接,每行一个链接
|
||||
</p>
|
||||
</div>
|
||||
|
||||
@@ -205,7 +205,7 @@ const clearForm = () => {
|
||||
newTag.value = ''
|
||||
}
|
||||
|
||||
// 单个添加提交
|
||||
// 单个添加提交 - 更新为使用批量添加方法
|
||||
const handleSubmit = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
@@ -214,23 +214,23 @@ const handleSubmit = async () => {
|
||||
// 多行链接处理
|
||||
const urls = form.value.url.split(/\r?\n/).map(l => l.trim()).filter(Boolean)
|
||||
|
||||
// 为每个URL创建一个资源
|
||||
for (const url of urls) {
|
||||
const resourceData = {
|
||||
title: form.value.title, // 标题必填
|
||||
description: form.value.description || undefined, // 添加描述
|
||||
url: url,
|
||||
// 使用批量添加方法,将多个URL作为一个资源的多个链接
|
||||
const resourceData = {
|
||||
resources: [{
|
||||
title: form.value.title || undefined, // 后端期望 *string 类型
|
||||
description: form.value.description || '',
|
||||
url: urls, // 现在 url 是一个数组
|
||||
category: form.value.category || '',
|
||||
tags: form.value.tags.join(','), // 转换为逗号分隔的字符串
|
||||
img: form.value.img || '',
|
||||
source: form.value.source || '手动添加',
|
||||
extra: form.value.extra || '',
|
||||
}
|
||||
|
||||
await readyResourceApi.createReadyResource(resourceData)
|
||||
}]
|
||||
}
|
||||
|
||||
emit('success', `成功添加 ${urls.length} 个资源到待处理列表`)
|
||||
const response = await readyResourceApi.batchCreateReadyResources(resourceData)
|
||||
|
||||
emit('success', `成功添加资源,包含 ${urls.length} 个链接`)
|
||||
clearForm()
|
||||
} catch (e: any) {
|
||||
emit('error', e.message || '添加失败')
|
||||
|
||||
@@ -109,7 +109,7 @@
|
||||
<script setup lang="ts">
|
||||
interface VersionInfo {
|
||||
version: string
|
||||
build_time: string
|
||||
build_time: string | Date
|
||||
git_commit: string
|
||||
git_branch: string
|
||||
go_version: string
|
||||
@@ -182,13 +182,13 @@ const refreshVersion = () => {
|
||||
}
|
||||
|
||||
// 格式化时间
|
||||
const formatTime = (timeStr: string) => {
|
||||
if (!timeStr) return 'N/A'
|
||||
const formatTime = (timeInput: string | Date) => {
|
||||
if (!timeInput) return 'N/A'
|
||||
try {
|
||||
const date = new Date(timeStr)
|
||||
const date = timeInput instanceof Date ? timeInput : new Date(timeInput)
|
||||
return date.toLocaleString('zh-CN')
|
||||
} catch {
|
||||
return timeStr
|
||||
return String(timeInput)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { useApiFetch } from './useApiFetch'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
|
||||
// 统一响应解析函数
|
||||
export const parseApiResponse = <T>(response: any): T => {
|
||||
console.log('parseApiResponse - 原始响应:', response)
|
||||
log('parseApiResponse - 原始响应:', response)
|
||||
|
||||
// 检查是否是新的统一响应格式
|
||||
if (response && typeof response === 'object' && 'code' in response && 'data' in response) {
|
||||
@@ -15,6 +18,11 @@ export const parseApiResponse = <T>(response: any): T => {
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否是包含items字段的响应格式(如分类接口)
|
||||
if (response && typeof response === 'object' && 'items' in response) {
|
||||
return response
|
||||
}
|
||||
|
||||
// 检查是否是包含success字段的响应格式(如登录接口)
|
||||
if (response && typeof response === 'object' && 'success' in response && 'data' in response) {
|
||||
if (response.success) {
|
||||
@@ -37,700 +45,130 @@ export const parseApiResponse = <T>(response: any): T => {
|
||||
return response
|
||||
}
|
||||
|
||||
// 使用 $fetch 替代 axios,更好地处理 SSR
|
||||
export const useResourceApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getResources = async (params?: any) => {
|
||||
const response = await $fetch('/resources', {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getResource = async (id: number) => {
|
||||
const response = await $fetch(`/resources/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createResource = async (data: any) => {
|
||||
const response = await $fetch('/resources', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updateResource = async (id: number, data: any) => {
|
||||
const response = await $fetch(`/resources/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deleteResource = async (id: number) => {
|
||||
const response = await $fetch(`/resources/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const searchResources = async (params: any) => {
|
||||
const response = await $fetch('/search', {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getResourcesByPan = async (panId: number, params?: any) => {
|
||||
const response = await $fetch('/resources', {
|
||||
baseURL: config.public.apiBase,
|
||||
params: { ...params, pan_id: panId },
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getResources,
|
||||
getResource,
|
||||
createResource,
|
||||
updateResource,
|
||||
deleteResource,
|
||||
searchResources,
|
||||
getResourcesByPan,
|
||||
}
|
||||
const getResources = (params?: any) => useApiFetch('/resources', { params }).then(parseApiResponse)
|
||||
const getResource = (id: number) => useApiFetch(`/resources/${id}`).then(parseApiResponse)
|
||||
const createResource = (data: any) => useApiFetch('/resources', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const updateResource = (id: number, data: any) => useApiFetch(`/resources/${id}`, { method: 'PUT', body: data }).then(parseApiResponse)
|
||||
const deleteResource = (id: number) => useApiFetch(`/resources/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
const searchResources = (params: any) => useApiFetch('/search', { params }).then(parseApiResponse)
|
||||
const getResourcesByPan = (panId: number, params?: any) => useApiFetch('/resources', { params: { ...params, pan_id: panId } }).then(parseApiResponse)
|
||||
// 新增:统一的资源访问次数上报
|
||||
const incrementViewCount = (id: number) => useApiFetch(`/resources/${id}/view`, { method: 'POST' })
|
||||
// 新增:批量删除资源
|
||||
const batchDeleteResources = (ids: number[]) => useApiFetch('/resources/batch', { method: 'DELETE', body: { ids } }).then(parseApiResponse)
|
||||
return { getResources, getResource, createResource, updateResource, deleteResource, searchResources, getResourcesByPan, incrementViewCount, batchDeleteResources }
|
||||
}
|
||||
|
||||
// 认证相关API
|
||||
export const useAuthApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const login = async (data: any) => {
|
||||
const response = await $fetch('/auth/login', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const register = async (data: any) => {
|
||||
const response = await $fetch('/auth/register', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getProfile = async () => {
|
||||
const token = localStorage.getItem('token')
|
||||
const response = await $fetch('/auth/profile', {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: token ? { Authorization: `Bearer ${token}` } : {}
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
login,
|
||||
register,
|
||||
getProfile,
|
||||
const login = (data: any) => useApiFetch('/auth/login', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const register = (data: any) => useApiFetch('/auth/register', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const getProfile = () => {
|
||||
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : ''
|
||||
return useApiFetch('/auth/profile', { headers: token ? { Authorization: `Bearer ${token}` } : {} }).then(parseApiResponse)
|
||||
}
|
||||
return { login, register, getProfile }
|
||||
}
|
||||
|
||||
// 分类相关API
|
||||
export const useCategoryApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getCategories = async () => {
|
||||
const response = await $fetch('/categories', {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createCategory = async (data: any) => {
|
||||
const response = await $fetch('/categories', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updateCategory = async (id: number, data: any) => {
|
||||
const response = await $fetch(`/categories/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deleteCategory = async (id: number) => {
|
||||
const response = await $fetch(`/categories/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getCategories,
|
||||
createCategory,
|
||||
updateCategory,
|
||||
deleteCategory,
|
||||
}
|
||||
const getCategories = (params?: any) => useApiFetch('/categories', { params }).then(parseApiResponse)
|
||||
const createCategory = (data: any) => useApiFetch('/categories', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const updateCategory = (id: number, data: any) => useApiFetch(`/categories/${id}`, { method: 'PUT', body: data }).then(parseApiResponse)
|
||||
const deleteCategory = (id: number) => useApiFetch(`/categories/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
return { getCategories, createCategory, updateCategory, deleteCategory }
|
||||
}
|
||||
|
||||
// 平台相关API
|
||||
export const usePanApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getPans = async () => {
|
||||
const response = await $fetch('/pans', {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getPan = async (id: number) => {
|
||||
const response = await $fetch(`/pans/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createPan = async (data: any) => {
|
||||
const response = await $fetch('/pans', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updatePan = async (id: number, data: any) => {
|
||||
const response = await $fetch(`/pans/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deletePan = async (id: number) => {
|
||||
const response = await $fetch(`/pans/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getPans,
|
||||
getPan,
|
||||
createPan,
|
||||
updatePan,
|
||||
deletePan,
|
||||
}
|
||||
const getPans = () => useApiFetch('/pans').then(parseApiResponse)
|
||||
const getPan = (id: number) => useApiFetch(`/pans/${id}`).then(parseApiResponse)
|
||||
const createPan = (data: any) => useApiFetch('/pans', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const updatePan = (id: number, data: any) => useApiFetch(`/pans/${id}`, { method: 'PUT', body: data }).then(parseApiResponse)
|
||||
const deletePan = (id: number) => useApiFetch(`/pans/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
return { getPans, getPan, createPan, updatePan, deletePan }
|
||||
}
|
||||
|
||||
// Cookie相关API
|
||||
export const useCksApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getCks = async (params?: any) => {
|
||||
const response = await $fetch('/cks', {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getCksByID = async (id: number) => {
|
||||
const response = await $fetch(`/cks/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createCks = async (data: any) => {
|
||||
const response = await $fetch('/cks', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updateCks = async (id: number, data: any) => {
|
||||
const response = await $fetch(`/cks/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deleteCks = async (id: number) => {
|
||||
const response = await $fetch(`/cks/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const refreshCapacity = async (id: number) => {
|
||||
const response = await $fetch(`/cks/${id}/refresh-capacity`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getCks,
|
||||
getCksByID,
|
||||
createCks,
|
||||
updateCks,
|
||||
deleteCks,
|
||||
refreshCapacity,
|
||||
}
|
||||
const getCks = (params?: any) => useApiFetch('/cks', { params }).then(parseApiResponse)
|
||||
const getCksByID = (id: number) => useApiFetch(`/cks/${id}`).then(parseApiResponse)
|
||||
const createCks = (data: any) => useApiFetch('/cks', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const updateCks = (id: number, data: any) => useApiFetch(`/cks/${id}`, { method: 'PUT', body: data }).then(parseApiResponse)
|
||||
const deleteCks = (id: number) => useApiFetch(`/cks/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
const refreshCapacity = (id: number) => useApiFetch(`/cks/${id}/refresh-capacity`, { method: 'POST' }).then(parseApiResponse)
|
||||
return { getCks, getCksByID, createCks, updateCks, deleteCks, refreshCapacity }
|
||||
}
|
||||
|
||||
// 标签相关API
|
||||
export const useTagApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getTags = async () => {
|
||||
const response = await $fetch('/tags', {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getTagsByCategory = async (categoryId: number, params?: any) => {
|
||||
const response = await $fetch(`/categories/${categoryId}/tags`, {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getTag = async (id: number) => {
|
||||
const response = await $fetch(`/tags/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createTag = async (data: any) => {
|
||||
const response = await $fetch('/tags', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updateTag = async (id: number, data: any) => {
|
||||
const response = await $fetch(`/tags/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deleteTag = async (id: number) => {
|
||||
const response = await $fetch(`/tags/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getResourceTags = async (resourceId: number) => {
|
||||
const response = await $fetch(`/resources/${resourceId}/tags`, {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getTags,
|
||||
getTagsByCategory,
|
||||
getTag,
|
||||
createTag,
|
||||
updateTag,
|
||||
deleteTag,
|
||||
getResourceTags,
|
||||
}
|
||||
const getTags = (params?: any) => useApiFetch('/tags', { params }).then(parseApiResponse)
|
||||
const getTagsByCategory = (categoryId: number, params?: any) => useApiFetch(`/categories/${categoryId}/tags`, { params }).then(parseApiResponse)
|
||||
const getTag = (id: number) => useApiFetch(`/tags/${id}`).then(parseApiResponse)
|
||||
const createTag = (data: any) => useApiFetch('/tags', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const updateTag = (id: number, data: any) => useApiFetch(`/tags/${id}`, { method: 'PUT', body: data }).then(parseApiResponse)
|
||||
const deleteTag = (id: number) => useApiFetch(`/tags/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
const getResourceTags = (resourceId: number) => useApiFetch(`/resources/${resourceId}/tags`).then(parseApiResponse)
|
||||
return { getTags, getTagsByCategory, getTag, createTag, updateTag, deleteTag, getResourceTags }
|
||||
}
|
||||
|
||||
// 待处理资源相关API
|
||||
export const useReadyResourceApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getReadyResources = async (params?: any) => {
|
||||
const response = await $fetch('/ready-resources', {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createReadyResource = async (data: any) => {
|
||||
const response = await $fetch('/ready-resources', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const batchCreateReadyResources = async (data: any) => {
|
||||
const response = await $fetch('/ready-resources/batch', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createReadyResourcesFromText = async (text: string) => {
|
||||
const getReadyResources = (params?: any) => useApiFetch('/ready-resources', { params }).then(parseApiResponse)
|
||||
const createReadyResource = (data: any) => useApiFetch('/ready-resources', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const batchCreateReadyResources = (data: any) => useApiFetch('/ready-resources/batch', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const createReadyResourcesFromText = (text: string) => {
|
||||
const formData = new FormData()
|
||||
formData.append('text', text)
|
||||
|
||||
const response = await $fetch('/ready-resources/text', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deleteReadyResource = async (id: number) => {
|
||||
const response = await $fetch(`/ready-resources/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const clearReadyResources = async () => {
|
||||
const response = await $fetch('/ready-resources', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getReadyResources,
|
||||
createReadyResource,
|
||||
batchCreateReadyResources,
|
||||
createReadyResourcesFromText,
|
||||
deleteReadyResource,
|
||||
clearReadyResources,
|
||||
return useApiFetch('/ready-resources/text', { method: 'POST', body: formData }).then(parseApiResponse)
|
||||
}
|
||||
const deleteReadyResource = (id: number) => useApiFetch(`/ready-resources/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
const clearReadyResources = () => useApiFetch('/ready-resources', { method: 'DELETE' }).then(parseApiResponse)
|
||||
return { getReadyResources, createReadyResource, batchCreateReadyResources, createReadyResourcesFromText, deleteReadyResource, clearReadyResources }
|
||||
}
|
||||
|
||||
// 统计相关API
|
||||
export const useStatsApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getStats = async () => {
|
||||
const response = await $fetch('/stats', {
|
||||
baseURL: config.public.apiBase,
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getStats,
|
||||
}
|
||||
const getStats = () => useApiFetch('/stats').then(parseApiResponse)
|
||||
return { getStats }
|
||||
}
|
||||
|
||||
// 系统配置相关API
|
||||
export const useSystemConfigApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getSystemConfig = async () => {
|
||||
const response = await $fetch('/system/config', {
|
||||
baseURL: config.public.apiBase,
|
||||
// GET接口不需要认证头
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updateSystemConfig = async (data: any) => {
|
||||
const authHeaders = getAuthHeaders()
|
||||
console.log('updateSystemConfig - authHeaders:', authHeaders)
|
||||
console.log('updateSystemConfig - token exists:', !!authHeaders.Authorization)
|
||||
|
||||
const response = await $fetch('/system/config', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: authHeaders as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getSystemConfig,
|
||||
updateSystemConfig,
|
||||
}
|
||||
const getSystemConfig = () => useApiFetch('/system/config').then(parseApiResponse)
|
||||
const updateSystemConfig = (data: any) => useApiFetch('/system/config', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const toggleAutoProcess = (enabled: boolean) => useApiFetch('/system/config/toggle-auto-process', { method: 'POST', body: { auto_process_ready_resources: enabled } }).then(parseApiResponse)
|
||||
return { getSystemConfig, updateSystemConfig, toggleAutoProcess }
|
||||
}
|
||||
|
||||
// 热播剧相关API
|
||||
export const useHotDramaApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getHotDramas = async (params?: any) => {
|
||||
const response = await $fetch('/hot-dramas', {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createHotDrama = async (data: any) => {
|
||||
const response = await $fetch('/hot-dramas', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updateHotDrama = async (id: number, data: any) => {
|
||||
const response = await $fetch(`/hot-dramas/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deleteHotDrama = async (id: number) => {
|
||||
const response = await $fetch(`/hot-dramas/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const fetchHotDramas = async () => {
|
||||
const response = await $fetch('/hot-dramas/fetch', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getHotDramas,
|
||||
createHotDrama,
|
||||
updateHotDrama,
|
||||
deleteHotDrama,
|
||||
fetchHotDramas,
|
||||
}
|
||||
const getHotDramas = (params?: any) => useApiFetch('/hot-dramas', { params }).then(parseApiResponse)
|
||||
const createHotDrama = (data: any) => useApiFetch('/hot-dramas', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const updateHotDrama = (id: number, data: any) => useApiFetch(`/hot-dramas/${id}`, { method: 'PUT', body: data }).then(parseApiResponse)
|
||||
const deleteHotDrama = (id: number) => useApiFetch(`/hot-dramas/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
const fetchHotDramas = () => useApiFetch('/hot-dramas/fetch', { method: 'POST' }).then(parseApiResponse)
|
||||
return { getHotDramas, createHotDrama, updateHotDrama, deleteHotDrama, fetchHotDramas }
|
||||
}
|
||||
|
||||
// 监控相关API
|
||||
export const useMonitorApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getPerformanceStats = async () => {
|
||||
const response = await $fetch('/performance', {
|
||||
baseURL: config.public.apiBase,
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
const getPerformanceStats = () => useApiFetch('/performance').then(parseApiResponse)
|
||||
const getSystemInfo = () => useApiFetch('/system/info').then(parseApiResponse)
|
||||
const getBasicStats = () => useApiFetch('/stats').then(parseApiResponse)
|
||||
return { getPerformanceStats, getSystemInfo, getBasicStats }
|
||||
}
|
||||
|
||||
const getSystemInfo = async () => {
|
||||
const response = await $fetch('/system/info', {
|
||||
baseURL: config.public.apiBase,
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const getBasicStats = async () => {
|
||||
const response = await $fetch('/stats', {
|
||||
baseURL: config.public.apiBase,
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getPerformanceStats,
|
||||
getSystemInfo,
|
||||
getBasicStats,
|
||||
}
|
||||
export const useUserApi = () => {
|
||||
const getUsers = (params?: any) => useApiFetch('/users', { params }).then(parseApiResponse)
|
||||
const getUser = (id: number) => useApiFetch(`/users/${id}`).then(parseApiResponse)
|
||||
const createUser = (data: any) => useApiFetch('/users', { method: 'POST', body: data }).then(parseApiResponse)
|
||||
const updateUser = (id: number, data: any) => useApiFetch(`/users/${id}`, { method: 'PUT', body: data }).then(parseApiResponse)
|
||||
const deleteUser = (id: number) => useApiFetch(`/users/${id}`, { method: 'DELETE' }).then(parseApiResponse)
|
||||
const changePassword = (id: number, newPassword: string) => useApiFetch(`/users/${id}/password`, { method: 'PUT', body: { new_password: newPassword } }).then(parseApiResponse)
|
||||
return { getUsers, getUser, createUser, updateUser, deleteUser, changePassword }
|
||||
}
|
||||
|
||||
// 用户管理相关API
|
||||
export const useUserApi = () => {
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const getAuthHeaders = () => {
|
||||
const userStore = useUserStore()
|
||||
return userStore.authHeaders
|
||||
}
|
||||
|
||||
const getUsers = async (params?: any) => {
|
||||
const response = await $fetch('/users', {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
// 公开获取系统配置API
|
||||
export const usePublicSystemConfigApi = () => {
|
||||
const getPublicSystemConfig = () => useApiFetch('/public/system-config').then(res => res)
|
||||
return { getPublicSystemConfig }
|
||||
}
|
||||
|
||||
const getUser = async (id: number) => {
|
||||
const response = await $fetch(`/users/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const createUser = async (data: any) => {
|
||||
const response = await $fetch('/users', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const updateUser = async (id: number, data: any) => {
|
||||
const response = await $fetch(`/users/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: data,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const deleteUser = async (id: number) => {
|
||||
const response = await $fetch(`/users/${id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
const changePassword = async (id: number, newPassword: string) => {
|
||||
const response = await $fetch(`/users/${id}/password`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: { new_password: newPassword },
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
return parseApiResponse(response)
|
||||
}
|
||||
|
||||
return {
|
||||
getUsers,
|
||||
getUser,
|
||||
createUser,
|
||||
updateUser,
|
||||
deleteUser,
|
||||
changePassword,
|
||||
// 日志函数:只在开发环境打印
|
||||
function log(...args: any[]) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
console.log(...args)
|
||||
}
|
||||
}
|
||||
63
web/composables/useApiFetch.ts
Normal file
63
web/composables/useApiFetch.ts
Normal file
@@ -0,0 +1,63 @@
|
||||
import { useRuntimeConfig } from '#app'
|
||||
import { useUserStore } from '~/stores/user'
|
||||
|
||||
export function useApiFetch<T = any>(
|
||||
url: string,
|
||||
options: any = {}
|
||||
): Promise<T> {
|
||||
const config = useRuntimeConfig()
|
||||
const userStore = useUserStore()
|
||||
const baseURL = process.server
|
||||
? String(config.public.apiServer)
|
||||
: String(config.public.apiBase)
|
||||
|
||||
// 自动带上 token
|
||||
const headers = {
|
||||
...(options.headers || {}),
|
||||
...(userStore.authHeaders || {})
|
||||
}
|
||||
|
||||
return $fetch<T>(url, {
|
||||
baseURL,
|
||||
...options,
|
||||
headers,
|
||||
onResponse({ response }) {
|
||||
if (response.status === 401 ||
|
||||
(response._data && (response._data.code === 401 || response._data.error === '无效的令牌'))
|
||||
) {
|
||||
userStore.logout()
|
||||
if (process.client) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
// 触发 onResponseError 逻辑
|
||||
throw Object.assign(new Error('登录已过期,请重新登录'), {
|
||||
data: response._data,
|
||||
status: response.status,
|
||||
})
|
||||
}
|
||||
|
||||
// 统一处理 code/message
|
||||
if (response._data && response._data.code && response._data.code !== 200) {
|
||||
throw new Error(response._data.message || '请求失败')
|
||||
}
|
||||
},
|
||||
onResponseError({ error }: { error: any }) {
|
||||
console.log('error', error)
|
||||
// 检查是否为"无效的令牌"错误
|
||||
if (error?.data?.error === '无效的令牌') {
|
||||
// 清除用户状态
|
||||
userStore.logout()
|
||||
// 跳转到登录页面
|
||||
if (process.client) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
throw new Error('登录已过期,请重新登录')
|
||||
}
|
||||
|
||||
// 统一错误提示
|
||||
// 你可以用 naive-ui 的 useMessage() 这里弹窗
|
||||
// useMessage().error(error.message)
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -40,16 +40,16 @@ export const useSeo = () => {
|
||||
if (systemConfig.value?.site_title) {
|
||||
return `${systemConfig.value.site_title} - ${pageTitle}`
|
||||
}
|
||||
return `${pageTitle} - 网盘资源数据库`
|
||||
return `${pageTitle} - 老九网盘资源数据库`
|
||||
}
|
||||
|
||||
// 生成页面元数据
|
||||
const generateMeta = (customMeta?: Record<string, string>) => {
|
||||
const defaultMeta = {
|
||||
description: systemConfig.value?.site_description || '专业的网盘资源数据库',
|
||||
description: systemConfig.value?.site_description || '专业的老九网盘资源数据库',
|
||||
keywords: systemConfig.value?.keywords || '网盘,资源管理,文件分享',
|
||||
author: systemConfig.value?.author || '系统管理员',
|
||||
copyright: systemConfig.value?.copyright || '© 2024 网盘资源数据库'
|
||||
copyright: systemConfig.value?.copyright || '© 2024 老九网盘资源数据库'
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -18,7 +18,7 @@ interface VersionResponse {
|
||||
|
||||
export const useVersion = () => {
|
||||
const versionInfo = ref<VersionInfo>({
|
||||
version: '1.0.0',
|
||||
version: '1.0.9',
|
||||
build_time: '',
|
||||
git_commit: 'unknown',
|
||||
git_branch: 'unknown',
|
||||
|
||||
@@ -33,6 +33,8 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useSystemConfigStore } from '~/stores/systemConfig'
|
||||
|
||||
// 页面加载状态
|
||||
const pageLoading = ref(false)
|
||||
|
||||
@@ -66,8 +68,9 @@ watch(() => route.path, () => {
|
||||
}, 300)
|
||||
})
|
||||
|
||||
// 页面加载时显示加载状态
|
||||
const systemConfigStore = useSystemConfigStore()
|
||||
onMounted(() => {
|
||||
systemConfigStore.initConfig()
|
||||
pageLoading.value = true
|
||||
setTimeout(() => {
|
||||
pageLoading.value = false
|
||||
|
||||
25
web/layouts/single.vue
Normal file
25
web/layouts/single.vue
Normal file
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<div class="forbidden-layout">
|
||||
<slot />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
|
||||
</script>
|
||||
|
||||
<style>
|
||||
body, html {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
.forbidden-layout {
|
||||
width: 100%;
|
||||
height: 100vh;
|
||||
overflow: hidden;
|
||||
}
|
||||
</style>
|
||||
13
web/middleware/anti-red.global.ts
Normal file
13
web/middleware/anti-red.global.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
export default defineNuxtRouteMiddleware((to, from) => {
|
||||
// 只在客户端执行
|
||||
if (process.client) {
|
||||
const ua = navigator.userAgent
|
||||
// 检测是否为QQ或微信内置浏览器
|
||||
if (['QQ/', 'MicroMessenger', 'WeiBo', 'DingTalk', 'Mail'].some(it => ua.includes(it))) {
|
||||
// 如果当前不在禁止访问页面,则跳转
|
||||
if (to.path !== '/forbidden') {
|
||||
return navigateTo('/forbidden')
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
@@ -25,7 +25,7 @@ export default defineNuxtConfig({
|
||||
})
|
||||
],
|
||||
optimizeDeps: {
|
||||
include: ['naive-ui', 'vueuc', 'date-fns'],
|
||||
include: ['vueuc', 'date-fns'],
|
||||
exclude: ["oxc-parser"] // 强制使用 WASM 版本
|
||||
}
|
||||
},
|
||||
@@ -38,11 +38,11 @@ export default defineNuxtConfig({
|
||||
],
|
||||
app: {
|
||||
head: {
|
||||
title: '开源网盘资源数据库',
|
||||
title: '老九网盘资源数据库',
|
||||
meta: [
|
||||
{ charset: 'utf-8' },
|
||||
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
|
||||
{ name: 'description', content: '开源网盘资源数据库 - 一个现代化的资源管理系统' }
|
||||
{ name: 'description', content: '老九网盘资源管理数据庫,现代化的网盘资源数据库,支持多网盘自动化转存分享,支持百度网盘,阿里云盘,夸克网盘, 天翼云盘,迅雷云盘,123云盘,115网盘,UC网盘' }
|
||||
],
|
||||
link: [
|
||||
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
|
||||
@@ -51,7 +51,10 @@ export default defineNuxtConfig({
|
||||
},
|
||||
runtimeConfig: {
|
||||
public: {
|
||||
apiBase: process.env.API_BASE || 'http://localhost:8080/api'
|
||||
// 开发环境:直接访问后端,生产环境:通过 Nginx 反代
|
||||
apiBase: process.env.NODE_ENV === 'production' ? '/api' : 'http://localhost:8080/api',
|
||||
// 服务端:开发环境直接访问,生产环境容器内访问
|
||||
apiServer: process.env.NODE_ENV === 'production' ? 'http://backend:8080/api' : 'http://localhost:8080/api'
|
||||
}
|
||||
},
|
||||
build: {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "res-db-web",
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.9",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -1,29 +1,5 @@
|
||||
<template>
|
||||
<div class="min-h-screen bg-gray-50 dark:bg-gray-900 text-gray-800 dark:text-gray-100">
|
||||
<!-- 页面头部 -->
|
||||
<div class="bg-white dark:bg-gray-800 shadow-sm border-b border-gray-200 dark:border-gray-700">
|
||||
<div class="max-w-4xl mx-auto px-4 py-4">
|
||||
<div class="flex items-center justify-between">
|
||||
<div class="flex items-center space-x-4">
|
||||
<button
|
||||
@click="$router.back()"
|
||||
class="text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100"
|
||||
>
|
||||
<i class="fas fa-arrow-left text-xl"></i>
|
||||
</button>
|
||||
<h1 class="text-2xl font-bold text-gray-900 dark:text-gray-100">添加资源</h1>
|
||||
</div>
|
||||
<div class="flex items-center space-x-2">
|
||||
<NuxtLink
|
||||
to="/admin"
|
||||
class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-md transition-colors text-sm"
|
||||
>
|
||||
<i class="fas fa-cog mr-1"></i>管理后台
|
||||
</NuxtLink>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 主要内容 -->
|
||||
<div class="max-w-4xl mx-auto px-4 py-8">
|
||||
@@ -64,12 +40,6 @@
|
||||
@error="handleError"
|
||||
@cancel="handleCancel"
|
||||
/>
|
||||
|
||||
<!-- API说明 -->
|
||||
<ApiDocumentation
|
||||
v-else
|
||||
@cancel="handleCancel"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -83,7 +53,8 @@
|
||||
<script setup lang="ts">
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
import { ref, onMounted } from 'vue'
|
||||
@@ -103,7 +74,6 @@ const errorMsg = ref('')
|
||||
const tabs = [
|
||||
{ label: '批量添加', value: 'batch' },
|
||||
{ label: '单个添加', value: 'single' },
|
||||
{ label: 'API说明', value: 'api' },
|
||||
]
|
||||
const mode = ref('batch')
|
||||
|
||||
@@ -133,7 +103,7 @@ const handleCancel = () => {
|
||||
|
||||
// 设置页面标题
|
||||
useHead({
|
||||
title: '添加资源 - 网盘资源数据库'
|
||||
title: '添加资源 - 老九网盘资源数据库'
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -192,12 +192,15 @@
|
||||
<script setup lang="ts">
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
const userStore = useUserStore()
|
||||
const config = useRuntimeConfig()
|
||||
import { useCategoryApi } from '~/composables/useApi'
|
||||
const categoryApi = useCategoryApi()
|
||||
|
||||
// 页面状态
|
||||
const pageLoading = ref(true)
|
||||
@@ -232,7 +235,7 @@ const getAuthHeaders = () => {
|
||||
|
||||
// 页面元数据
|
||||
useHead({
|
||||
title: '分类管理 - 网盘资源数据库',
|
||||
title: '分类管理 - 老九网盘资源数据库',
|
||||
meta: [
|
||||
{ name: 'description', content: '管理网盘资源分类' },
|
||||
{ name: 'keywords', content: '分类管理,资源管理' }
|
||||
@@ -257,25 +260,34 @@ const fetchCategories = async () => {
|
||||
page_size: pageSize.value,
|
||||
search: searchQuery.value
|
||||
}
|
||||
|
||||
const response = await $fetch('/categories', {
|
||||
baseURL: config.public.apiBase,
|
||||
params
|
||||
})
|
||||
|
||||
|
||||
// 解析响应
|
||||
if (response && typeof response === 'object' && 'code' in response && response.code === 200) {
|
||||
categories.value = response.data.items || []
|
||||
totalCount.value = response.data.total || 0
|
||||
totalPages.value = Math.ceil(totalCount.value / pageSize.value)
|
||||
} else {
|
||||
categories.value = response.items || []
|
||||
console.log('获取分类列表参数:', params)
|
||||
const response = await categoryApi.getCategories(params)
|
||||
console.log('分类接口响应:', response)
|
||||
|
||||
// 适配后端API响应格式
|
||||
if (response && response.items) {
|
||||
console.log('使用 items 格式:', response.items)
|
||||
categories.value = response.items
|
||||
totalCount.value = response.total || 0
|
||||
totalPages.value = Math.ceil(totalCount.value / pageSize.value)
|
||||
} else if (Array.isArray(response)) {
|
||||
console.log('使用数组格式:', response)
|
||||
// 兼容旧格式
|
||||
categories.value = response
|
||||
totalCount.value = response.length
|
||||
totalPages.value = 1
|
||||
} else {
|
||||
console.log('使用默认格式:', response)
|
||||
categories.value = []
|
||||
totalCount.value = 0
|
||||
totalPages.value = 1
|
||||
}
|
||||
console.log('最终分类数据:', categories.value)
|
||||
} catch (error) {
|
||||
console.error('获取分类列表失败:', error)
|
||||
categories.value = []
|
||||
totalCount.value = 0
|
||||
totalPages.value = 1
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -318,13 +330,8 @@ const deleteCategory = async (categoryId: number) => {
|
||||
if (!confirm(`确定要删除分类吗?`)) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await $fetch(`/categories/${categoryId}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
await categoryApi.deleteCategory(categoryId)
|
||||
await fetchCategories()
|
||||
} catch (error) {
|
||||
console.error('删除分类失败:', error)
|
||||
@@ -335,23 +342,11 @@ const deleteCategory = async (categoryId: number) => {
|
||||
const handleSubmit = async () => {
|
||||
try {
|
||||
submitting.value = true
|
||||
|
||||
if (editingCategory.value) {
|
||||
await $fetch(`/categories/${editingCategory.value.id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: formData.value,
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
await categoryApi.updateCategory(editingCategory.value.id, formData.value)
|
||||
} else {
|
||||
await $fetch('/categories', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: formData.value,
|
||||
headers: getAuthHeaders()
|
||||
})
|
||||
await categoryApi.createCategory(formData.value)
|
||||
}
|
||||
|
||||
closeModal()
|
||||
await fetchCategories()
|
||||
} catch (error) {
|
||||
|
||||
@@ -117,6 +117,14 @@
|
||||
</td>
|
||||
<td class="px-4 py-3 text-sm">
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
@click="toggleStatus(cks)"
|
||||
:class="cks.is_valid ? 'text-orange-600 hover:text-orange-800 dark:text-orange-400 dark:hover:text-orange-300' : 'text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300'"
|
||||
class="transition-colors"
|
||||
:title="cks.is_valid ? '禁用账号' : '启用账号'"
|
||||
>
|
||||
<i :class="cks.is_valid ? 'fas fa-ban' : 'fas fa-check'"></i>
|
||||
</button>
|
||||
<button
|
||||
@click="refreshCapacity(cks.id)"
|
||||
class="text-green-600 hover:text-green-800 dark:text-green-400 dark:hover:text-green-300 transition-colors"
|
||||
@@ -287,7 +295,8 @@
|
||||
|
||||
<script setup>
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
@@ -315,9 +324,14 @@ const pageLoading = ref(true)
|
||||
const submitting = ref(false)
|
||||
const platform = ref(null)
|
||||
|
||||
const { data: pansData } = await useAsyncData('pans', () => $fetch('/api/pans'))
|
||||
import { useCksApi, usePanApi } from '~/composables/useApi'
|
||||
const cksApi = useCksApi()
|
||||
const panApi = usePanApi()
|
||||
|
||||
const { data: pansData } = await useAsyncData('pans', () => panApi.getPans())
|
||||
const pans = computed(() => {
|
||||
return (pansData.value).data.list || []
|
||||
// 统一接口格式后直接为数组
|
||||
return Array.isArray(pansData.value) ? pansData.value : (pansData.value?.list || [])
|
||||
})
|
||||
const platformOptions = computed(() => {
|
||||
return pans.value.map(pan => ({
|
||||
@@ -339,10 +353,10 @@ const checkAuth = () => {
|
||||
const fetchCks = async () => {
|
||||
loading.value = true
|
||||
try {
|
||||
const { useCksApi } = await import('~/composables/useApi')
|
||||
const cksApi = useCksApi()
|
||||
console.log('开始获取账号列表...')
|
||||
const response = await cksApi.getCks()
|
||||
cksList.value = Array.isArray(response) ? response : []
|
||||
console.log('获取账号列表成功,数据:', cksList.value)
|
||||
} catch (error) {
|
||||
console.error('获取账号列表失败:', error)
|
||||
} finally {
|
||||
@@ -354,8 +368,6 @@ const fetchCks = async () => {
|
||||
// 获取平台列表
|
||||
const fetchPlatforms = async () => {
|
||||
try {
|
||||
const { usePanApi } = await import('~/composables/useApi')
|
||||
const panApi = usePanApi()
|
||||
const response = await panApi.getPans()
|
||||
platforms.value = Array.isArray(response) ? response : []
|
||||
} catch (error) {
|
||||
@@ -367,8 +379,6 @@ const fetchPlatforms = async () => {
|
||||
const createCks = async () => {
|
||||
submitting.value = true
|
||||
try {
|
||||
const { useCksApi } = await import('~/composables/useApi')
|
||||
const cksApi = useCksApi()
|
||||
await cksApi.createCks(form.value)
|
||||
await fetchCks()
|
||||
closeModal()
|
||||
@@ -384,8 +394,6 @@ const createCks = async () => {
|
||||
const updateCks = async () => {
|
||||
submitting.value = true
|
||||
try {
|
||||
const { useCksApi } = await import('~/composables/useApi')
|
||||
const cksApi = useCksApi()
|
||||
await cksApi.updateCks(editingCks.value.id, form.value)
|
||||
await fetchCks()
|
||||
closeModal()
|
||||
@@ -402,8 +410,6 @@ const deleteCks = async (id) => {
|
||||
if (!confirm('确定要删除这个账号吗?')) return
|
||||
|
||||
try {
|
||||
const { useCksApi } = await import('~/composables/useApi')
|
||||
const cksApi = useCksApi()
|
||||
await cksApi.deleteCks(id)
|
||||
await fetchCks()
|
||||
} catch (error) {
|
||||
@@ -417,8 +423,6 @@ const refreshCapacity = async (id) => {
|
||||
if (!confirm('确定要刷新此账号的容量信息吗?')) return
|
||||
|
||||
try {
|
||||
const { useCksApi } = await import('~/composables/useApi')
|
||||
const cksApi = useCksApi()
|
||||
await cksApi.refreshCapacity(id)
|
||||
await fetchCks()
|
||||
alert('容量信息已刷新!')
|
||||
@@ -428,6 +432,24 @@ const refreshCapacity = async (id) => {
|
||||
}
|
||||
}
|
||||
|
||||
// 切换账号状态
|
||||
const toggleStatus = async (cks) => {
|
||||
const newStatus = !cks.is_valid
|
||||
if (!confirm(`确定要${cks.is_valid ? '禁用' : '启用'}此账号吗?`)) return
|
||||
|
||||
try {
|
||||
console.log('切换状态 - 账号ID:', cks.id, '当前状态:', cks.is_valid, '新状态:', newStatus)
|
||||
await cksApi.updateCks(cks.id, { is_valid: newStatus })
|
||||
console.log('状态更新成功,正在刷新数据...')
|
||||
await fetchCks()
|
||||
console.log('数据刷新完成')
|
||||
alert(`账号已${newStatus ? '启用' : '禁用'}!`)
|
||||
} catch (error) {
|
||||
console.error('切换账号状态失败:', error)
|
||||
alert(`切换账号状态失败: ${error.message || '未知错误'}`)
|
||||
}
|
||||
}
|
||||
|
||||
// 编辑账号
|
||||
const editCks = (cks) => {
|
||||
editingCks.value = cks
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
<div class="space-y-2">
|
||||
<div class="flex flex-wrap gap-1 w-full text-left rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer">
|
||||
<div v-for="pan in pans" :key="pan.id" class="h-6 px-1 rounded-full bg-gray-100 dark:bg-gray-700 flex items-center justify-center">
|
||||
<span v-html="pan.icon"></span> {{ pan.name }}
|
||||
<span v-html="pan.icon"></span> {{ pan.name }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -237,22 +237,25 @@
|
||||
<script setup lang="ts">
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
// 用户状态管理
|
||||
const userStore = useUserStore()
|
||||
|
||||
// 统计数据
|
||||
const { data: statsData } = await useAsyncData('stats', () => $fetch('/api/stats'))
|
||||
const stats = computed(() => (statsData.value as any)?.data || {})
|
||||
import { useStatsApi, usePanApi } from '~/composables/useApi'
|
||||
|
||||
const statsApi = useStatsApi()
|
||||
const panApi = usePanApi()
|
||||
|
||||
const { data: statsData } = await useAsyncData('stats', () => statsApi.getStats())
|
||||
const stats = computed(() => (statsData.value as any) || {})
|
||||
|
||||
// 平台数据
|
||||
const { data: pansData } = await useAsyncData('pans', () => $fetch('/api/pans'))
|
||||
console.log()
|
||||
const pans = computed(() => {
|
||||
return (pansData.value as any).data.list || []
|
||||
})
|
||||
const { data: pansData } = await useAsyncData('pans', () => panApi.getPans())
|
||||
const pans = computed(() => (pansData.value as any) || [])
|
||||
|
||||
// 分类管理相关
|
||||
const goToCategoryManagement = () => {
|
||||
|
||||
@@ -14,22 +14,6 @@
|
||||
</div>
|
||||
|
||||
<div class="max-w-7xl mx-auto">
|
||||
<!-- 头部 -->
|
||||
<div class="bg-slate-800 dark:bg-gray-800 text-white dark:text-gray-100 rounded-lg shadow-lg p-4 sm:p-8 mb-4 sm:mb-8 text-center flex items-center">
|
||||
<nav class="mt-4 flex flex-col sm:flex-row justify-center gap-2 sm:gap-4">
|
||||
<NuxtLink
|
||||
to="/admin"
|
||||
class="w-full sm:w-auto px-4 py-2 bg-blue-600 hover:bg-blue-700 rounded-md transition-colors text-center flex items-center justify-center gap-2"
|
||||
>
|
||||
<i class="fas fa-arrow-left"></i> 返回
|
||||
</NuxtLink>
|
||||
</nav>
|
||||
<div class="flex-1">
|
||||
<h1 class="text-2xl sm:text-3xl font-bold">
|
||||
<NuxtLink to="/" class="text-white hover:text-gray-200 dark:hover:text-gray-300 no-underline">网盘资源数据库</NuxtLink>
|
||||
</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 自动处理配置状态 -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg p-4 mb-6">
|
||||
@@ -326,7 +310,8 @@ https://pan.baidu.com/s/345678</pre>
|
||||
<script setup lang="ts">
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
interface ReadyResource {
|
||||
@@ -350,12 +335,11 @@ const totalCount = ref(0)
|
||||
const totalPages = ref(0)
|
||||
|
||||
// 获取待处理资源API
|
||||
const { useReadyResourceApi } = await import('~/composables/useApi')
|
||||
import { useReadyResourceApi, useSystemConfigApi } from '~/composables/useApi'
|
||||
import { useSystemConfigStore } from '~/stores/systemConfig'
|
||||
const readyResourceApi = useReadyResourceApi()
|
||||
|
||||
// 获取系统配置API
|
||||
const { useSystemConfigApi } = await import('~/composables/useApi')
|
||||
const systemConfigApi = useSystemConfigApi()
|
||||
const systemConfigStore = useSystemConfigStore()
|
||||
|
||||
// 获取系统配置
|
||||
const systemConfig = ref<any>(null)
|
||||
@@ -364,6 +348,8 @@ const fetchSystemConfig = async () => {
|
||||
try {
|
||||
const response = await systemConfigApi.getSystemConfig()
|
||||
systemConfig.value = response
|
||||
// 同时更新 Pinia store
|
||||
systemConfigStore.setConfig(response)
|
||||
} catch (error) {
|
||||
console.error('获取系统配置失败:', error)
|
||||
}
|
||||
@@ -562,32 +548,18 @@ const toggleAutoProcess = async () => {
|
||||
updatingConfig.value = true
|
||||
try {
|
||||
const newValue = !systemConfig.value?.auto_process_ready_resources
|
||||
console.log('当前配置:', systemConfig.value)
|
||||
console.log('新值:', newValue)
|
||||
console.log('切换自动处理配置:', newValue)
|
||||
|
||||
// 先获取当前配置,然后只更新需要的字段
|
||||
const currentConfig = await systemConfigApi.getSystemConfig() as any
|
||||
console.log('获取到的当前配置:', currentConfig)
|
||||
|
||||
const updateData = {
|
||||
site_title: currentConfig.site_title || '',
|
||||
site_description: currentConfig.site_description || '',
|
||||
keywords: currentConfig.keywords || '',
|
||||
author: currentConfig.author || '',
|
||||
copyright: currentConfig.copyright || '',
|
||||
auto_process_ready_resources: newValue,
|
||||
auto_process_interval: currentConfig.auto_process_interval || 30,
|
||||
auto_transfer_enabled: currentConfig.auto_transfer_enabled || false,
|
||||
auto_fetch_hot_drama_enabled: currentConfig.auto_fetch_hot_drama_enabled || false,
|
||||
page_size: currentConfig.page_size || 100,
|
||||
maintenance_mode: currentConfig.maintenance_mode || false
|
||||
}
|
||||
|
||||
console.log('更新数据:', updateData)
|
||||
const response = await systemConfigApi.updateSystemConfig(updateData)
|
||||
console.log('更新响应:', response)
|
||||
// 使用专门的切换API
|
||||
const response = await systemConfigApi.toggleAutoProcess(newValue)
|
||||
console.log('切换响应:', response)
|
||||
|
||||
// 更新本地配置状态
|
||||
systemConfig.value = response
|
||||
|
||||
// 同时更新 Pinia store 中的系统配置
|
||||
systemConfigStore.setConfig(response)
|
||||
|
||||
alert(`自动处理配置已${newValue ? '开启' : '关闭'}`)
|
||||
} catch (error: any) {
|
||||
console.error('切换自动处理配置失败:', error)
|
||||
@@ -613,7 +585,7 @@ onMounted(async () => {
|
||||
|
||||
// 设置页面标题
|
||||
useHead({
|
||||
title: '待处理资源管理 - 网盘资源数据库'
|
||||
title: '待处理资源管理 - 老九网盘资源数据库'
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -364,7 +364,8 @@
|
||||
<script setup lang="ts">
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
interface Resource {
|
||||
@@ -420,10 +421,7 @@ const selectedResources = ref<number[]>([])
|
||||
const selectAll = ref(false)
|
||||
|
||||
// API
|
||||
const { useResourceApi } = await import('~/composables/useApi')
|
||||
const { usePanApi } = await import('~/composables/useApi')
|
||||
const { useCategoryApi } = await import('~/composables/useApi')
|
||||
const { useTagApi } = await import('~/composables/useApi')
|
||||
import { useResourceApi, usePanApi, useCategoryApi, useTagApi } from '~/composables/useApi'
|
||||
|
||||
const resourceApi = useResourceApi()
|
||||
const panApi = usePanApi()
|
||||
@@ -452,9 +450,10 @@ const fetchData = async () => {
|
||||
}
|
||||
|
||||
const response = await resourceApi.getResources(params) as any
|
||||
|
||||
if (response && response.resources) {
|
||||
resources.value = response.resources
|
||||
console.log('DEBUG', response)
|
||||
|
||||
if (response && response.data) {
|
||||
resources.value = response.data
|
||||
totalCount.value = response.total || 0
|
||||
totalPages.value = Math.ceil((response.total || 0) / pageSize.value)
|
||||
} else if (Array.isArray(response)) {
|
||||
@@ -602,7 +601,7 @@ const handleBatchAction = async () => {
|
||||
switch (batchAction.value) {
|
||||
case 'delete':
|
||||
if (confirm(`确定要删除选中的 ${selectedResources.value.length} 个资源吗?`)) {
|
||||
await Promise.all(selectedResources.value.map(id => resourceApi.deleteResource(id)))
|
||||
await resourceApi.batchDeleteResources(selectedResources.value)
|
||||
alert('批量删除成功')
|
||||
}
|
||||
break
|
||||
|
||||
@@ -82,6 +82,28 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 搜索记录 -->
|
||||
<div class="bg-white rounded-lg shadow p-6 mt-8">
|
||||
<h2 class="text-xl font-semibold text-gray-900 mb-4">搜索记录</h2>
|
||||
<table class="w-full table-auto text-sm">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="px-2 py-2 text-left">关键词</th>
|
||||
<th class="px-2 py-2 text-left">次数</th>
|
||||
<th class="px-2 py-2 text-left">日期</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="item in searchList" :key="item.id">
|
||||
<td class="px-2 py-2">{{ item.keyword }}</td>
|
||||
<td class="px-2 py-2">{{ item.count }}</td>
|
||||
<td class="px-2 py-2">{{ item.date ? (new Date(item.date)).toLocaleDateString() : '' }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<div v-if="searchList.length === 0" class="text-gray-400 text-center py-8">暂无搜索记录</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -89,11 +111,14 @@
|
||||
<script setup>
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
import { ref, onMounted, computed } from 'vue'
|
||||
import Chart from 'chart.js/auto'
|
||||
import { useApiFetch } from '~/composables/useApiFetch'
|
||||
import { parseApiResponse } from '~/composables/useApi'
|
||||
|
||||
const stats = ref({
|
||||
todaySearches: 0,
|
||||
@@ -106,6 +131,8 @@ const stats = ref({
|
||||
}
|
||||
})
|
||||
|
||||
const searchList = ref([])
|
||||
|
||||
const trendChart = ref(null)
|
||||
let chart = null
|
||||
|
||||
@@ -119,14 +146,23 @@ const getPercentage = (count) => {
|
||||
// 加载搜索统计
|
||||
const loadSearchStats = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/search-stats')
|
||||
if (response.ok) {
|
||||
const data = await response.json()
|
||||
stats.value = data
|
||||
|
||||
// 更新图表
|
||||
updateChart()
|
||||
}
|
||||
// 1. 汇总卡片
|
||||
const summary = await useApiFetch('/search-stats/summary').then(parseApiResponse)
|
||||
stats.value.todaySearches = summary.today || 0
|
||||
stats.value.weekSearches = summary.week || 0
|
||||
stats.value.monthSearches = summary.month || 0
|
||||
// 2. 热门关键词
|
||||
const hotKeywords = await useApiFetch('/search-stats/hot-keywords').then(parseApiResponse)
|
||||
stats.value.hotKeywords = hotKeywords || []
|
||||
// 3. 趋势
|
||||
const trend = await useApiFetch('/search-stats/trend').then(parseApiResponse)
|
||||
stats.value.searchTrend.days = (trend || []).map(item => item.date ? (new Date(item.date)).toLocaleDateString() : '')
|
||||
stats.value.searchTrend.values = (trend || []).map(item => item.total_searches)
|
||||
// 4. 搜索记录
|
||||
const data = await useApiFetch('/search-stats').then(parseApiResponse)
|
||||
searchList.value = data || []
|
||||
// 5. 更新图表
|
||||
setTimeout(updateChart, 100)
|
||||
} catch (error) {
|
||||
console.error('加载搜索统计失败:', error)
|
||||
}
|
||||
|
||||
@@ -18,14 +18,10 @@
|
||||
<!-- 配置表单 -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg shadow p-6">
|
||||
<form @submit.prevent="saveConfig" class="space-y-6">
|
||||
<!-- SEO 配置 -->
|
||||
<div class="border-b border-gray-200 dark:border-gray-700 pb-6">
|
||||
<h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
|
||||
<i class="fas fa-search text-blue-600"></i>
|
||||
SEO 配置
|
||||
</h2>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
|
||||
<n-tabs type="line" animated>
|
||||
<n-tab-pane name="SEO 配置" tab="SEO 配置">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<!-- 网站标题 -->
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
@@ -36,7 +32,7 @@
|
||||
type="text"
|
||||
required
|
||||
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
|
||||
placeholder="网盘资源数据库"
|
||||
placeholder="老九网盘资源数据库"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -49,7 +45,7 @@
|
||||
v-model="config.siteDescription"
|
||||
type="text"
|
||||
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
|
||||
placeholder="专业的网盘资源数据库"
|
||||
placeholder="专业的老九网盘资源数据库"
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -88,41 +84,55 @@
|
||||
v-model="config.copyright"
|
||||
type="text"
|
||||
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
|
||||
placeholder="© 2024 网盘资源数据库"
|
||||
placeholder="© 2024 老九网盘资源数据库"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 自动处理配置 -->
|
||||
<div class="border-b border-gray-200 dark:border-gray-700 pb-6">
|
||||
<h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
|
||||
<i class="fas fa-cogs text-green-600"></i>
|
||||
自动处理配置
|
||||
</h2>
|
||||
|
||||
<div class="space-y-4">
|
||||
<!-- 待处理资源自动处理 -->
|
||||
<div class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||
<div class="flex-1">
|
||||
<h3 class="text-lg font-medium text-gray-900 dark:text-white">
|
||||
待处理资源自动处理
|
||||
</h3>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
开启后,系统将自动处理待处理的资源,无需手动操作
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="自动处理配置" tab="自动处理配置">
|
||||
<div class="space-y-4">
|
||||
<div class="flex flex-col gap-1">
|
||||
<!-- 待处理资源自动处理 -->
|
||||
<div class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||
<div class="flex-1">
|
||||
<h3 class="text-lg font-medium text-gray-900 dark:text-white">
|
||||
待处理资源自动处理
|
||||
</h3>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
开启后,系统将自动处理待处理的资源,无需手动操作
|
||||
</p>
|
||||
</div>
|
||||
<div class="ml-4">
|
||||
<label class="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
v-model="config.autoProcessReadyResources"
|
||||
type="checkbox"
|
||||
class="sr-only peer"
|
||||
/>
|
||||
<div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="config.autoProcessReadyResources" class="ml-6">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
自动处理间隔 (分钟)
|
||||
</label>
|
||||
<input
|
||||
v-model.number="config.autoProcessInterval"
|
||||
type="number"
|
||||
min="1"
|
||||
max="1440"
|
||||
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
|
||||
placeholder="30"
|
||||
/>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
建议设置 5-60 分钟,避免过于频繁的处理
|
||||
</p>
|
||||
</div>
|
||||
<div class="ml-4">
|
||||
<label class="relative inline-flex items-center cursor-pointer">
|
||||
<input
|
||||
v-model="config.autoProcessReadyResources"
|
||||
type="checkbox"
|
||||
class="sr-only peer"
|
||||
/>
|
||||
<div class="w-11 h-6 bg-gray-200 peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-blue-300 dark:peer-focus:ring-blue-800 rounded-full peer dark:bg-gray-700 peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 after:border after:rounded-full after:h-5 after:w-5 after:transition-all dark:border-gray-600 peer-checked:bg-blue-600"></div>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<!-- 自动转存 -->
|
||||
<div class="flex items-center justify-between p-4 bg-gray-50 dark:bg-gray-700 rounded-lg">
|
||||
@@ -208,33 +218,11 @@
|
||||
</div>
|
||||
|
||||
<!-- 自动处理间隔 -->
|
||||
<div v-if="config.autoProcessReadyResources" class="ml-6">
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
自动处理间隔 (分钟)
|
||||
</label>
|
||||
<input
|
||||
v-model.number="config.autoProcessInterval"
|
||||
type="number"
|
||||
min="1"
|
||||
max="1440"
|
||||
class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 dark:bg-gray-700 dark:text-white"
|
||||
placeholder="30"
|
||||
/>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
|
||||
建议设置 5-60 分钟,避免过于频繁的处理
|
||||
</p>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 其他配置 -->
|
||||
<div>
|
||||
<h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
|
||||
<i class="fas fa-info-circle text-purple-600"></i>
|
||||
其他配置
|
||||
</h2>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="其他配置" tab="其他配置">
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
|
||||
<!-- 每页显示数量 -->
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
@@ -273,16 +261,9 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- API配置 -->
|
||||
<div class="border-b border-gray-200 dark:border-gray-700 pb-6">
|
||||
<h2 class="text-xl font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
|
||||
<i class="fas fa-key text-orange-600"></i>
|
||||
API 配置
|
||||
</h2>
|
||||
|
||||
<div class="space-y-4">
|
||||
</n-tab-pane>
|
||||
<n-tab-pane name="API配置" tab="API配置">
|
||||
<div class="space-y-4">
|
||||
<!-- API Token -->
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
|
||||
@@ -315,7 +296,6 @@
|
||||
API使用说明
|
||||
</h3>
|
||||
<div class="text-xs text-blue-700 dark:text-blue-300 space-y-1">
|
||||
<p>• 单个添加资源: POST /api/public/resources/add</p>
|
||||
<p>• 批量添加资源: POST /api/public/resources/batch-add</p>
|
||||
<p>• 资源搜索: GET /api/public/resources/search</p>
|
||||
<p>• 热门剧: GET /api/public/hot-dramas</p>
|
||||
@@ -324,7 +304,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</n-tab-pane>
|
||||
</n-tabs>
|
||||
|
||||
<!-- 保存按钮 -->
|
||||
<div class="flex justify-end space-x-4 pt-6">
|
||||
@@ -354,23 +335,27 @@
|
||||
<script setup>
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
import { ref, onMounted } from 'vue'
|
||||
import { useSystemConfigApi } from '~/composables/useApi'
|
||||
import { useSystemConfigStore } from '~/stores/systemConfig'
|
||||
const systemConfigStore = useSystemConfigStore()
|
||||
|
||||
// API
|
||||
const { getSystemConfig, updateSystemConfig } = useSystemConfigApi()
|
||||
const systemConfigApi = useSystemConfigApi()
|
||||
|
||||
// 响应式数据
|
||||
const loading = ref(false)
|
||||
const config = ref({
|
||||
// SEO 配置
|
||||
siteTitle: '网盘资源数据库',
|
||||
siteDescription: '专业的网盘资源数据库',
|
||||
siteTitle: '老九网盘资源数据库',
|
||||
siteDescription: '专业的老九网盘资源数据库',
|
||||
keywords: '网盘,资源管理,文件分享',
|
||||
author: '系统管理员',
|
||||
copyright: '© 2024 网盘资源数据库',
|
||||
copyright: '© 2024 老九网盘资源数据库',
|
||||
|
||||
// 自动处理配置
|
||||
autoProcessReadyResources: false,
|
||||
@@ -391,7 +376,7 @@ const systemConfig = ref(null)
|
||||
|
||||
// 页面元数据 - 移到变量声明之后
|
||||
useHead({
|
||||
title: () => systemConfig.value?.site_title ? `${systemConfig.value.site_title} - 系统配置` : '系统配置 - 网盘资源数据库',
|
||||
title: () => systemConfig.value?.site_title ? `${systemConfig.value.site_title} - 系统配置` : '系统配置 - 老九网盘资源数据库',
|
||||
meta: [
|
||||
{
|
||||
name: 'description',
|
||||
@@ -412,17 +397,17 @@ useHead({
|
||||
const loadConfig = async () => {
|
||||
try {
|
||||
loading.value = true
|
||||
const response = await getSystemConfig()
|
||||
const response = await systemConfigApi.getSystemConfig()
|
||||
console.log('系统配置响应:', response)
|
||||
|
||||
// 使用新的统一响应格式,直接使用response
|
||||
if (response) {
|
||||
config.value = {
|
||||
siteTitle: response.site_title || '网盘资源数据库',
|
||||
siteDescription: response.site_description || '专业的网盘资源数据库',
|
||||
siteTitle: response.site_title || '老九网盘资源数据库',
|
||||
siteDescription: response.site_description || '专业的老九网盘资源数据库',
|
||||
keywords: response.keywords || '网盘,资源管理,文件分享',
|
||||
author: response.author || '系统管理员',
|
||||
copyright: response.copyright || '© 2024 网盘资源数据库',
|
||||
copyright: response.copyright || '© 2024 老九网盘资源数据库',
|
||||
autoProcessReadyResources: response.auto_process_ready_resources || false,
|
||||
autoProcessInterval: response.auto_process_interval || 30,
|
||||
autoTransferEnabled: response.auto_transfer_enabled || false, // 新增
|
||||
@@ -465,12 +450,13 @@ const saveConfig = async () => {
|
||||
api_token: config.value.apiToken // 保存API Token
|
||||
}
|
||||
|
||||
const response = await updateSystemConfig(requestData)
|
||||
const response = await systemConfigApi.updateSystemConfig(requestData)
|
||||
// 使用新的统一响应格式,直接检查response是否存在
|
||||
if (response) {
|
||||
alert('配置保存成功!')
|
||||
// 重新加载配置以获取最新数据
|
||||
await loadConfig()
|
||||
// 自动更新 systemConfig store(强制刷新)
|
||||
await systemConfigStore.initConfig(true)
|
||||
} else {
|
||||
alert('保存配置失败:未知错误')
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
|
||||
<div class="">
|
||||
<div class="max-w-7xl mx-auto">
|
||||
<n-alert class="mb-4" title="提交的数据中,如果包含标签,数据添加成功,会自动添加标签" type="info" />
|
||||
|
||||
<!-- 操作按钮 -->
|
||||
<div class="flex justify-between items-center mb-4">
|
||||
@@ -266,15 +267,26 @@
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
// API 导入
|
||||
import { useTagApi, useCategoryApi } from '~/composables/useApi'
|
||||
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
const userStore = useUserStore()
|
||||
const config = useRuntimeConfig()
|
||||
|
||||
const tagApi = useTagApi()
|
||||
const categoryApi = useCategoryApi()
|
||||
|
||||
// 调试信息
|
||||
console.log('tagApi:', tagApi)
|
||||
console.log('categoryApi:', categoryApi)
|
||||
|
||||
// 页面状态
|
||||
const pageLoading = ref(true)
|
||||
const loading = ref(false)
|
||||
@@ -311,7 +323,7 @@ const getAuthHeaders = () => {
|
||||
|
||||
// 页面元数据
|
||||
useHead({
|
||||
title: '标签管理 - 网盘资源数据库',
|
||||
title: '标签管理 - 老九网盘资源数据库',
|
||||
meta: [
|
||||
{ name: 'description', content: '管理网盘资源标签' },
|
||||
{ name: 'keywords', content: '标签管理,资源管理' }
|
||||
@@ -330,18 +342,25 @@ const checkAuth = () => {
|
||||
// 获取分类列表
|
||||
const fetchCategories = async () => {
|
||||
try {
|
||||
const response = await $fetch('/categories', {
|
||||
baseURL: config.public.apiBase,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
console.log('获取分类列表...')
|
||||
const response = await categoryApi.getCategories()
|
||||
console.log('分类接口响应:', response)
|
||||
|
||||
if (response && typeof response === 'object' && 'code' in response && response.code === 200) {
|
||||
categories.value = (response as any).data?.items || []
|
||||
// 适配后端API响应格式
|
||||
if (response && response.items) {
|
||||
console.log('使用 items 格式:', response.items)
|
||||
categories.value = response.items
|
||||
} else if (Array.isArray(response)) {
|
||||
console.log('使用数组格式:', response)
|
||||
categories.value = response
|
||||
} else {
|
||||
categories.value = (response as any).items || []
|
||||
console.log('使用默认格式:', response)
|
||||
categories.value = []
|
||||
}
|
||||
console.log('最终分类数据:', categories.value)
|
||||
} catch (error) {
|
||||
console.error('获取分类列表失败:', error)
|
||||
categories.value = []
|
||||
}
|
||||
}
|
||||
|
||||
@@ -354,36 +373,39 @@ const fetchTags = async () => {
|
||||
page_size: pageSize.value,
|
||||
search: searchQuery.value
|
||||
}
|
||||
console.log('获取标签列表参数:', params)
|
||||
|
||||
let response: any
|
||||
if (selectedCategory.value) {
|
||||
// 如果选择了分类,使用按分类查询的接口
|
||||
response = await $fetch(`/categories/${selectedCategory.value}/tags`, {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
response = await tagApi.getTagsByCategory(parseInt(selectedCategory.value), params)
|
||||
} else {
|
||||
// 否则使用普通查询接口
|
||||
response = await $fetch('/tags', {
|
||||
baseURL: config.public.apiBase,
|
||||
params,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
response = await tagApi.getTags(params)
|
||||
}
|
||||
console.log('标签接口响应:', response)
|
||||
|
||||
// 解析响应
|
||||
if (response && typeof response === 'object' && 'code' in response && response.code === 200) {
|
||||
tags.value = response.data?.items || []
|
||||
totalCount.value = response.data?.total || 0
|
||||
totalPages.value = Math.ceil(totalCount.value / pageSize.value)
|
||||
} else {
|
||||
tags.value = response.items || []
|
||||
// 适配后端API响应格式
|
||||
if (response && response.items) {
|
||||
console.log('使用 items 格式:', response.items)
|
||||
tags.value = response.items
|
||||
totalCount.value = response.total || 0
|
||||
totalPages.value = Math.ceil(totalCount.value / pageSize.value)
|
||||
} else if (Array.isArray(response)) {
|
||||
console.log('使用数组格式:', response)
|
||||
tags.value = response
|
||||
totalCount.value = response.length
|
||||
totalPages.value = 1
|
||||
} else {
|
||||
console.log('使用默认格式:', response)
|
||||
tags.value = []
|
||||
totalCount.value = 0
|
||||
totalPages.value = 1
|
||||
}
|
||||
console.log('最终标签数据:', tags.value)
|
||||
} catch (error) {
|
||||
console.error('获取标签列表失败:', error)
|
||||
tags.value = []
|
||||
totalCount.value = 0
|
||||
totalPages.value = 1
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
@@ -435,11 +457,7 @@ const deleteTag = async (tagId: number) => {
|
||||
}
|
||||
|
||||
try {
|
||||
await $fetch(`/tags/${tagId}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'DELETE',
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
await tagApi.deleteTag(tagId)
|
||||
await fetchTags()
|
||||
} catch (error) {
|
||||
console.error('删除标签失败:', error)
|
||||
@@ -464,19 +482,9 @@ const handleSubmit = async () => {
|
||||
}
|
||||
|
||||
if (editingTag.value) {
|
||||
await $fetch(`/tags/${editingTag.value.id}`, {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'PUT',
|
||||
body: submitData,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
await tagApi.updateTag(editingTag.value.id, submitData)
|
||||
} else {
|
||||
await $fetch('/tags', {
|
||||
baseURL: config.public.apiBase,
|
||||
method: 'POST',
|
||||
body: submitData,
|
||||
headers: getAuthHeaders() as Record<string, string>
|
||||
})
|
||||
await tagApi.createTag(submitData)
|
||||
}
|
||||
|
||||
closeModal()
|
||||
@@ -520,15 +528,25 @@ const handleLogout = () => {
|
||||
// 页面加载
|
||||
onMounted(async () => {
|
||||
try {
|
||||
console.log('页面开始加载...')
|
||||
checkAuth()
|
||||
console.log('认证检查完成')
|
||||
|
||||
console.log('开始获取分类列表...')
|
||||
await fetchCategories()
|
||||
console.log('分类列表获取完成')
|
||||
|
||||
console.log('开始获取标签列表...')
|
||||
await fetchTags()
|
||||
console.log('标签列表获取完成')
|
||||
|
||||
// 检查URL参数,如果action=add则自动打开新增弹窗
|
||||
const route = useRoute()
|
||||
if (route.query.action === 'add') {
|
||||
showAddModal.value = true
|
||||
}
|
||||
|
||||
console.log('页面加载完成')
|
||||
} catch (error) {
|
||||
console.error('标签管理页面初始化失败:', error)
|
||||
} finally {
|
||||
|
||||
@@ -197,13 +197,14 @@
|
||||
<script setup lang="ts">
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
const router = useRouter()
|
||||
const userStore = useUserStore()
|
||||
|
||||
const users = ref([])
|
||||
const users = ref<any[]>([])
|
||||
const showCreateModal = ref(false)
|
||||
const showEditModal = ref(false)
|
||||
const showPasswordModal = ref(false)
|
||||
|
||||
@@ -15,70 +15,6 @@
|
||||
|
||||
<!-- 版本信息组件 -->
|
||||
<VersionInfo />
|
||||
|
||||
<!-- 版本历史 -->
|
||||
<div class="mt-8 bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
<i class="fas fa-history mr-2 text-green-500"></i>
|
||||
版本历史
|
||||
</h3>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div v-for="(version, index) in versionHistory" :key="index"
|
||||
class="border-l-4 border-blue-500 pl-4 py-2">
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<h4 class="font-medium text-gray-900 dark:text-white">
|
||||
v{{ version.version }}
|
||||
</h4>
|
||||
<p class="text-sm text-gray-600 dark:text-gray-400 mt-1">
|
||||
{{ version.date }}
|
||||
</p>
|
||||
</div>
|
||||
<span class="px-2 py-1 text-xs rounded-full"
|
||||
:class="getVersionTypeClass(version.type)">
|
||||
{{ version.type }}
|
||||
</span>
|
||||
</div>
|
||||
<ul class="mt-2 space-y-1">
|
||||
<li v-for="(change, changeIndex) in version.changes" :key="changeIndex"
|
||||
class="text-sm text-gray-600 dark:text-gray-400 flex items-start">
|
||||
<span class="mr-2 mt-1" :class="getChangeTypeClass(change.type)">
|
||||
{{ getChangeTypeIcon(change.type) }}
|
||||
</span>
|
||||
{{ change.description }}
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 构建信息 -->
|
||||
<div class="mt-8 bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
|
||||
<h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
|
||||
<i class="fas fa-cogs mr-2 text-purple-500"></i>
|
||||
构建信息
|
||||
</h3>
|
||||
|
||||
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div class="p-3 bg-gray-50 dark:bg-gray-700 rounded">
|
||||
<span class="text-sm text-gray-600 dark:text-gray-400">构建环境</span>
|
||||
<p class="font-mono text-gray-900 dark:text-white">Go 1.23.0</p>
|
||||
</div>
|
||||
<div class="p-3 bg-gray-50 dark:bg-gray-700 rounded">
|
||||
<span class="text-sm text-gray-600 dark:text-gray-400">前端框架</span>
|
||||
<p class="font-mono text-gray-900 dark:text-white">Nuxt.js 3.8.0</p>
|
||||
</div>
|
||||
<div class="p-3 bg-gray-50 dark:bg-gray-700 rounded">
|
||||
<span class="text-sm text-gray-600 dark:text-gray-400">数据库</span>
|
||||
<p class="font-mono text-gray-900 dark:text-white">PostgreSQL 15+</p>
|
||||
</div>
|
||||
<div class="p-3 bg-gray-50 dark:bg-gray-700 rounded">
|
||||
<span class="text-sm text-gray-600 dark:text-gray-400">部署方式</span>
|
||||
<p class="font-mono text-gray-900 dark:text-white">Docker</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -87,12 +23,13 @@
|
||||
<script setup lang="ts">
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'admin',
|
||||
ssr: false
|
||||
})
|
||||
|
||||
// 页面元数据
|
||||
useHead({
|
||||
title: '版本信息 - 网盘资源数据库',
|
||||
title: '版本信息 - 老九网盘资源数据库',
|
||||
meta: [
|
||||
{ name: 'description', content: '查看系统版本信息和更新状态' }
|
||||
]
|
||||
|
||||
@@ -4,10 +4,10 @@
|
||||
<div class="flex-1 p-3 sm:p-5">
|
||||
<div class="max-w-7xl mx-auto">
|
||||
<!-- 头部 -->
|
||||
<div class="bg-slate-800 dark:bg-gray-800 text-white dark:text-gray-100 rounded-lg shadow-lg p-4 sm:p-8 mb-4 sm:mb-8 text-center relative">
|
||||
<div class="header-container bg-slate-800 dark:bg-gray-800 text-white dark:text-gray-100 rounded-lg shadow-lg p-4 sm:p-8 mb-4 sm:mb-8 text-center relative">
|
||||
<h1 class="text-2xl sm:text-3xl font-bold mb-4">
|
||||
<a href="/" class="text-white hover:text-gray-200 dark:hover:text-gray-300 no-underline">
|
||||
网盘资源数据库 - API文档
|
||||
老九网盘资源数据库 - API文档
|
||||
</a>
|
||||
</h1>
|
||||
<p class="text-gray-300 max-w-2xl mx-auto">公开API接口文档,支持资源添加、搜索和热门剧获取等功能</p>
|
||||
@@ -46,57 +46,6 @@
|
||||
|
||||
<!-- API接口列表 -->
|
||||
<div class="space-y-8">
|
||||
<!-- 单个添加资源 -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg overflow-hidden">
|
||||
<div class="bg-green-600 text-white px-6 py-4">
|
||||
<h3 class="text-xl font-semibold flex items-center">
|
||||
<i class="fas fa-plus-circle mr-2"></i>
|
||||
单个添加资源
|
||||
</h3>
|
||||
<p class="text-green-100 mt-1">添加单个资源到待处理列表</p>
|
||||
</div>
|
||||
<div class="p-6">
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
<div>
|
||||
<h4 class="font-semibold text-gray-900 dark:text-white mb-3">请求信息</h4>
|
||||
<div class="space-y-2 text-sm">
|
||||
<p><strong>方法:</strong><span class="bg-green-100 dark:bg-green-800 text-green-800 dark:text-green-200 px-2 py-1 rounded">POST</span></p>
|
||||
<p><strong>路径:</strong><code class="bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded">/api/public/resources/add</code></p>
|
||||
<p><strong>认证:</strong><span class="text-red-600 dark:text-red-400">必需</span></p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h4 class="font-semibold text-gray-900 dark:text-white mb-3">请求参数</h4>
|
||||
<div class="bg-gray-50 dark:bg-gray-700 rounded p-4">
|
||||
<pre class="text-sm overflow-x-auto"><code>{
|
||||
"title": "资源标题",
|
||||
"description": "资源描述",
|
||||
"url": "资源链接",
|
||||
"category": "分类名称",
|
||||
"tags": "标签1,标签2",
|
||||
"img": "封面图片链接",
|
||||
"source": "数据来源",
|
||||
"extra": "额外信息"
|
||||
}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-6">
|
||||
<h4 class="font-semibold text-gray-900 dark:text-white mb-3">响应示例</h4>
|
||||
<div class="bg-gray-50 dark:bg-gray-700 rounded p-4">
|
||||
<pre class="text-sm overflow-x-auto"><code>{
|
||||
"success": true,
|
||||
"message": "资源添加成功,已进入待处理列表",
|
||||
"data": {
|
||||
"id": 123
|
||||
},
|
||||
"code": 200
|
||||
}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 批量添加资源 -->
|
||||
<div class="bg-white dark:bg-gray-800 rounded-lg shadow-lg overflow-hidden">
|
||||
<div class="bg-purple-600 text-white px-6 py-4">
|
||||
@@ -104,7 +53,7 @@
|
||||
<i class="fas fa-layer-group mr-2"></i>
|
||||
批量添加资源
|
||||
</h3>
|
||||
<p class="text-purple-100 mt-1">批量添加多个资源到待处理列表</p>
|
||||
<p class="text-purple-100 mt-1">批量添加多个资源到待处理列表,每个资源可包含多个链接(url为数组),标题和url为必填项</p>
|
||||
</div>
|
||||
<div class="p-6">
|
||||
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
|
||||
@@ -113,22 +62,28 @@
|
||||
<div class="space-y-2 text-sm">
|
||||
<p><strong>方法:</strong><span class="bg-purple-100 dark:bg-purple-800 text-purple-800 dark:text-purple-200 px-2 py-1 rounded">POST</span></p>
|
||||
<p><strong>路径:</strong><code class="bg-gray-100 dark:bg-gray-700 px-2 py-1 rounded">/api/public/resources/batch-add</code></p>
|
||||
<p><strong>认证:</strong><span class="text-red-600 dark:text-red-400">必需</span></p>
|
||||
<p><strong>认证:</strong><span class="text-red-600 dark:text-red-400">必需</span>(X-API-Token)</p>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h4 class="font-semibold text-gray-900 dark:text-white mb-3">请求参数</h4>
|
||||
<p class="text-xs text-gray-500 dark:text-gray-400 mb-2">title 和 url 是必填项,其他字段均为选填</p>
|
||||
<div class="bg-gray-50 dark:bg-gray-700 rounded p-4">
|
||||
<pre class="text-sm overflow-x-auto"><code>{
|
||||
"resources": [
|
||||
{
|
||||
"title": "资源1",
|
||||
"url": "链接1",
|
||||
"description": "描述1"
|
||||
"description": "描述1",
|
||||
"url": ["链接1", "链接2"],
|
||||
"category": "分类",
|
||||
"tags": "标签1,标签2",
|
||||
"img": "图片链接",
|
||||
"source": "数据来源",
|
||||
"extra": "额外信息"
|
||||
},
|
||||
{
|
||||
"title": "资源2",
|
||||
"url": "链接2",
|
||||
"title": "资源2",
|
||||
"url": ["链接3"],
|
||||
"description": "描述2"
|
||||
}
|
||||
]
|
||||
@@ -141,7 +96,7 @@
|
||||
<div class="bg-gray-50 dark:bg-gray-700 rounded p-4">
|
||||
<pre class="text-sm overflow-x-auto"><code>{
|
||||
"success": true,
|
||||
"message": "批量添加成功,共添加 2 个资源",
|
||||
"message": "批量添加成功",
|
||||
"data": {
|
||||
"created_count": 2,
|
||||
"created_ids": [123, 124]
|
||||
@@ -323,14 +278,15 @@
|
||||
<pre class="text-sm overflow-x-auto"><code># 设置API Token
|
||||
API_TOKEN="your_api_token_here"
|
||||
|
||||
# 单个添加资源
|
||||
curl -X POST "http://localhost:8080/api/public/resources/add" \
|
||||
# 批量添加资源
|
||||
curl -X POST "http://localhost:8080/api/public/resources/batch-add" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Token: $API_TOKEN" \
|
||||
-d '{
|
||||
"title": "测试资源",
|
||||
"url": "https://example.com/resource",
|
||||
"description": "测试描述"
|
||||
"resources": [
|
||||
{ "title": "测试资源1", "url": ["https://example.com/resource1"], "description": "描述1" },
|
||||
{ "title": "测试资源2", "url": ["https://example.com/resource2", "https://example.com/resource3"], "description": "描述2" }
|
||||
]
|
||||
}'
|
||||
|
||||
# 搜索资源
|
||||
@@ -341,6 +297,41 @@ curl -X GET "http://localhost:8080/api/public/resources/search?keyword=测试" \
|
||||
curl -X GET "http://localhost:8080/api/public/hot-dramas?page=1&page_size=5" \
|
||||
-H "X-API-Token: $API_TOKEN"</code></pre>
|
||||
</div>
|
||||
<h4 class="font-semibold text-gray-900 dark:text-white mb-3">前端 fetch 示例</h4>
|
||||
<div class="bg-gray-50 dark:bg-gray-700 rounded p-4">
|
||||
<pre class="text-sm overflow-x-auto"><code>
|
||||
// 资源搜索
|
||||
fetch('/api/public/resources/search?q=测试', { headers: { 'X-API-Token': 'your_token' } })
|
||||
.then(res => res.json())
|
||||
.then(res => {
|
||||
if (res.success) {
|
||||
const list = res.data.list // 资源列表
|
||||
const total = res.data.total
|
||||
} else {
|
||||
alert(res.message)
|
||||
}
|
||||
})
|
||||
// 批量添加资源
|
||||
fetch('/api/public/resources/batch-add', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'X-API-Token': 'your_token' },
|
||||
body: JSON.stringify({
|
||||
resources: [
|
||||
{ title: 'xxx', url: ['xxx'], description: 'xxx' },
|
||||
{ title: 'yyy', url: ['yyy', 'zzz'], description: 'yyy' }
|
||||
]
|
||||
})
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(res => {
|
||||
if (res.success) {
|
||||
alert('添加成功,ID: ' + res.data.created_ids.join(', '))
|
||||
} else {
|
||||
alert(res.message)
|
||||
}
|
||||
})
|
||||
</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -354,14 +345,14 @@ curl -X GET "http://localhost:8080/api/public/hot-dramas?page=1&page_size=5" \
|
||||
<script setup>
|
||||
// 设置页面布局
|
||||
definePageMeta({
|
||||
layout: 'admin'
|
||||
layout: 'default'
|
||||
})
|
||||
|
||||
// 页面元数据
|
||||
useHead({
|
||||
title: 'API文档 - 网盘资源数据库',
|
||||
title: 'API文档 - 老九网盘资源数据库',
|
||||
meta: [
|
||||
{ name: 'description', content: '网盘资源数据库的公开API接口文档' },
|
||||
{ name: 'description', content: '老九网盘资源数据库的公开API接口文档' },
|
||||
{ name: 'keywords', content: 'API,接口文档,网盘资源管理' }
|
||||
]
|
||||
})
|
||||
@@ -376,4 +367,12 @@ pre {
|
||||
code {
|
||||
font-family: 'Courier New', Courier, monospace;
|
||||
}
|
||||
.header-container {
|
||||
background: url(/assets/images/banner.webp) center top/cover no-repeat,
|
||||
linear-gradient(
|
||||
to bottom,
|
||||
rgba(0,0,0,0.1) 0%,
|
||||
rgba(0,0,0,0.25) 100%
|
||||
);
|
||||
}
|
||||
</style>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user