Compare commits

...
6 Commits
Author SHA1 Message Date
chenxin 5bcc8a962e ♻️ refactor(handlers): status 与 review 页面模板化
- HTML 提取至 templates/status.html、templates/review.html(go:embed 内嵌)
- status.go 1022→271 行、review.go 1281→438 行,动态数据全部经 html/template 按上下文自动转义
- 评论循环/作者徽章/贴纸/图片条件渲染翻译为模板 range/if;emojiMap 以 template.JS 注入
- 与旧版渲染输出实测对比:22 条评论结构完全一致;差异仅为 JS 上下文安全转义(& 等)与 html/template 剥除 CSS 注释,均无功能影响
- 其余文件为 gofmt 顺手格式化
2026-09-30 00:25:09 +08:00
chenxin ad6d28fd85 ⚡️ perf(media): 音频代理改为流式转发
- downloadMedia 拿到响应头即返回 Body,音频不再全量驻留内存,改由 io.Copy 流式写出
- 重试仅覆盖响应阶段;Body 读取中途失败由客户端自行重试
- 请求头设置提取为 setMediaHeaders 复用;data_uri 模式保持全量读取(本就需驻留内存)
- 漫画代理因需解密后输出,维持原有全量方式
2026-09-30 00:25:09 +08:00
chenxin f89bee8ddc ✨ feat(server): 新增每 IP 请求限流
- 新增 RateLimit 中间件:golang.org/x/time/rate 令牌桶,超出返回 429
- server.rate_limit_qps 配置(默认 0 不限制,突发 10),公网部署建议开启
- 业务路由统一接入 限流 → 鉴权 中间件链;/healthz 与静态资源不限流
- X-Forwarded-For 优先取真实客户端 IP(反代场景),visitor 表定时清理防泄漏
- config.yaml 补齐 protect_all 与 rate_limit_qps 配置项(此前仅存在于代码)
2026-09-30 00:24:58 +08:00
chenxin 822d3fe444 📝 docs(api): 补充 search 接口 tab_type 过滤语义 2026-09-29 23:55:44 +08:00
chenxin 8bc6f5c2ae 🐛 fix(search): 按 tab_type 过滤搜索结果
- 上游 search/tab/v/ 固定返回所有 tab 的 search_tabs,此前原样转发导致传 tab_type 仍返回全部结果
- 新增 filterSearchTabs 只保留匹配项,无匹配时保留原样兜底
- 过滤路径用 UseNumber 解析重组,避免 19 位 book_id 经 float64 丢精度;解析失败退回原样转发
- 新增测试:过滤正确性、无匹配兜底、大整数精度保持
2026-09-29 23:54:27 +08:00
chenxin bb0cc39950 📝 docs(readme): 同步近期改动并修正过时内容
- 补充 /healthz、protect_all 配置、错误响应规范(400/500/401)、缓存机制表
- 修正接口参数名与代码不符处:content 实为 item_id、multi-content 需 book_id、media 系列为 item_ids 等
- /vacuum 修正为 POST;技术栈删除已移除的 Gin,改为标准库 net/http
2026-09-29 23:52:10 +08:00
39 changed files with 392 additions and 1825 deletions

No files matched your search

+32 -18
View File
@@ -34,9 +34,11 @@ Go 语言实现的番茄小说非官方 API 服务,完整实现了签名算法
- **签名算法** - Gorgon、8404、Argus、Ladon、Khronos
- **设备密钥池** - 多设备轮换、自动补充
- **SQLite 缓存** - 本地缓存、过期清理、数据库压缩;支持切换 PostgreSQL 与 Redis
- **多级缓存** - 正文/详情/目录等 24 小时缓存,搜索/分类短缓存;存储后端可选 SQLite / PostgreSQL / Redis
- **配置热更新** - 修改配置无需重启
- **访问控制** - 支持 AccessKey 验证
- **访问控制** - AccessKey 验证(常量时间比较防时序攻击),可扩展保护全部业务接口
- **优雅退出** - 超时保护、信号驱动的平滑关闭
- **错误规范** - 统一 JSON 错误响应,缺参 400 / 服务端错误 500
## 项目结构
@@ -134,36 +136,37 @@ go run ./cmd/fanqie
| 接口 | 方法 | 说明 |
| ------ | ------ | ------ |
| `GET /` | GET | 服务首页 |
| `GET /healthz` | GET | 存活探针(不校验密钥,供容器/反代使用) |
| `GET /status` | GET | 服务状态(需 AccessKey) |
| `GET /self-info` | GET | 自我信息(需 AccessKey) |
| `GET /vacuum` | GET | 数据库压缩(需 AccessKey) |
| `POST /vacuum` | POST | 数据库压缩(需 AccessKey) |
### 书籍相关
| 接口 | 方法 | 说明 | 参数 |
| ------ | ------ | ------ | ------ |
| `/search` | GET | 搜索书籍 | `keyword`, `tab_type`, `offset` |
| `/search` | GET | 搜索书籍 | `query`(或 `key`), `tab_type`, `offset`(`search_tabs` 仅返回匹配 `tab_type` 的 tab) |
| `/detail` | GET | 书籍详情 | `book_id` |
| `/info` | GET | 书籍详情(同 detail) | `book_id` |
| `/catalog` | GET | 章节目录 | `book_id` |
| `/directory/all_items` | GET | 章节目录(同 catalog) | `book_id` |
| `/multi-detail` | GET | 批量书籍详情 | `book_ids`(逗号分隔) |
| `/multi-detail` | GET | 批量书籍详情 | `book_id`(逗号分隔) |
### 内容相关
| 接口 | 方法 | 说明 | 参数 |
| ------ | ------ | ------ | ------ |
| `/content` | GET | 章节内容 | `chapter_id`, `book_id` |
| `/multi-content` | GET | 批量章节内容 | `chapter_ids`(逗号分隔) |
| `/item-summary` | GET | 章节摘要 | `book_id`, `chapter_id` |
| `/content` | GET | 章节内容 | `item_id` |
| `/multi-content` | GET | 批量章节内容 | `book_id`, `item_ids`(逗号分隔) |
| `/item-summary` | GET | 章节摘要 | `book_id`, `item_ids`(逗号分隔) |
### 评论相关
| 接口 | 方法 | 说明 | 参数 |
| ------ | ------ | ------ | ------ |
| `/chapter_review` | GET | 章节评论 | `book_id`, `chapter_id` |
| `/review` | GET | 书评列表 | `book_id`, `offset`, `limit` |
| `/review_html` | GET | 评论 HTML | `book_id`, `chapter_id` |
| `/chapter_review` | GET | 章节评论 | `book_id`, `item_id` |
| `/review` | GET | 书评列表 | `book_id`, `item_id`, `para`, `comment_id`, `offset`, `limit` |
| `/review_html` | GET | 评论 HTML | `book_id`, `item_id`, `para` |
### 分类相关
@@ -176,9 +179,9 @@ go run ./cmd/fanqie
| 接口 | 方法 | 说明 | 参数 |
| ------ | ------ | ------ | ------ |
| `/audio` | GET | 音频内容 | `audio_id`, `tone_id` |
| `/video` | GET | 视频内容 | `video_id` |
| `/manga` | GET | 漫画内容 | `manga_id`, `chapter_id` |
| `/audio` | GET | 音频内容 | `item_ids`, `tone_id`, `output` |
| `/video` | GET | 视频内容 | `item_ids` |
| `/manga` | GET | 漫画内容 | `item_ids`(或 `item_id`), `show_html`, `output` |
| `/manga/image/{itemID}/{index}` | GET | 漫画图片 | 路径参数 |
## 内容获取示例
@@ -235,6 +238,7 @@ server:
host: "0.0.0.0" # 监听地址
port: "40180" # 监听端口
access_key: "" # 访问密钥(可选)
protect_all: false # 业务接口也要求访问密钥(公网部署建议开启)
# 番茄小说配置
fanqie:
@@ -324,6 +328,7 @@ cp .env.example .env
| `server.host` | HTTP 服务监听地址 | `0.0.0.0` |
| `server.port` | HTTP 服务监听端口 | `40180` |
| `server.access_key` | 访问密钥,设为空则不验证 | - |
| `server.protect_all` | 业务接口是否也要求访问密钥 | `false` |
| `fanqie.algorithm` | 签名算法 `gorgon` / `8404` | `gorgon` |
| `fanqie.signature` | 签名方法 `sign2` / `sign4` | `sign4` |
| `fanqie.content.*` | 正文内容处理选项 | 见上文 |
@@ -377,15 +382,24 @@ cp .env.example .env
## 缓存机制
- **SQLite 本地缓存** - 缓存书籍内容和章节数据
- **自动清理** - 定期清理过期缓存
- **接口缓存** - 命中直接返回,不打上游(Redis 启用时优先走 Redis)
- **自动清理** - 定期清理过期缓存(Redis 由 TTL 自动过期)
- **数据库压缩** - 支持 VACUUM 操作优化数据库
| 接口 | 缓存时长 |
| ------ | ------ |
| `/content` | 24 小时 |
| `/detail`、`/info`、`/catalog`、`/multi-detail`、`/item-summary` | 24 小时 |
| `/search`、`/category-front`、`/category-landing` | 10 分钟 |
| `/audio` 代理链接 | 2 小时(匹配 CDN 有效期) |
失败响应不缓存;评论类接口为动态数据,不缓存。
## 技术栈
- **Go 1.24** - 编程语言
- **Gin** - HTTP 框架(间接依赖)
- **SQLite3** - 本地数据库
- **net/http** - 标准库 HTTP 服务(超时保护 + 优雅退出)
- **SQLite3 / PostgreSQL / Redis** - 缓存与存储
- **Viper** - 配置管理
- **goquery** - HTML 解析
+24 -21
View File
@@ -121,7 +121,7 @@ func initDeviceKeyPool() error {
pool := fqapi.GetDeviceKeyPool()
if err := pool.Initialize(); err != nil {
return fmt.Errorf("初始化设备密钥池失败: %w", err)
}
}
// 显示池状态
stats := pool.GetStats()
@@ -140,28 +140,31 @@ func setupRoutes() {
http.HandleFunc("/healthz", handlers.HandleHealth)
// API端点(protect_all 开启时要求访问密钥;代理路由不包,URL 由服务端生成不含 key)
http.HandleFunc("/search", handlers.OptionalAccessKey(handlers.HandleSearch))
http.HandleFunc("/detail", handlers.OptionalAccessKey(handlers.HandleDetail))
http.HandleFunc("/info", handlers.OptionalAccessKey(handlers.HandleDetail))
http.HandleFunc("/catalog", handlers.OptionalAccessKey(handlers.HandleCatalog))
http.HandleFunc("/directory/all_items", handlers.OptionalAccessKey(handlers.HandleCatalog))
http.HandleFunc("/multi-detail", handlers.OptionalAccessKey(handlers.HandleMultiDetail))
http.HandleFunc("/multi-content", handlers.OptionalAccessKey(handlers.HandleMultiContent))
http.HandleFunc("/content", handlers.OptionalAccessKey(handlers.HandleContent))
http.HandleFunc("/item-summary", handlers.OptionalAccessKey(handlers.HandleItemSummary))
http.HandleFunc("/category-front", handlers.OptionalAccessKey(handlers.HandleCategoryFront))
http.HandleFunc("/category-landing", handlers.OptionalAccessKey(handlers.HandleCategoryLanding))
http.HandleFunc("/audio", handlers.OptionalAccessKey(handlers.HandleAudio))
http.HandleFunc("/audio/proxy/", handlers.HandleAudioProxy)
http.HandleFunc("/video", handlers.OptionalAccessKey(handlers.HandleVideo))
http.HandleFunc("/manga", handlers.OptionalAccessKey(handlers.HandleManga))
http.HandleFunc("/manga/image/", handlers.HandleMangaImageProxy)
// API端点:限流 + protect_all 鉴权链(代理路由不鉴权,URL 由服务端生成不含 key)
wrap := func(h http.HandlerFunc) http.HandlerFunc {
return handlers.RateLimit(handlers.OptionalAccessKey(h))
}
http.HandleFunc("/search", wrap(handlers.HandleSearch))
http.HandleFunc("/detail", wrap(handlers.HandleDetail))
http.HandleFunc("/info", wrap(handlers.HandleDetail))
http.HandleFunc("/catalog", wrap(handlers.HandleCatalog))
http.HandleFunc("/directory/all_items", wrap(handlers.HandleCatalog))
http.HandleFunc("/multi-detail", wrap(handlers.HandleMultiDetail))
http.HandleFunc("/multi-content", wrap(handlers.HandleMultiContent))
http.HandleFunc("/content", wrap(handlers.HandleContent))
http.HandleFunc("/item-summary", wrap(handlers.HandleItemSummary))
http.HandleFunc("/category-front", wrap(handlers.HandleCategoryFront))
http.HandleFunc("/category-landing", wrap(handlers.HandleCategoryLanding))
http.HandleFunc("/audio", wrap(handlers.HandleAudio))
http.HandleFunc("/audio/proxy/", wrap(handlers.HandleAudioProxy))
http.HandleFunc("/video", wrap(handlers.HandleVideo))
http.HandleFunc("/manga", wrap(handlers.HandleManga))
http.HandleFunc("/manga/image/", wrap(handlers.HandleMangaImageProxy))
// 评论相关端点
http.HandleFunc("/chapter_review", handlers.OptionalAccessKey(handlers.HandleChapterReview))
http.HandleFunc("/review", handlers.OptionalAccessKey(handlers.HandleReview))
http.HandleFunc("/review_html", handlers.OptionalAccessKey(handlers.HandleReviewHTML))
http.HandleFunc("/chapter_review", wrap(handlers.HandleChapterReview))
http.HandleFunc("/review", wrap(handlers.HandleReview))
http.HandleFunc("/review_html", wrap(handlers.HandleReviewHTML))
// 表情图片静态文件服务
http.Handle("/emoji/", http.StripPrefix("/emoji/", http.FileServer(http.Dir("emoji"))))
+1
View File
@@ -10,6 +10,7 @@ require (
github.com/mattn/go-sqlite3 v1.14.18
github.com/redis/go-redis/v9 v9.22.0
github.com/spf13/viper v1.18.2
golang.org/x/time v0.5.0
)
require (
+2
View File
@@ -114,6 +114,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.30.0 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
+5 -4
View File
@@ -19,10 +19,11 @@ type Config struct {
// ServerConfig 服务器配置
type ServerConfig struct {
Port string `mapstructure:"port"`
Host string `mapstructure:"host"`
AccessKey string `mapstructure:"access_key"`
ProtectAll bool `mapstructure:"protect_all"` // 业务接口也要求访问密钥(公网部署建议开启)
Port string `mapstructure:"port"`
Host string `mapstructure:"host"`
AccessKey string `mapstructure:"access_key"`
ProtectAll bool `mapstructure:"protect_all"` // 业务接口也要求访问密钥(公网部署建议开启)
RateLimitQPS float64 `mapstructure:"rate_limit_qps"` // 每 IP 每秒请求上限,0=不限制
}
// FanqieConfig 番茄小说配置
-1
View File
@@ -132,4 +132,3 @@ func HandleAudio(itemIDs interface{}, toneID interface{}, output interface{}) (s
audioLogger.Error(fmt.Sprintf("获取音频失败: code=%v, msg=%s", respCode, errMsg))
return BuildErrorResponse(errMsg), nil
}
+8 -7
View File
@@ -4,15 +4,16 @@ import (
"database/sql"
"encoding/json"
"fmt"
"io"
"time"
)
// AudioCacheItem 音频缓存项
type AudioCacheItem struct {
OriginalURL string `json:"original_url"` // 原始CDN URL
DeviceID string `json:"device_id"` // 关联的设备ID
DeviceID string `json:"device_id"` // 关联的设备ID
Headers map[string]string `json:"headers"` // 请求头信息
CachedAt time.Time `json:"cached_at"` // 缓存时间
CachedAt time.Time `json:"cached_at"` // 缓存时间
}
// GenerateAudioProxyURL 生成音频代理URL
@@ -49,8 +50,8 @@ func GenerateAudioProxyURL(originalURL, deviceID string, headers map[string]stri
return fmt.Sprintf("/audio/proxy/%s", key)
}
// HandleAudioProxy 处理音频代理请求
func HandleAudioProxy(key string) ([]byte, string, error) {
// HandleAudioProxy 处理音频代理请求(流式返回,调用方负责 Close)
func HandleAudioProxy(key string) (io.ReadCloser, string, error) {
var originalURL, deviceID string
var headers map[string]string
@@ -95,13 +96,13 @@ func HandleAudioProxy(key string) ([]byte, string, error) {
headers = make(map[string]string)
}
// 下载音频内容,使用关联的设备信息
data, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 3)
// 下载音频内容(流式),使用关联的设备信息
body, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 3)
if err != nil {
return nil, "", fmt.Errorf("下载音频失败: %w", err)
}
return data, contentType, nil
return body, contentType, nil
}
// CleanExpiredAudioCache 清理过期的音频缓存
+1 -2
View File
@@ -12,7 +12,7 @@ var catalogLogger = common.NewLogger("catalog", "INFO", "")
// HandleGetCatalog 处理获取书籍目录,目录数据基本不变,缓存 24 小时
func HandleGetCatalog(bookID string) (string, error) {
return withCache("catalog_" + bookID, 86400, func() (string, error) {
return withCache("catalog_"+bookID, 86400, func() (string, error) {
return fetchCatalog(bookID)
})
}
@@ -210,4 +210,3 @@ func itemMultiDetail(itemList []string) ([]map[string]interface{}, error) {
return nil, fmt.Errorf("请求失败")
}
-1
View File
@@ -47,4 +47,3 @@ func fetchCategoryFront(tab interface{}) (string, error) {
return BuildErrorResponse("获取失败"), nil
}
-1
View File
@@ -59,4 +59,3 @@ func fetchCategoryLanding(categoryID, offset, wordNumber, bookStatus, sortBy int
return BuildErrorResponse("获取失败"), nil
}
-1
View File
@@ -276,4 +276,3 @@ func tryBackupAPI(itemID string, textMode, imageMode bool) (string, error) {
contentLogger.Warning("备用接口1获取正文出错!")
return `{"code": -1, "msg": "获取失败"}`, fmt.Errorf("所有接口都失败")
}
-2
View File
@@ -13,7 +13,6 @@ var (
parserLogger = common.NewLogger("content_parser", "INFO", "")
)
// ContentParser 内容解析器
type ContentParser struct {
cfg config.ContentConfig
@@ -184,4 +183,3 @@ func (p *ContentParser) processHTMLMode(content string) string {
return content
}
-1
View File
@@ -262,4 +262,3 @@ func ParseStringParam(param interface{}, defaultVal string) string {
}
return defaultVal
}
+1 -2
View File
@@ -10,7 +10,7 @@ var detailLogger = common.NewLogger("detail", "INFO", "")
// HandleGetDetail 处理获取书籍详情,详情数据基本不变,缓存 24 小时
func HandleGetDetail(bookID string) (string, error) {
return withCache("detail_" + bookID, 86400, func() (string, error) {
return withCache("detail_"+bookID, 86400, func() (string, error) {
return fetchDetail(bookID)
})
}
@@ -58,4 +58,3 @@ func fetchDetail(bookID string) (string, error) {
return BuildErrorResponse("获取失败"), nil
}
-4
View File
@@ -399,7 +399,6 @@ func (p *DeviceKeyPool) saveDeviceToDB(item *DeviceKeyItem) error {
return fmt.Errorf("数据库未初始化")
}
// RETURNING id 同时兼容 SQLite(3.35+) 与 PostgreSQL,替代 LastInsertId()
err := cacheDB.QueryRow(q(`
INSERT INTO device_pool (device_header, key, key_ver, is_valid, created_at, last_used_at)
@@ -417,7 +416,6 @@ func (p *DeviceKeyPool) updateDeviceInDB(item *DeviceKeyItem) error {
return fmt.Errorf("数据库未初始化")
}
_, err := cacheDB.Exec(q(`
UPDATE device_pool
SET device_header = ?, key = ?, key_ver = ?, is_valid = ?, last_used_at = ?
@@ -434,7 +432,6 @@ func (p *DeviceKeyPool) removeInvalidFromDB() error {
return fmt.Errorf("数据库未初始化")
}
result, err := cacheDB.Exec(`DELETE FROM device_pool WHERE is_valid = 0`)
if err != nil {
return err
@@ -544,4 +541,3 @@ func GetCurrentDevice() *DeviceKeyItem {
item, _ := pool.GetNext()
return item
}
+17 -18
View File
@@ -88,19 +88,19 @@ func generateDeviceInfo() map[string]interface{} {
rand.Read(openUDIDBytes)
return map[string]interface{}{
"os": "Android",
"os_version": osVersion[0],
"os_api": osVersion[1],
"device_model": deviceModel,
"device_brand": deviceBrand,
"device_manufacturer": deviceBrand,
"cpu_abi": "arm64-v8a",
"release_build": releaseBuild,
"cdid": generateUUID(),
"sig_hash": "a4a27c2633195374c15651ffc3c4a497",
"openudid": hex.EncodeToString(openUDIDBytes),
"clientudid": generateUUID(),
"req_id": generateUUID(),
"os": "Android",
"os_version": osVersion[0],
"os_api": osVersion[1],
"device_model": deviceModel,
"device_brand": deviceBrand,
"device_manufacturer": deviceBrand,
"cpu_abi": "arm64-v8a",
"release_build": releaseBuild,
"cdid": generateUUID(),
"sig_hash": "a4a27c2633195374c15651ffc3c4a497",
"openudid": hex.EncodeToString(openUDIDBytes),
"clientudid": generateUUID(),
"req_id": generateUUID(),
}
}
@@ -130,9 +130,9 @@ func generateOptionalFields() (map[string]interface{}, map[string]int64) {
genTime := currentMillis()
return map[string]interface{}{
"rom": rom,
"rom_version": fmt.Sprintf("coloros__%s.%s.%s release-keys", part1, part2, part3),
"apk_first_install_time": genTime - int64(randInt(365))*86400000,
"rom": rom,
"rom_version": fmt.Sprintf("coloros__%s.%s.%s release-keys", part1, part2, part3),
"apk_first_install_time": genTime - int64(randInt(365))*86400000,
}, map[string]int64{
"_gen_time": genTime,
}
@@ -370,7 +370,7 @@ func Register() (string, error) {
deviceModel,
respData["install_id_str"])
logger.Info("设备注册成功!" )
logger.Info("设备注册成功!")
// 尝试激活特权
tryActivatePremium(header)
@@ -381,4 +381,3 @@ func Register() (string, error) {
logger.Warning("设备注册失败!")
return "", fmt.Errorf("设备注册失败")
}
+3 -4
View File
@@ -11,9 +11,9 @@ import (
// CM 加密管理器
type CM struct {
bigC *big.Int // 大素数C
bigB int64 // 底数B
arryD []byte // 固定密钥
bigC *big.Int // 大素数C
bigB int64 // 底数B
arryD []byte // 固定密钥
thisD [2]*big.Int // 密钥对(私钥, 公钥)
thisC []byte // 随机IV
}
@@ -182,4 +182,3 @@ func (cm *CM) Decrypt(c, y, content string) (string, error) {
return string(decrypted), nil
}
-1
View File
@@ -227,4 +227,3 @@ func ReplaceEmojisInText(text string) string {
return result
}
-1
View File
@@ -114,4 +114,3 @@ func ContentRequest(urlStr string, options map[string]interface{}) (*common.Clie
client := common.NewHTTPClient()
return client.Request(urlStr, options)
}
+1 -2
View File
@@ -9,7 +9,7 @@ var itemSummaryLogger = common.NewLogger("item_summary", "INFO", "")
// HandleItemSummary 处理获取章节摘要,章节摘要数据基本不变,缓存 24 小时
func HandleItemSummary(itemIDs, bookID string) (string, error) {
return withCache("item_summary_" + bookID + "_" + itemIDs, 86400, func() (string, error) {
return withCache("item_summary_"+bookID+"_"+itemIDs, 86400, func() (string, error) {
return fetchItemSummary(itemIDs, bookID)
})
}
@@ -48,4 +48,3 @@ func fetchItemSummary(itemIDs, bookID string) (string, error) {
return BuildErrorResponse("获取失败"), nil
}
+2 -3
View File
@@ -606,11 +606,10 @@ func getImageFormat(data []byte, url string) string {
// WEBP: RIFF...WEBP
if bytes.HasPrefix(data, []byte{0x52, 0x49, 0x46, 0x46}) &&
len(data) >= 12 &&
bytes.Equal(data[8:12], []byte{0x57, 0x45, 0x42, 0x50}) {
len(data) >= 12 &&
bytes.Equal(data[8:12], []byte{0x57, 0x45, 0x42, 0x50}) {
return "webp"
}
return "png"
}
-1
View File
@@ -69,4 +69,3 @@ func CleanExpiredMangaCache() {
}
}
}
+40 -35
View File
@@ -32,15 +32,15 @@ func extractDeviceParam(deviceHeader, paramName string) string {
return ""
}
// downloadMediaWithRetry 带重试的媒体下载,自动切换设备
func downloadMediaWithRetry(url, deviceID string, headers map[string]string, maxRetries int) ([]byte, string, error) {
// downloadMediaWithRetry 带重试的流式媒体下载,自动切换设备(仅响应阶段可重试)
func downloadMediaWithRetry(url, deviceID string, headers map[string]string, maxRetries int) (io.ReadCloser, string, error) {
var lastErr error
currentDeviceID := deviceID
for i := 0; i <= maxRetries; i++ {
data, contentType, err := downloadMedia(url, currentDeviceID, headers)
if err == nil && len(data) > 0 {
return data, contentType, nil
body, contentType, err := downloadMedia(url, currentDeviceID, headers)
if err == nil {
return body, contentType, nil
}
lastErr = err
@@ -58,9 +58,10 @@ func downloadMediaWithRetry(url, deviceID string, headers map[string]string, max
return nil, "", fmt.Errorf("下载失败(已重试%d次): %w", maxRetries, lastErr)
}
// downloadMedia 下载媒体内容
func downloadMedia(url, deviceID string, headers map[string]string) ([]byte, string, error) {
// 创建专用的媒体下载客户端,超时时间更长
// downloadMedia 流式下载媒体内容:拿到响应头即返回,Body 由调用方消费
// 大文件不再整体驻留内存;Body 读取中途的错误无法重试,由客户端自行重试
func downloadMedia(url, deviceID string, headers map[string]string) (io.ReadCloser, string, error) {
// 创建专用的媒体下载客户端,超时时间更长(Timeout 覆盖整个响应周期含 Body 传输)
client := &http.Client{
Timeout: 300 * time.Second, // 5分钟超时,适合大文件
}
@@ -70,6 +71,30 @@ func downloadMedia(url, deviceID string, headers map[string]string) ([]byte, str
return nil, "", err
}
setMediaHeaders(req, deviceID, headers)
resp, err := client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("下载失败: %v", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
resp.Body.Close()
return nil, "", fmt.Errorf("HTTP状态码: %d", resp.StatusCode)
}
// 获取Content-Type
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
// 根据文件后缀推断
contentType = getContentTypeFromURL(url)
}
return resp.Body, contentType, nil
}
// setMediaHeaders 设置媒体下载请求头(CDN 伪装 + 设备信息 + 自定义头)
func setMediaHeaders(req *http.Request, deviceID string, headers map[string]string) {
// 设置CDN请求头,模拟安卓客户端请求
req.Header.Set("User-Agent", "com.dragon.read/7.9.9.32 (Linux; U; Android 13; zh_CN; M2102K1AC; Build/TKQ1.220807.001; Cronet/113.0.5672.62)")
req.Header.Set("Accept", "*/*")
@@ -89,31 +114,6 @@ func downloadMedia(url, deviceID string, headers map[string]string) ([]byte, str
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := client.Do(req)
if err != nil {
return nil, "", fmt.Errorf("下载失败: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, "", fmt.Errorf("HTTP状态码: %d", resp.StatusCode)
}
// 读取内容
data, err := io.ReadAll(resp.Body)
if err != nil {
return nil, "", fmt.Errorf("读取内容失败: %w", err)
}
// 获取Content-Type
contentType := resp.Header.Get("Content-Type")
if contentType == "" {
// 根据文件后缀推断
contentType = getContentTypeFromURL(url)
}
return data, contentType, nil
}
// getContentTypeFromURL 根据URL推断Content-Type
@@ -179,11 +179,16 @@ func processMediaURL(originalURL, deviceID string, headers map[string]string, ou
// 其他类型返回原始URL
return originalURL
case "data_uri":
// 直接下载并返回base64
data, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 2)
// 直接下载并返回base64(data_uri 模式本就要求全量驻留内存)
body, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 2)
if err != nil {
return originalURL
}
data, readErr := io.ReadAll(body)
body.Close()
if readErr != nil {
return originalURL
}
return fmt.Sprintf("data:%s;base64,%s", contentType, base64.StdEncoding.EncodeToString(data))
default:
// 直接返回原始URL
-1
View File
@@ -270,4 +270,3 @@ func MultiContent(itemIDs interface{}, bookID string, textMode, imageMode, ignor
func HandleMultiContent(itemIDs interface{}, bookID string, textMode, imageMode, ignoreFailed interface{}) (string, error) {
return MultiContent(itemIDs, bookID, textMode, imageMode, ignoreFailed, 0)
}
-1
View File
@@ -218,4 +218,3 @@ func fetchMultiDetail(bookID interface{}) (string, error) {
resultBytes, _ := json.Marshal(response)
return string(resultBytes), nil
}
-1
View File
@@ -246,4 +246,3 @@ func GetKeyInfo() *KeyInfo {
func init() {
rand.Seed(time.Now().UnixNano())
}
+35 -1
View File
@@ -1,6 +1,8 @@
package fqapi
import (
"bytes"
"encoding/json"
"fanqie/internal/common"
"fmt"
"net/url"
@@ -57,9 +59,41 @@ func fetchBookSearch(key string, offset int, tabType int) (string, error) {
}
if code, ok := respJSON["code"].(float64); ok && code == 0 {
return resp.Text, nil
// 用 UseNumber 重新解析后按 tab_type 过滤:
// 上游 search/tab/v/ 固定返回所有 tab 的 search_tabs;
// 大整数 ID 经 float64 重组会丢精度,必须 UseNumber
dec := json.NewDecoder(bytes.NewReader(resp.Content))
dec.UseNumber()
var numJSON map[string]interface{}
if err := dec.Decode(&numJSON); err != nil {
return resp.Text, nil // 解析失败时退回原样转发
}
filterSearchTabs(numJSON, tabType)
return ToJSON(numJSON)
}
return BuildErrorResponseWithCode(1, "搜索失败"), nil
}
// filterSearchTabs 按 tab_type 只保留 search_tabs 中匹配的项;无匹配时保留原样
func filterSearchTabs(respJSON map[string]interface{}, tabType int) {
tabs, ok := respJSON["search_tabs"].([]interface{})
if !ok {
return
}
filtered := make([]interface{}, 0, 1)
for _, t := range tabs {
m, ok := t.(map[string]interface{})
if !ok {
continue
}
if tt, ok := m["tab_type"].(json.Number); ok {
if v, err := tt.Int64(); err == nil && int(v) == tabType {
filtered = append(filtered, m)
}
}
}
if len(filtered) > 0 {
respJSON["search_tabs"] = filtered
}
}
+63
View File
@@ -0,0 +1,63 @@
package fqapi
import (
"bytes"
"encoding/json"
"strings"
"testing"
)
// TestFilterSearchTabs 上游返回全部 tab 时,应只保留请求的 tab_type;无匹配时保留原样
func TestFilterSearchTabs(t *testing.T) {
raw := `{"code":0,"search_tabs":[
{"tab_type":1,"title":"综合"},
{"tab_type":3,"title":"书籍","book_id":7123456789012345678}
]}`
decode := func(s string) map[string]interface{} {
dec := json.NewDecoder(strings.NewReader(s))
dec.UseNumber()
var m map[string]interface{}
if err := dec.Decode(&m); err != nil {
t.Fatal(err)
}
return m
}
m := decode(raw)
filterSearchTabs(m, 3)
tabs := m["search_tabs"].([]interface{})
if len(tabs) != 1 {
t.Fatalf("tab_type=3 应只剩 1 个 tab, got %d", len(tabs))
}
// 大整数 ID 不得丢精度
want := "7123456789012345678"
got := tabs[0].(map[string]interface{})["book_id"].(json.Number).String()
if got != want {
t.Errorf("book_id 精度丢失: got %s want %s", got, want)
}
// 无匹配 tab 时保留原样
m = decode(raw)
filterSearchTabs(m, 99)
if len(m["search_tabs"].([]interface{})) != 2 {
t.Error("无匹配时应保留原始 search_tabs")
}
}
// TestToJSONPreservesNumberID 重组后大整数 ID 字符串不变
func TestToJSONPreservesNumberID(t *testing.T) {
dec := json.NewDecoder(bytes.NewReader([]byte(`{"id":7123456789012345678}`)))
dec.UseNumber()
var m map[string]interface{}
if err := dec.Decode(&m); err != nil {
t.Fatal(err)
}
out, err := ToJSON(m)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(out, "7123456789012345678") {
t.Errorf("重组丢失精度: %s", out)
}
}
-1
View File
@@ -193,4 +193,3 @@ func Decrypt(encryptedStr string) ([]byte, error) {
}
return TTDecrypt(encryptedData)
}
-1
View File
@@ -263,4 +263,3 @@ func formatBitrate(bitrate float64) string {
mbps := kbps / unit
return fmt.Sprintf("%.2f Mbps", mbps)
}
-1
View File
@@ -103,4 +103,3 @@ func HandleMultiDetail(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, result)
}
-1
View File
@@ -41,4 +41,3 @@ func HandleCategoryLanding(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, result)
}
+67
View File
@@ -6,9 +6,14 @@ import (
"fanqie/internal/config"
"fanqie/internal/fqapi"
"fmt"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"time"
"golang.org/x/time/rate"
)
var (
@@ -106,6 +111,68 @@ func respondError(w http.ResponseWriter, msg string, isClientErr bool) {
respondJSON(w, status, map[string]interface{}{"code": -1, "msg": msg})
}
// RateLimit 每 IP 限流(server.rate_limit_qps > 0 时启用)
// ponytail: 配置启动时读取一次,热更新不生效;visitor 表由后台协程清理防泄漏
func RateLimit(handler http.HandlerFunc) http.HandlerFunc {
cfg := config.GetAppConfig()
qps := 0.0
if cfg != nil {
qps = cfg.Server.RateLimitQPS
}
if qps <= 0 {
return handler
}
const burst = 10
var mu sync.Mutex
limitters := map[string]*rate.Limiter{}
lastSeen := map[string]time.Time{}
go func() {
for range time.Tick(time.Minute) {
mu.Lock()
for ip, t := range lastSeen {
if time.Since(t) > 10*time.Minute {
delete(lastSeen, ip)
delete(limitters, ip)
}
}
mu.Unlock()
}
}()
return func(w http.ResponseWriter, r *http.Request) {
ip := clientIP(r)
mu.Lock()
l, ok := limitters[ip]
if !ok {
l = rate.NewLimiter(rate.Limit(qps), burst)
limitters[ip] = l
}
lastSeen[ip] = time.Now()
mu.Unlock()
if !l.Allow() {
respondJSON(w, http.StatusTooManyRequests, map[string]interface{}{
"code": -1, "msg": "请求过于频繁,请稍后再试",
})
return
}
handler(w, r)
}
}
// clientIP 取客户端 IP:优先 X-Forwarded-For 首段(反代场景),否则 RemoteAddr
func clientIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
return strings.TrimSpace(strings.Split(xff, ",")[0])
}
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return host
}
return r.RemoteAddr
}
// RequireAccessKey 验证访问密钥中间件
func RequireAccessKey(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
+3 -4
View File
@@ -20,9 +20,9 @@ func HandleContent(w http.ResponseWriter, r *http.Request) {
itemID := params["item_id"]
// 获取URL参数(支持动态覆盖配置)
textMode := r.URL.Query().Get("text_mode") // 1=纯文本模式
imageMode := r.URL.Query().Get("image_mode") // 0=移除图片, 1=保留图片
reviewParam := r.URL.Query().Get("review") // 1=启用段评, 0=禁用段评
textMode := r.URL.Query().Get("text_mode") // 1=纯文本模式
imageMode := r.URL.Query().Get("image_mode") // 0=移除图片, 1=保留图片
reviewParam := r.URL.Query().Get("review") // 1=启用段评, 0=禁用段评
result, err := fqapi.HandleGetContent(itemID, textMode, imageMode)
if err != nil {
@@ -164,4 +164,3 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
return newJSON
}
-1
View File
@@ -41,4 +41,3 @@ func HandleMangaImageProxy(w http.ResponseWriter, r *http.Request) {
// 返回图片数据
w.Write(imageData)
}
+6 -5
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"fanqie/internal/fqapi"
"fmt"
"io"
"net/http"
"strings"
)
@@ -31,9 +32,9 @@ func HandleAudio(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, result)
}
// HandleAudioProxy 音频代理处理
// HandleAudioProxy 音频代理处理(流式转发,音频不全量驻留内存)
func HandleAudioProxy(w http.ResponseWriter, r *http.Request) {
incrementStat("total")
incrementStat("total", "audio")
// 从URL路径提取key: /audio/proxy/{key}
path := r.URL.Path
@@ -44,11 +45,12 @@ func HandleAudioProxy(w http.ResponseWriter, r *http.Request) {
}
// 调用代理处理函数
data, contentType, err := fqapi.HandleAudioProxy(key)
body, contentType, err := fqapi.HandleAudioProxy(key)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
defer body.Close()
// 设置正确的Content-Type
if contentType != "" {
@@ -59,7 +61,7 @@ func HandleAudioProxy(w http.ResponseWriter, r *http.Request) {
// 直接播放,不强制下载
// 浏览器会根据Content-Type决定是播放还是下载
w.Write(data)
io.Copy(w, body)
}
// HandleVideo 视频处理
@@ -133,4 +135,3 @@ func HandleManga(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, string(jsonData))
}
}
+43 -887
View File
@@ -1,9 +1,11 @@
package handlers
import (
_ "embed"
"encoding/json"
"fanqie/internal/fqapi"
"fmt"
"html/template"
"net/http"
"strconv"
"strings"
@@ -216,8 +218,6 @@ func init() {
em.LoadEmojis()
}
// replaceEmojiWithImages 将表情文本替换为图片标签
func replaceEmojiWithImages(text string) string {
return fqapi.ReplaceEmojisInText(text)
@@ -231,6 +231,7 @@ type CommentInfo struct {
StickerImageURL string
CreateTime string
CommentText string
CommentTextHTML template.HTML // 预计算:转义+表情替换后的正文
CommentID string
DiggCount int
ReplyCount int
@@ -307,357 +308,36 @@ func parseCommentData(comment map[string]interface{}) CommentInfo {
return info
}
// reviewTmpl 评论页模板(embed 内嵌;用户内容由 html/template 按上下文自动转义)
//
//go:embed templates/review.html
var reviewHTML string
var reviewTmpl = template.Must(template.New("review").Parse(reviewHTML))
// reviewPageData 评论页模板数据
type reviewPageData struct {
ItemID, BookID string
ParaPlus1, Para, Sort int
Total, NextOffset int
PageSize, CommentCount int
HasMore bool
EmojiMapJS template.JS
Comments []CommentInfo
}
// generateReviewHTML 生成评论 HTML 页面
func generateReviewHTML(data map[string]interface{}, itemID, bookID string, para, page, pageSize, sort int) string {
var html strings.Builder
html.WriteString(`<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>番茄段评 · 第 `)
html.WriteString(strconv.Itoa(para + 1))
html.WriteString(` 段</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.css">
<meta name="color-scheme" content="light dark">
<style>
:root {
/* 浅色模式变量 */
--bg-primary: #f5f5f5;
--bg-secondary: #ffffff;
--text-primary: #333333;
--text-secondary: #666666;
--text-tertiary: #999999;
--border-color: #e5e5e5;
--shadow: rgba(0, 0, 0, 0.05);
--badge-bg: #f0f5ff;
--badge-color: #4a80f0;
--tag-bg: #f0f0f0;
--tag-color: #666666;
--avatar-bg: #f0f0f0;
--loading-color: #666666;
}
/* 深色模式变量 */
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #000000;
--bg-secondary: #1c1c1e;
--text-primary: #ffffff;
--text-secondary: #ebebf5;
--text-tertiary: #8e8e93;
--border-color: #38383a;
--shadow: rgba(0, 0, 0, 0.3);
--badge-bg: #1c3a5f;
--badge-color: #64a3ff;
--tag-bg: #2c2c2e;
--tag-color: #ebebf5;
--avatar-bg: #2c2c2e;
--loading-color: #8e8e93;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
body {
background-color: var(--bg-primary);
color: var(--text-primary);
padding: 15px;
max-width: 600px;
margin: 0 auto;
transition: background-color 0.3s ease, color 0.3s ease;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding: 10px 15px;
background: var(--bg-secondary);
border-radius: 12px;
box-shadow: 0 2px 8px var(--shadow);
transition: background-color 0.3s ease;
}
.header h1 {
font-size: 18px;
color: var(--text-primary);
margin: 0;
flex: 1;
}
.source-tag {
display: inline-block;
padding: 3px 8px;
background-color: var(--tag-bg);
border-radius: 4px;
font-size: 14px;
margin-left: 8px;
color: var(--tag-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
.comment-item {
background: var(--bg-secondary);
border-radius: 12px;
padding: 15px;
box-shadow: 0 2px 8px var(--shadow);
margin-bottom: 15px;
transition: background-color 0.3s ease;
}
.user-info {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.user-avatar, .reply-avatar {
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 10px;
background: var(--avatar-bg);
object-fit: cover;
}
.reply-avatar {
width: 32px;
height: 32px;
}
.user-name {
font-weight: 500;
font-size: 15px;
color: var(--text-primary);
}
.author-badge {
background: var(--badge-bg);
color: var(--badge-color);
font-size: 12px;
padding: 0 6px;
border-radius: 3px;
margin-left: 6px;
}
.user-sticker {
height: 18px;
margin-left: 6px;
vertical-align: middle;
}
.comment-content {
font-size: 15px;
line-height: 1.5;
margin-bottom: 10px;
white-space: pre-line;
}
.comment-img {
max-width: 100%;
border-radius: 6px;
margin: 8px 0;
cursor: pointer;
background: #eee;
}
.emoji-img {
width: 22px;
height: 22px;
vertical-align: middle;
margin: 0 2px;
}
.comment-time {
font-size: 12px;
color: var(--text-tertiary);
margin-bottom: 10px;
}
.comment-meta {
display: flex;
align-items: center;
gap: 15px;
font-size: 13px;
color: var(--text-secondary);
}
.comment-meta i {
margin-right: 4px;
font-size: 14px;
}
.comment-meta span {
cursor: pointer;
display: inline-flex;
align-items: center;
padding: 4px 8px;
border-radius: 6px;
transition: all 0.2s ease;
}
.comment-meta span:hover {
background: var(--bg-secondary);
color: var(--text-primary);
}
.comment-meta span:hover i {
transform: scale(1.1);
}
.reply-btn {
transition: all 0.2s ease;
}
.reply-btn:active {
transform: scale(0.95);
opacity: 0.4;
}
.replies-container {
margin-top: 15px;
padding-left: 25px;
position: relative;
display: none;
}
.replies-container.show {
display: block;
}
.replies-container::before {
content: '';
position: absolute;
left: 8px;
top: 0;
bottom: 0;
width: 2px;
background: var(--border-color);
}
.reply-item {
display: flex;
align-items: flex-start;
margin-bottom: 15px;
}
.reply-content {
flex: 1;
padding-top: 2px;
}
.reply-username {
font-weight: 500;
font-size: 14px;
margin-right: 5px;
color: var(--text-primary);
}
.reply-text {
font-size: 14px;
line-height: 1.4;
margin: 5px 0;
color: var(--text-primary);
}
.reply-time {
font-size: 11px;
color: var(--text-tertiary);
margin-top: 3px;
}
.image-viewer {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.9);
display: none;
justify-content: center;
align-items: center;
z-index: 1000;
}
.image-viewer.show {
display: flex;
}
.image-viewer img {
max-width: 90%;
max-height: 90%;
}
.close-btn {
position: absolute;
top: 20px;
right: 20px;
color: #fff;
font-size: 30px;
cursor: pointer;
}
.empty, .loading {
text-align: center;
color: var(--text-tertiary);
}
.empty {
padding: 20px;
background: var(--bg-secondary);
border-radius: 12px;
}
.loading {
padding: 10px;
color: var(--loading-color);
}
.sort-tabs {
display: flex;
gap: 0;
background: var(--bg-primary);
border-radius: 20px;
padding: 3px;
}
.sort-tab {
padding: 6px 16px;
background: transparent;
border: none;
border-radius: 17px;
cursor: pointer;
font-size: 14px;
color: var(--text-secondary);
transition: all 0.2s ease;
user-select: none;
white-space: nowrap;
}
.sort-tab.active {
background: var(--bg-secondary);
color: var(--text-primary);
font-weight: 500;
box-shadow: 0 1px 3px var(--shadow);
}
.sort-tab:hover:not(.active) {
opacity: 0.7;
}
.back-to-top {
position: fixed;
bottom: 30px;
right: 30px;
width: 50px;
height: 50px;
background: var(--bg-secondary);
border-radius: 50%;
display: none;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 4px 12px var(--shadow);
transition: all 0.3s ease;
z-index: 999;
border: 1px solid var(--border-color);
}
.back-to-top.show {
display: flex;
}
.back-to-top:hover {
transform: translateY(-5px);
box-shadow: 0 6px 16px var(--shadow);
}
.back-to-top i {
font-size: 20px;
color: var(--text-primary);
}
</style>
</head>
<body>
<div class="header">
<h1><span class="source-tag">段落评论 · `)
// 提取评论总数和是否有更多
total := 0
hasMore := false
nextOffset := 0
// 新接口返回 count 字段表示总数
// 提取评论总数(新接口 count 字段)
if countVal, ok := data["count"].(float64); ok {
total = int(countVal)
} else if countVal, ok := data["count"].(int); ok {
total = countVal
}
// 检查是否有更多数据
if hasMoreVal, ok := data["has_more"].(bool); ok {
hasMore = hasMoreVal
} else if hasMoreVal, ok := data["has_more"].(float64); ok {
@@ -665,34 +345,12 @@ func generateReviewHTML(data map[string]interface{}, itemID, bookID string, para
} else if hasMoreVal, ok := data["has_more"].(int); ok {
hasMore = hasMoreVal > 0
}
// 获取下一页的 offset
if nextOffsetVal, ok := data["next_offset"].(float64); ok {
nextOffset = int(nextOffsetVal)
} else if nextOffsetVal, ok := data["next_offset"].(int); ok {
nextOffset = nextOffsetVal
}
html.WriteString(strconv.Itoa(total))
html.WriteString(` 条</span></h1>
<span style="display: flex; align-items: center;">
<i class="fas fa-book-open" style="color: var(--text-tertiary); font-size: 16px; margin: 0 10px;"></i>
</span>
<div class="sort-tabs">
<div class="sort-tab`)
if sort == 1 {
html.WriteString(` active`)
}
html.WriteString(`" onclick="switchSort(1)">最热</div>
<div class="sort-tab`)
if sort == 3 {
html.WriteString(` active`)
}
html.WriteString(`" onclick="switchSort(3)">最新</div>
</div>
</div>
`)
// 解析评论数据
comments := []map[string]interface{}{}
if commentsList, ok := data["comments"].([]interface{}); ok {
@@ -704,538 +362,37 @@ func generateReviewHTML(data map[string]interface{}, itemID, bookID string, para
}
// 计算分页
totalComments := len(comments)
startIdx := (page - 1) * pageSize
endIdx := startIdx + pageSize
if endIdx > totalComments {
endIdx = totalComments
if endIdx > len(comments) {
endIdx = len(comments)
}
// 获取当前页的评论
var pageComments []map[string]interface{}
if startIdx < totalComments {
if startIdx < len(comments) {
pageComments = comments[startIdx:endIdx]
}
html.WriteString(` <div id="comment-list">
`)
if len(pageComments) == 0 {
html.WriteString(` <div class="empty">暂无评论</div>`)
} else {
for idx, comment := range pageComments {
info := parseCommentData(comment)
// 生成 HTML
html.WriteString(` <div class="comment-item" id="comment-`)
html.WriteString(strconv.Itoa(idx))
html.WriteString(`">
<div class="user-info">
<img src="`)
html.WriteString(htmlEscape(info.UserAvatar))
html.WriteString(`" class="user-avatar" alt="`)
html.WriteString(htmlEscape(info.UserName))
html.WriteString(`的头像" onerror="this.style.display='none'" loading="lazy">
<div class="user-name">`)
html.WriteString(htmlEscape(info.UserName))
if info.IsAuthor {
html.WriteString(`<span class="author-badge">作者</span>`)
}
if info.StickerImageURL != "" {
html.WriteString(`<img src="`)
html.WriteString(htmlEscape(info.StickerImageURL))
html.WriteString(`" class="user-sticker" alt="勋章">`)
}
html.WriteString(`</div>
</div>
<div class="comment-content">`)
html.WriteString(replaceEmojiWithImages(htmlEscape(info.CommentText)))
html.WriteString(`</div>
`)
if info.ImageURL != "" {
html.WriteString(` <img src="`)
html.WriteString(htmlEscape(info.ImageURL))
html.WriteString(`" class="comment-img" alt="评论图片" onclick="showImage('`)
html.WriteString(htmlEscape(info.ImageLargeURL))
html.WriteString(`')" onerror="this.style.display='none'" loading="lazy">
`)
}
html.WriteString(` <div class="comment-time">`)
html.WriteString(info.CreateTime)
html.WriteString(`</div>
<div class="comment-meta">
<span><i class="far fa-heart"></i>`)
html.WriteString(strconv.Itoa(info.DiggCount))
html.WriteString(`</span>
<span class="reply-btn" onclick="loadReplies(`)
html.WriteString(strconv.Itoa(idx))
html.WriteString(`, '`)
html.WriteString(htmlEscape(info.CommentID))
html.WriteString(`', `)
html.WriteString(strconv.Itoa(info.ReplyCount))
html.WriteString(`)"><i class="far fa-comment-dots"></i>`)
html.WriteString(strconv.Itoa(info.ReplyCount))
html.WriteString(`</span>
</div>
<div class="replies-container" id="replies-`)
html.WriteString(strconv.Itoa(idx))
html.WriteString(`"></div>
</div>
`)
}
pageInfos := make([]CommentInfo, 0, len(pageComments))
for _, comment := range pageComments {
info := parseCommentData(comment)
// 正文先转义再替换表情为 <img>,预计算后模板按 HTML 输出
info.CommentTextHTML = template.HTML(replaceEmojiWithImages(htmlEscape(info.CommentText)))
pageInfos = append(pageInfos, info)
}
// 如果初始加载就没有更多数据了,显示提示
if !hasMore && len(pageComments) > 0 {
html.WriteString(`
<div class="empty">没有更多评论了</div>`)
var b strings.Builder
if err := reviewTmpl.Execute(&b, reviewPageData{
ItemID: itemID, BookID: bookID,
ParaPlus1: para + 1, Para: para, Sort: sort,
Total: total, NextOffset: nextOffset,
PageSize: pageSize, CommentCount: len(pageComments),
HasMore: hasMore,
EmojiMapJS: template.JS(generateEmojiMapJS()),
Comments: pageInfos,
}); err != nil {
return "<p>评论页渲染失败: " + htmlEscape(err.Error()) + "</p>"
}
html.WriteString(`
</div>
<div class="image-viewer" id="imageViewer">
<span class="close-btn" onclick="closeImage()">&times;</span>
<img id="previewImage" src="" alt="图片预览">
</div>
<div class="back-to-top" id="backToTop" onclick="scrollToTop()">
<i class="fas fa-arrow-up"></i>
</div>
<script>
const itemID = '`)
html.WriteString(itemID)
html.WriteString(`';
const bookID = '`)
html.WriteString(bookID)
html.WriteString(`';
const para = `)
html.WriteString(strconv.Itoa(para))
html.WriteString(`;
let currentSort = `)
html.WriteString(strconv.Itoa(sort))
html.WriteString(`;
const commentList = document.getElementById('comment-list');
const imageViewer = document.getElementById('imageViewer');
const backToTopBtn = document.getElementById('backToTop');
const LOADING_HTML = '<div class="loading"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>';
// 已加载回复的评论
const loadedReplies = new Set();
// URL 构建
function buildReviewURL(params) {
const baseParams = {
item_id: itemID,
book_id: bookID,
para: para
};
const query = new URLSearchParams({...baseParams, ...params});
return '/review?' + query.toString();
}
// 时间格式化
function formatTime(timestamp, format = 'simple') {
const date = new Date(timestamp * 1000);
if (format === 'full') {
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
}).replace(/\//g, '-');
}
return date.toLocaleString('zh-CN');
}
// 图片渲染
function renderImage(imageData, type = 'comment') {
if (!imageData?.[0]) return '';
const imgUrl = imageData[0].expand_web_url || imageData[0].web_uri || '';
if (!imgUrl) return '';
const escapedUrl = escapeHtml(imgUrl);
if (type === 'reply') {
return '<img src="' + escapedUrl + '" class="comment-img" alt="回复图片" onclick="showImage(\'' + escapedUrl + '\')" onerror="this.style.display=\'none\'" style="max-width:200px;margin-top:5px;border-radius:4px;cursor:pointer;" loading="lazy">';
}
const largeUrl = escapeHtml(imageData[0].expand_web_url || imgUrl);
return '<img src="' + escapedUrl + '" class="comment-img" alt="评论图片" onclick="showImage(\'' + largeUrl + '\')" onerror="this.style.display=\'none\'" loading="lazy">';
}
// 防抖
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 滚动信息获取
function getScrollInfo() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollHeight = document.documentElement.scrollHeight;
const clientHeight = document.documentElement.clientHeight;
return {
scrollTop,
scrollHeight,
clientHeight,
distanceFromBottom: scrollHeight - (scrollTop + clientHeight)
};
}
// 切换排序
async function switchSort(newSort) {
if (currentSort === newSort) return;
document.querySelectorAll('.sort-tab').forEach(tab => tab.classList.remove('active'));
event.target.closest('.sort-tab').classList.add('active');
commentList.innerHTML = LOADING_HTML;
try {
currentSort = newSort;
currentOffset = 0;
const url = buildReviewURL({ offset: 0, count: 20, sort: newSort });
const response = await fetch(url);
const result = await response.json();
if (result.code === 0 && result.data && result.data.comments) {
hasMore = result.data.has_more || false;
currentOffset = result.data.next_offset || 0;
const comments = result.data.comments || [];
if (comments.length === 0) {
commentList.innerHTML = '<div class="empty">暂无评论</div>';
commentIndex = 0;
} else {
commentList.innerHTML = comments.map((comment, idx) => renderComment(comment, idx)).join('');
commentIndex = comments.length;
// 如果没有更多数据,显示提示
if (!hasMore) {
commentList.insertAdjacentHTML('beforeend', '<div class="empty">没有更多评论了</div>');
}
}
loadedReplies.clear();
window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
commentList.innerHTML = '<div class="empty">加载失败,请重试</div>';
commentIndex = 0;
}
} catch (error) {
console.error('切换排序失败:', error);
commentList.innerHTML = '<div class="empty">加载失败,请重试</div>';
}
}
// 加载回复
async function loadReplies(idx, commentID, count) {
const container = document.getElementById('replies-' + idx);
if (count === 0) {
if (container.classList.contains('show')) {
container.classList.remove('show');
return;
}
container.innerHTML = '<div class="loading" style="color: #999;">暂无回复</div>';
container.classList.add('show');
loadedReplies.add(commentID);
return;
}
if (loadedReplies.has(commentID)) {
container.classList.toggle('show');
return;
}
container.innerHTML = LOADING_HTML;
container.classList.add('show');
try {
const url = buildReviewURL({ comment_id: commentID, offset: 0, count: 20 });
const response = await fetch(url);
const result = await response.json();
if (result.code !== 0 || !result.data) {
container.innerHTML = '<div class="loading">暂无回复</div>';
return;
}
const replies = result.data.reply_list || [];
const totalCount = result.data.count || replies.length;
const hasMore = result.data.has_more || false;
const nextOffset = result.data.next_offset || 0;
if (replies.length === 0) {
container.innerHTML = '<div class="loading">暂无回复</div>';
return;
}
let html = replies.map(renderReply).join('');
if (hasMore) {
html += '<div class="load-more-replies" style="text-align:center;padding:10px;color:var(--text-secondary);cursor:pointer;" ' +
'onclick="loadMoreReplies(\'' + escapeHtml(commentID) + '\', ' + nextOffset + ', this)">' +
'<i class="fas fa-angle-down"></i> 加载更多回复 (还有 ' + (totalCount - replies.length) + ' 条)' +
'</div>';
}
container.innerHTML = html;
loadedReplies.add(commentID);
} catch (error) {
console.error('加载回复失败:', error);
container.innerHTML = '<div class="loading">加载失败</div>';
}
}
// 加载更多回复
async function loadMoreReplies(commentID, offset, button) {
button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 加载中...';
try {
const url = buildReviewURL({ comment_id: commentID, offset: offset, count: 20 });
const response = await fetch(url);
const result = await response.json();
if (result.code !== 0 || !result.data) {
button.textContent = '加载失败';
return;
}
const replies = result.data.reply_list || [];
const totalCount = result.data.count || 0;
const hasMore = result.data.has_more || false;
const nextOffset = result.data.next_offset || 0;
button.insertAdjacentHTML('beforebegin', replies.map(renderReply).join(''));
if (hasMore) {
const loadedCount = offset + replies.length;
button.innerHTML = '<i class="fas fa-angle-down"></i> 加载更多回复 (还有 ' + (totalCount - loadedCount) + ' 条)';
button.onclick = () => loadMoreReplies(commentID, nextOffset, button);
} else {
button.remove();
}
} catch (error) {
console.error('加载更多回复失败:', error);
button.textContent = '加载失败,点击重试';
}
}
// HTML 转义
const htmlEscapeMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
function escapeHtml(text) {
return text.replace(/[&<>"']/g, m => htmlEscapeMap[m]);
}
// 表情替换
const emojiMap = ` + generateEmojiMapJS() + `;
const emojiPattern = new RegExp(
Object.keys(emojiMap)
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|'),
'g'
);
function replaceEmoji(text) {
return text.replace(emojiPattern, match =>
'<img src="' + emojiMap[match] + '" class="emoji-img" alt="' + match + '" title="' + match + '" loading="lazy">'
);
}
// 渲染单个回复
function renderReply(reply) {
const userName = reply.user_info?.user_name || '匿名用户';
const userAvatar = reply.user_info?.user_avatar || '';
const text = reply.text || '';
const time = formatTime(reply.create_timestamp || 0);
const imageHTML = renderImage(reply.image_data, 'reply');
return '<div class="reply-item">' +
'<img src="' + escapeHtml(userAvatar) + '" class="reply-avatar" alt="' + escapeHtml(userName) + '的头像" onerror="this.style.display=\'none\';" loading="lazy">' +
'<div class="reply-content">' +
'<span class="reply-username">' + escapeHtml(userName) + '</span>' +
'<div class="reply-text">' + replaceEmoji(escapeHtml(text)) + imageHTML + '</div>' +
'<div class="reply-time">' + time + '</div>' +
'</div>' +
'</div>';
}
// 渲染单个评论
function renderComment(comment, idx) {
const userName = comment.user_info?.user_name || '匿名用户';
const userAvatar = comment.user_info?.user_avatar || '';
const isAuthor = comment.user_info?.is_author || false;
const commentText = comment.text || '';
const commentID = comment.comment_id || '';
const diggCount = comment.digg_count || 0;
const replyCount = comment.reply_count || 0;
const createTime = formatTime(comment.create_timestamp || 0, 'full');
const imageHTML = renderImage(comment.image_data);
return '<div class="comment-item" id="comment-' + idx + '">' +
'<div class="user-info">' +
'<img src="' + escapeHtml(userAvatar) + '" class="user-avatar" alt="' + escapeHtml(userName) + '的头像" onerror="this.style.display=\'none\'" loading="lazy">' +
'<div class="user-name">' + escapeHtml(userName) +
(isAuthor ? '<span class="author-badge">作者</span>' : '') +
'</div></div>' +
'<div class="comment-content">' + replaceEmoji(escapeHtml(commentText)) + '</div>' +
imageHTML +
'<div class="comment-time">' + createTime + '</div>' +
'<div class="comment-meta">' +
'<span><i class="far fa-heart"></i>' + diggCount + '</span>' +
'<span class="reply-btn" onclick="loadReplies(' + idx + ', \'' + escapeHtml(commentID) + '\', ' + replyCount + ')">' +
'<i class="far fa-comment-dots"></i>' + replyCount + '</span>' +
'</div>' +
'<div class="replies-container" id="replies-' + idx + '"></div>' +
'</div>';
}
// 显示图片
function showImage(url) {
document.getElementById('previewImage').src = url;
imageViewer.classList.add('show');
document.body.style.overflow = 'hidden';
}
// 关闭图片
function closeImage() {
imageViewer.classList.remove('show');
document.body.style.overflow = '';
}
// 点击空白处关闭
imageViewer.addEventListener('click', e => {
if (e.target.id === 'imageViewer') closeImage();
});
// ESC 键关闭
document.addEventListener('keydown', e => {
if (e.key === 'Escape') closeImage();
});
// 懒加载相关变量
let currentOffset = `)
html.WriteString(strconv.Itoa(nextOffset))
html.WriteString(`;
const pageSize = `)
html.WriteString(strconv.Itoa(pageSize))
html.WriteString(`;
let hasMore = `)
if hasMore {
html.WriteString(`true`)
} else {
html.WriteString(`false`)
}
html.WriteString(`;
let isLoading = false;
let commentIndex = `)
html.WriteString(strconv.Itoa(len(pageComments)))
html.WriteString(`;
// 懒加载更多评论
async function loadMoreComments() {
if (isLoading || !hasMore) return;
isLoading = true;
let loadingDiv = document.getElementById('loading-indicator');
if (!loadingDiv) {
loadingDiv = document.createElement('div');
loadingDiv.id = 'loading-indicator';
loadingDiv.className = 'loading';
loadingDiv.innerHTML = LOADING_HTML;
commentList.appendChild(loadingDiv);
}
loadingDiv.style.display = 'block';
try {
const url = buildReviewURL({ offset: currentOffset, count: pageSize, sort: currentSort });
const response = await fetch(url);
const result = await response.json();
if (result.code === 0 && result.data) {
const comments = result.data.comments || [];
if (comments.length > 0) {
loadingDiv?.remove();
hasMore = result.data.has_more === true;
currentOffset = result.data.next_offset || 0;
comments.forEach((comment, idx) => {
commentList.insertAdjacentHTML('beforeend', renderComment(comment, commentIndex + idx));
});
commentIndex += comments.length;
if (!hasMore) {
commentList.insertAdjacentHTML('beforeend', '<div class="empty">没有更多评论了</div>');
}
} else {
loadingDiv.className = 'empty';
loadingDiv.textContent = '没有更多评论了';
hasMore = false;
}
} else {
loadingDiv.className = 'empty';
loadingDiv.textContent = '没有更多评论了';
hasMore = false;
}
} catch (error) {
console.error('加载失败:', error);
if (loadingDiv) {
loadingDiv.textContent = '加载失败';
setTimeout(() => loadingDiv.remove(), 2000);
}
} finally {
isLoading = false;
}
}
// 回到顶部
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
// 滚动监听
const handleScroll = debounce(() => {
const scroll = getScrollInfo();
// 显示/隐藏回到顶部按钮
backToTopBtn.classList.toggle('show', scroll.scrollTop > 300);
// 距离底部 200px 时触发加载
if (scroll.distanceFromBottom <= 200) {
loadMoreComments();
}
}, 100);
window.addEventListener('scroll', handleScroll, { passive: true });
</script>
</body>
</html>`)
return html.String()
return b.String()
}
// htmlEscape HTML 转义
@@ -1278,4 +435,3 @@ func respondJSON(w http.ResponseWriter, statusCode int, data interface{}) {
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(data)
}
+36 -788
View File
@@ -1,11 +1,13 @@
package handlers
import (
_ "embed"
"encoding/json"
"fanqie/internal/algos"
"fanqie/internal/config"
"fanqie/internal/fqapi"
"fmt"
"html/template"
"net/http"
"time"
)
@@ -39,6 +41,13 @@ func HandleVacuum(w http.ResponseWriter, r *http.Request) {
})
}
// 状态页模板(embed 内嵌,动态数据由 html/template 自动转义)
//
//go:embed templates/status.html
var statusHTML string
var statusTmpl = template.Must(template.New("status").Parse(statusHTML))
// HandleStatus 状态页面处理
func HandleStatus(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
@@ -77,793 +86,33 @@ func HandleStatus(w http.ResponseWriter, r *http.Request) {
// 获取设备密钥池状态
poolStatus := getDeviceKeyPoolStatus()
html := fmt.Sprintf(`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>番茄小说API - 运行状态</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", Arial, sans-serif;
background: #f5f5f5;
min-height: 100vh;
padding: 20px;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
text-align: center;
color: #333;
margin-bottom: 30px;
background: white;
padding: 30px;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.08);
}
.header h1 {
font-size: 2em;
margin-bottom: 8px;
color: #1a1a1a;
}
.header p {
font-size: 1em;
color: #666;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 20px;
margin-bottom: 20px;
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.08);
border: 1px solid #e0e0e0;
}
.card-title {
font-size: 1.1em;
color: #333;
margin-bottom: 15px;
font-weight: 600;
padding-bottom: 8px;
border-bottom: 2px solid #f0f0f0;
}
.stat-item {
display: flex;
justify-content: space-between;
padding: 8px 0;
border-bottom: 1px solid #f5f5f5;
}
.stat-item:last-child {
border-bottom: none;
}
.stat-label {
color: #666;
font-size: 0.95em;
}
.stat-value {
color: #1a1a1a;
font-weight: 600;
font-size: 0.95em;
}
.api-docs {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.08);
border: 1px solid #e0e0e0;
}
.api-section {
margin-bottom: 25px;
}
.api-section:last-child {
margin-bottom: 0;
}
.api-section-title {
color: #1a1a1a;
font-size: 1em;
font-weight: 600;
margin-bottom: 12px;
padding-left: 20px;
position: relative;
}
.api-section-title::before {
content: "▸";
position: absolute;
left: 0;
color: #666;
}
.api-endpoint {
background: #fafafa;
border: 1px solid #e8e8e8;
border-radius: 6px;
padding: 12px;
margin-bottom: 10px;
}
.api-endpoint:last-child {
margin-bottom: 0;
}
.api-method {
display: inline-block;
background: #2196F3;
color: white;
padding: 2px 8px;
border-radius: 3px;
font-size: 0.75em;
font-weight: 600;
margin-right: 8px;
}
.api-path {
font-family: "Consolas", "Monaco", monospace;
font-size: 0.9em;
color: #333;
font-weight: 500;
}
.api-desc {
color: #666;
font-size: 0.85em;
margin-top: 6px;
padding-left: 4px;
}
.api-params {
margin-top: 8px;
padding-left: 4px;
}
.param-item {
display: flex;
align-items: center;
font-size: 0.8em;
margin: 4px 0;
color: #555;
}
.param-name {
font-family: "Consolas", "Monaco", monospace;
color: #e91e63;
font-weight: 500;
margin-right: 6px;
}
.param-required {
background: #ff9800;
color: white;
padding: 1px 5px;
border-radius: 2px;
font-size: 0.75em;
margin-right: 6px;
}
.param-optional {
background: #2196F3;
color: white;
padding: 1px 5px;
border-radius: 2px;
font-size: 0.75em;
margin-right: 6px;
}
.param-desc {
color: #777;
}
.badge {
display: inline-block;
padding: 2px 8px;
border-radius: 12px;
font-size: 0.75em;
font-weight: 600;
margin-left: 8px;
}
.badge-success {
background: #d4edda;
color: #155724;
}
.badge-info {
background: #d1ecf1;
color: #0c5460;
}
.badge-warning {
background: #fff3cd;
color: #856404;
}
.badge-clickable {
cursor: pointer;
transition: all 0.2s;
}
.badge-clickable:hover {
background: #ffc107;
color: #000;
transform: scale(1.05);
}
.badge-clickable:active {
transform: scale(0.95);
}
.toast {
position: fixed;
top: 20px;
right: 20px;
padding: 15px 20px;
background: #333;
color: white;
border-radius: 6px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
z-index: 9999;
animation: slideIn 0.3s ease-out;
max-width: 300px;
}
.toast.success {
background: #4caf50;
}
.toast.error {
background: #f44336;
}
@keyframes slideIn {
from {
transform: translateX(400px);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
}
@keyframes slideOut {
from {
transform: translateX(0);
opacity: 1;
}
to {
transform: translateX(400px);
opacity: 0;
}
}
</style>
<script type="text/javascript">
let autoRefreshInterval;
window.onload = function() {
startAutoRefresh();
}
function startAutoRefresh() {
autoRefreshInterval = setInterval(function() {
fetch(window.location.href)
.then(response => response.text())
.then(html => {
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const newBody = doc.querySelector('body');
document.body.innerHTML = newBody.innerHTML;
})
.catch(err => console.error('刷新失败:', err));
}, 3000);
}
function stopAutoRefresh() {
if (autoRefreshInterval) {
clearInterval(autoRefreshInterval);
}
}
function showToast(message, type = 'success') {
const toast = document.createElement('div');
toast.className = 'toast ' + type;
toast.textContent = message;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.animation = 'slideOut 0.3s ease-out';
setTimeout(() => {
document.body.removeChild(toast);
}, 300);
}, 3000);
}
function performVacuum() {
stopAutoRefresh();
const badge = event.target;
const originalText = badge.textContent;
badge.textContent = '压缩中...';
badge.style.cursor = 'wait';
const urlParams = new URLSearchParams(window.location.search);
const key = urlParams.get('key');
const vacuumUrl = key ? '/vacuum?key=' + encodeURIComponent(key) : '/vacuum';
fetch(vacuumUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
showToast(data.message, 'success');
setTimeout(() => {
location.reload();
}, 1000);
} else {
showToast(data.message, 'error');
badge.textContent = originalText;
badge.style.cursor = 'pointer';
startAutoRefresh();
}
})
.catch(err => {
showToast('压缩失败: ' + err.message, 'error');
badge.textContent = originalText;
badge.style.cursor = 'pointer';
startAutoRefresh();
});
}
</script>
</head>
<body>
<div class="container">
<div class="header">
<h1>番茄小说API</h1>
<p>运行状态监控面板</p>
</div>
<div class="grid">
<div class="card">
<div class="card-title">● 运行状态</div>
<div class="stat-item">
<span class="stat-label">服务器时间</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">运行时长</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">启动时间</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item" style="flex-direction: column; align-items: flex-start;">
<span class="stat-label" style="margin-bottom: 8px;">签名方法</span>
<span class="stat-value" style="font-size: 13px; line-height: 1.6;">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">数据库大小</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">已用空间</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">空闲空间</span>
<span class="stat-value">%s <span class="badge badge-warning badge-clickable" onclick="performVacuum()" title="点击立即压缩数据库">立即压缩</span></span>
</div>
</div>
<div class="card">
<div class="card-title">◉ 设备密钥池</div>
<div class="stat-item">
<span class="stat-label">池状态</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">总设备数</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">有效设备</span>
<span class="stat-value">%d <span class="badge badge-success">可用</span></span>
</div>
<div class="stat-item">
<span class="stat-label">无效设备</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">当前索引</span>
<span class="stat-value">%d</span>
</div>
</div>
<div class="card">
<div class="card-title">■ 请求统计</div>
<div class="stat-item">
<span class="stat-label">总请求数</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">搜索请求</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">详情请求</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">目录请求</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">内容请求</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">漫画请求</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">音频请求</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">视频请求</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">分类请求</span>
<span class="stat-value">%d</span>
</div>
</div>
<div class="card">
<div class="card-title">◆ 缓存统计</div>
<div class="stat-item">
<span class="stat-label">正文缓存数</span>
<span class="stat-value">%d</span>
</div>
<div class="stat-item">
<span class="stat-label">正文缓存</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">自动清理</span>
<span class="stat-value">%s</span>
</div>
<div class="stat-item">
<span class="stat-label">清理间隔</span>
<span class="stat-value">%s</span>
</div>
</div>
</div>
<div class="api-docs">
<div class="card-title">◈ API 接口文档</div>
<!-- 书籍相关 -->
<div class="api-section">
<div class="api-section-title">书籍相关</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/search</span></div>
<div class="api-desc">◆ 搜索书籍</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">query</span>
<span class="param-required">必需</span>
<span class="param-desc">搜索关键字</span>
</div>
<div class="param-item">
<span class="param-name">offset</span>
<span class="param-optional">可选</span>
<span class="param-desc">偏移量,默认0</span>
</div>
<div class="param-item">
<span class="param-name">tab_type</span>
<span class="param-optional">可选</span>
<span class="param-desc">类型,默认3</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/detail</span></div>
<div class="api-desc">◆ 获取书籍详情</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">book_id</span>
<span class="param-required">必需</span>
<span class="param-desc">书籍ID</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/catalog</span></div>
<div class="api-desc">◆ 获取书籍目录</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">book_id</span>
<span class="param-required">必需</span>
<span class="param-desc">书籍ID</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/multi-detail</span></div>
<div class="api-desc">◆ 批量获取书籍详情</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">book_id</span>
<span class="param-required">必需</span>
<span class="param-desc">书籍ID列表,逗号分隔</span>
</div>
</div>
</div>
</div>
<!-- 内容相关 -->
<div class="api-section">
<div class="api-section-title">内容相关</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/content</span></div>
<div class="api-desc">◆ 获取章节正文内容</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">item_id</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID,支持路径参数或查询参数</span>
</div>
<div class="param-item">
<span class="param-name">text_mode</span>
<span class="param-optional">可选</span>
<span class="param-desc">纯文本模式:1/true=纯文本,0/false=HTML</span>
</div>
<div class="param-item">
<span class="param-name">image_mode</span>
<span class="param-optional">可选</span>
<span class="param-desc">图片处理:1/true=保留图片,0/false=移除图片</span>
</div>
<div class="param-item">
<span class="param-name">review</span>
<span class="param-optional">可选</span>
<span class="param-desc">段评功能:1=启用,0=禁用</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/multi-content</span></div>
<div class="api-desc">◆ 批量获取多个章节正文</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">book_id</span>
<span class="param-required">必需</span>
<span class="param-desc">书籍ID</span>
</div>
<div class="param-item">
<span class="param-name">item_ids</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID列表,多个ID用逗号分隔,如:123,456,789</span>
</div>
<div class="param-item">
<span class="param-name">text_mode</span>
<span class="param-optional">可选</span>
<span class="param-desc">纯文本模式:1/true=纯文本,0/false=HTML</span>
</div>
<div class="param-item">
<span class="param-name">image_mode</span>
<span class="param-optional">可选</span>
<span class="param-desc">图片处理:1/true=保留图片,0/false=移除图片</span>
</div>
<div class="param-item">
<span class="param-name">ignore_failed</span>
<span class="param-optional">可选</span>
<span class="param-desc">忽略失败章节:1/true=忽略,0/false=不忽略</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/item-summary</span></div>
<div class="api-desc">◆ 获取章节摘要信息</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">book_id</span>
<span class="param-required">必需</span>
<span class="param-desc">书籍ID</span>
</div>
<div class="param-item">
<span class="param-name">item_ids</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID列表,逗号分隔</span>
</div>
</div>
</div>
</div>
<!-- 段评相关 -->
<div class="api-section">
<div class="api-section-title">段评相关</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/review</span></div>
<div class="api-desc">◆ 获取段落评论、回复</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">item_id</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID</span>
</div>
<div class="param-item">
<span class="param-name">book_id</span>
<span class="param-required">必需</span>
<span class="param-desc">书籍ID</span>
</div>
<div class="param-item">
<span class="param-name">para</span>
<span class="param-required">必需</span>
<span class="param-desc">段落索引(从0开始)</span>
</div>
<div class="param-item">
<span class="param-name">comment_id</span>
<span class="param-optional">可选</span>
<span class="param-desc">评论ID(获取回复时需要)</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/review_html</span></div>
<div class="api-desc">◆ 获取段落评论HTML页面</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">item_id</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID</span>
</div>
<div class="param-item">
<span class="param-name">book_id</span>
<span class="param-required">必需</span>
<span class="param-desc">书籍ID</span>
</div>
<div class="param-item">
<span class="param-name">para</span>
<span class="param-required">必需</span>
<span class="param-desc">段落索引(从0开始)</span>
</div>
</div>
</div>
</div>
<!-- 多媒体 -->
<div class="api-section">
<div class="api-section-title">多媒体</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/manga</span></div>
<div class="api-desc">◆ 获取漫画内容</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">item_ids</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID</span>
</div>
<div class="param-item">
<span class="param-name">output</span>
<span class="param-optional">可选</span>
<span class="param-desc">输出格式:url/proxy/data_uri,默认url</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/audio</span></div>
<div class="api-desc">◆ 获取音频信息</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">item_ids</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID</span>
</div>
<div class="param-item">
<span class="param-name">tone_id</span>
<span class="param-optional">可选</span>
<span class="param-desc">音色ID,默认1</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/video</span></div>
<div class="api-desc">◆ 获取视频信息</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">item_ids</span>
<span class="param-required">必需</span>
<span class="param-desc">章节ID</span>
</div>
</div>
</div>
</div>
<!-- 分类 -->
<div class="api-section">
<div class="api-section-title">分类</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/category-front</span></div>
<div class="api-desc">◆ 获取分类首页</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">tab</span>
<span class="param-optional">可选</span>
<span class="param-desc">标签页,默认0</span>
</div>
</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/category-landing</span></div>
<div class="api-desc">◆ 获取分类详情页</div>
<div class="api-params">
<div class="param-item">
<span class="param-name">category_id</span>
<span class="param-required">必需</span>
<span class="param-desc">分类ID</span>
</div>
<div class="param-item">
<span class="param-name">offset</span>
<span class="param-optional">可选</span>
<span class="param-desc">偏移量,默认0</span>
</div>
<div class="param-item">
<span class="param-name">limit</span>
<span class="param-optional">可选</span>
<span class="param-desc">每页数量,默认20</span>
</div>
</div>
</div>
</div>
<!-- 系统 -->
<div class="api-section">
<div class="api-section-title">系统</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/status</span></div>
<div class="api-desc">◆ 系统状态页面(当前页面)</div>
</div>
<div class="api-endpoint">
<div><span class="api-method">GET</span><span class="api-path">/self-info</span></div>
<div class="api-desc">◆ 设备信息(包含敏感数据)</div>
</div>
</div>
</div>
</div>
</body>
</html>
`,
time.Now().Format("2006-01-02 15:04:05"),
uptimeStr,
startTime.Format("2006-01-02 15:04:05"),
signatureDetails,
getDBTotalSize(),
getDBUsedSize(),
getDBFreeSize(),
poolStatus["status"],
poolStatus["total"],
poolStatus["valid"],
poolStatus["invalid"],
poolStatus["current_index"],
stats["total"],
stats["search"],
stats["detail"],
stats["catalog"],
stats["content"],
stats["manga"],
stats["audio"],
stats["video"],
stats["category"],
getDBCacheCount(),
getCacheStatus(),
getCleanupStatus(),
getCleanupInterval(),
)
fmt.Fprint(w, html)
statusTmpl.Execute(w, map[string]interface{}{
"NowTime": time.Now().Format("2006-01-02 15:04:05"),
"Uptime": uptimeStr,
"StartTime": startTime.Format("2006-01-02 15:04:05"),
"Signature": signatureDetails,
"DBTotal": getDBTotalSize(),
"DBUsed": getDBUsedSize(),
"DBFree": getDBFreeSize(),
"PoolStatus": poolStatus["status"],
"PoolTotal": poolStatus["total"],
"PoolValid": poolStatus["valid"],
"PoolInvalid": poolStatus["invalid"],
"PoolIndex": poolStatus["current_index"],
"StatTotal": stats["total"],
"StatSearch": stats["search"],
"StatDetail": stats["detail"],
"StatCatalog": stats["catalog"],
"StatContent": stats["content"],
"StatManga": stats["manga"],
"StatAudio": stats["audio"],
"StatVideo": stats["video"],
"StatCategory": stats["category"],
"CacheCount": getDBCacheCount(),
"CacheStatus": getCacheStatus(),
"CleanupStatus": getCleanupStatus(),
"CleanupInterval": getCleanupInterval(),
})
}
// getCacheStatus 获取缓存状态
@@ -1019,4 +268,3 @@ func getDeviceKeyPoolStatus() map[string]interface{} {
"current_index": stats["current_index"],
}
}
+2 -2
View File
@@ -171,12 +171,12 @@ paths:
example: 0
- name: tab_type
in: query
description: 搜索类型,默认 3
description: 搜索类型,默认 3;响应 search_tabs 仅保留匹配该值的 tab
schema: { type: integer, default: 3 }
example: 3
responses:
"200":
description: 搜索结果(上游转发,结构以实际返回为准)
description: 搜索结果(search_tabs 已按请求的 tab_type 过滤,仅保留匹配项)
content:
application/json:
schema: