Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bcc8a962e | ||
|
|
ad6d28fd85 | ||
|
|
f89bee8ddc | ||
|
|
822d3fe444 | ||
|
|
8bc6f5c2ae | ||
|
|
bb0cc39950 |
No files matched your search
@@ -34,9 +34,11 @@ Go 语言实现的番茄小说非官方 API 服务,完整实现了签名算法
|
|||||||
|
|
||||||
- **签名算法** - Gorgon、8404、Argus、Ladon、Khronos
|
- **签名算法** - 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 /` | GET | 服务首页 |
|
||||||
|
| `GET /healthz` | GET | 存活探针(不校验密钥,供容器/反代使用) |
|
||||||
| `GET /status` | GET | 服务状态(需 AccessKey) |
|
| `GET /status` | GET | 服务状态(需 AccessKey) |
|
||||||
| `GET /self-info` | 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` |
|
| `/detail` | GET | 书籍详情 | `book_id` |
|
||||||
| `/info` | GET | 书籍详情(同 detail) | `book_id` |
|
| `/info` | GET | 书籍详情(同 detail) | `book_id` |
|
||||||
| `/catalog` | GET | 章节目录 | `book_id` |
|
| `/catalog` | GET | 章节目录 | `book_id` |
|
||||||
| `/directory/all_items` | GET | 章节目录(同 catalog) | `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` |
|
| `/content` | GET | 章节内容 | `item_id` |
|
||||||
| `/multi-content` | GET | 批量章节内容 | `chapter_ids`(逗号分隔) |
|
| `/multi-content` | GET | 批量章节内容 | `book_id`, `item_ids`(逗号分隔) |
|
||||||
| `/item-summary` | GET | 章节摘要 | `book_id`, `chapter_id` |
|
| `/item-summary` | GET | 章节摘要 | `book_id`, `item_ids`(逗号分隔) |
|
||||||
|
|
||||||
### 评论相关
|
### 评论相关
|
||||||
|
|
||||||
| 接口 | 方法 | 说明 | 参数 |
|
| 接口 | 方法 | 说明 | 参数 |
|
||||||
| ------ | ------ | ------ | ------ |
|
| ------ | ------ | ------ | ------ |
|
||||||
| `/chapter_review` | GET | 章节评论 | `book_id`, `chapter_id` |
|
| `/chapter_review` | GET | 章节评论 | `book_id`, `item_id` |
|
||||||
| `/review` | GET | 书评列表 | `book_id`, `offset`, `limit` |
|
| `/review` | GET | 书评列表 | `book_id`, `item_id`, `para`, `comment_id`, `offset`, `limit` |
|
||||||
| `/review_html` | GET | 评论 HTML | `book_id`, `chapter_id` |
|
| `/review_html` | GET | 评论 HTML | `book_id`, `item_id`, `para` |
|
||||||
|
|
||||||
### 分类相关
|
### 分类相关
|
||||||
|
|
||||||
@@ -176,9 +179,9 @@ go run ./cmd/fanqie
|
|||||||
|
|
||||||
| 接口 | 方法 | 说明 | 参数 |
|
| 接口 | 方法 | 说明 | 参数 |
|
||||||
| ------ | ------ | ------ | ------ |
|
| ------ | ------ | ------ | ------ |
|
||||||
| `/audio` | GET | 音频内容 | `audio_id`, `tone_id` |
|
| `/audio` | GET | 音频内容 | `item_ids`, `tone_id`, `output` |
|
||||||
| `/video` | GET | 视频内容 | `video_id` |
|
| `/video` | GET | 视频内容 | `item_ids` |
|
||||||
| `/manga` | GET | 漫画内容 | `manga_id`, `chapter_id` |
|
| `/manga` | GET | 漫画内容 | `item_ids`(或 `item_id`), `show_html`, `output` |
|
||||||
| `/manga/image/{itemID}/{index}` | GET | 漫画图片 | 路径参数 |
|
| `/manga/image/{itemID}/{index}` | GET | 漫画图片 | 路径参数 |
|
||||||
|
|
||||||
## 内容获取示例
|
## 内容获取示例
|
||||||
@@ -235,6 +238,7 @@ server:
|
|||||||
host: "0.0.0.0" # 监听地址
|
host: "0.0.0.0" # 监听地址
|
||||||
port: "40180" # 监听端口
|
port: "40180" # 监听端口
|
||||||
access_key: "" # 访问密钥(可选)
|
access_key: "" # 访问密钥(可选)
|
||||||
|
protect_all: false # 业务接口也要求访问密钥(公网部署建议开启)
|
||||||
|
|
||||||
# 番茄小说配置
|
# 番茄小说配置
|
||||||
fanqie:
|
fanqie:
|
||||||
@@ -324,6 +328,7 @@ cp .env.example .env
|
|||||||
| `server.host` | HTTP 服务监听地址 | `0.0.0.0` |
|
| `server.host` | HTTP 服务监听地址 | `0.0.0.0` |
|
||||||
| `server.port` | HTTP 服务监听端口 | `40180` |
|
| `server.port` | HTTP 服务监听端口 | `40180` |
|
||||||
| `server.access_key` | 访问密钥,设为空则不验证 | - |
|
| `server.access_key` | 访问密钥,设为空则不验证 | - |
|
||||||
|
| `server.protect_all` | 业务接口是否也要求访问密钥 | `false` |
|
||||||
| `fanqie.algorithm` | 签名算法 `gorgon` / `8404` | `gorgon` |
|
| `fanqie.algorithm` | 签名算法 `gorgon` / `8404` | `gorgon` |
|
||||||
| `fanqie.signature` | 签名方法 `sign2` / `sign4` | `sign4` |
|
| `fanqie.signature` | 签名方法 `sign2` / `sign4` | `sign4` |
|
||||||
| `fanqie.content.*` | 正文内容处理选项 | 见上文 |
|
| `fanqie.content.*` | 正文内容处理选项 | 见上文 |
|
||||||
@@ -377,15 +382,24 @@ cp .env.example .env
|
|||||||
|
|
||||||
## 缓存机制
|
## 缓存机制
|
||||||
|
|
||||||
- **SQLite 本地缓存** - 缓存书籍内容和章节数据
|
- **接口缓存** - 命中直接返回,不打上游(Redis 启用时优先走 Redis)
|
||||||
- **自动清理** - 定期清理过期缓存
|
- **自动清理** - 定期清理过期缓存(Redis 由 TTL 自动过期)
|
||||||
- **数据库压缩** - 支持 VACUUM 操作优化数据库
|
- **数据库压缩** - 支持 VACUUM 操作优化数据库
|
||||||
|
|
||||||
|
| 接口 | 缓存时长 |
|
||||||
|
| ------ | ------ |
|
||||||
|
| `/content` | 24 小时 |
|
||||||
|
| `/detail`、`/info`、`/catalog`、`/multi-detail`、`/item-summary` | 24 小时 |
|
||||||
|
| `/search`、`/category-front`、`/category-landing` | 10 分钟 |
|
||||||
|
| `/audio` 代理链接 | 2 小时(匹配 CDN 有效期) |
|
||||||
|
|
||||||
|
失败响应不缓存;评论类接口为动态数据,不缓存。
|
||||||
|
|
||||||
## 技术栈
|
## 技术栈
|
||||||
|
|
||||||
- **Go 1.24** - 编程语言
|
- **Go 1.24** - 编程语言
|
||||||
- **Gin** - HTTP 框架(间接依赖)
|
- **net/http** - 标准库 HTTP 服务(超时保护 + 优雅退出)
|
||||||
- **SQLite3** - 本地数据库
|
- **SQLite3 / PostgreSQL / Redis** - 缓存与存储
|
||||||
- **Viper** - 配置管理
|
- **Viper** - 配置管理
|
||||||
- **goquery** - HTML 解析
|
- **goquery** - HTML 解析
|
||||||
|
|
||||||
|
|||||||
+31
-28
@@ -40,10 +40,10 @@ func main() {
|
|||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
defer fqapi.CloseRedis()
|
defer fqapi.CloseRedis()
|
||||||
|
|
||||||
// 加载统计数据
|
// 加载统计数据
|
||||||
handlers.LoadStatistics()
|
handlers.LoadStatistics()
|
||||||
|
|
||||||
// 启动统计数据定期保存
|
// 启动统计数据定期保存
|
||||||
handlers.StartStatisticsSaver()
|
handlers.StartStatisticsSaver()
|
||||||
defer handlers.StopStatisticsSaver() // 程序退出时保存统计数据
|
defer handlers.StopStatisticsSaver() // 程序退出时保存统计数据
|
||||||
@@ -99,9 +99,9 @@ func initAlgorithm() {
|
|||||||
if config.GetAppConfig() != nil {
|
if config.GetAppConfig() != nil {
|
||||||
algos.GlobalAlgorithmSwitcher.SwitchAlgorithm(config.GetAppConfig().Fanqie.Algorithm)
|
algos.GlobalAlgorithmSwitcher.SwitchAlgorithm(config.GetAppConfig().Fanqie.Algorithm)
|
||||||
logger.Info(fmt.Sprintf("当前算法: %s", config.GetAppConfig().Fanqie.Algorithm))
|
logger.Info(fmt.Sprintf("当前算法: %s", config.GetAppConfig().Fanqie.Algorithm))
|
||||||
|
|
||||||
algos.GlobalSignatureSwitcher.SwitchSignature(config.GetAppConfig().Fanqie.Signature)
|
algos.GlobalSignatureSwitcher.SwitchSignature(config.GetAppConfig().Fanqie.Signature)
|
||||||
|
|
||||||
// 根据签名方法显示详细信息
|
// 根据签名方法显示详细信息
|
||||||
var signatureDetails string
|
var signatureDetails string
|
||||||
if config.GetAppConfig().Fanqie.Signature == "sign4" {
|
if config.GetAppConfig().Fanqie.Signature == "sign4" {
|
||||||
@@ -121,7 +121,7 @@ func initDeviceKeyPool() error {
|
|||||||
pool := fqapi.GetDeviceKeyPool()
|
pool := fqapi.GetDeviceKeyPool()
|
||||||
if err := pool.Initialize(); err != nil {
|
if err := pool.Initialize(); err != nil {
|
||||||
return fmt.Errorf("初始化设备密钥池失败: %w", err)
|
return fmt.Errorf("初始化设备密钥池失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 显示池状态
|
// 显示池状态
|
||||||
stats := pool.GetStats()
|
stats := pool.GetStats()
|
||||||
@@ -140,29 +140,32 @@ func setupRoutes() {
|
|||||||
|
|
||||||
http.HandleFunc("/healthz", handlers.HandleHealth)
|
http.HandleFunc("/healthz", handlers.HandleHealth)
|
||||||
|
|
||||||
// API端点(protect_all 开启时要求访问密钥;代理路由不包,URL 由服务端生成不含 key)
|
// API端点:限流 + protect_all 鉴权链(代理路由不鉴权,URL 由服务端生成不含 key)
|
||||||
http.HandleFunc("/search", handlers.OptionalAccessKey(handlers.HandleSearch))
|
wrap := func(h http.HandlerFunc) http.HandlerFunc {
|
||||||
http.HandleFunc("/detail", handlers.OptionalAccessKey(handlers.HandleDetail))
|
return handlers.RateLimit(handlers.OptionalAccessKey(h))
|
||||||
http.HandleFunc("/info", handlers.OptionalAccessKey(handlers.HandleDetail))
|
}
|
||||||
http.HandleFunc("/catalog", handlers.OptionalAccessKey(handlers.HandleCatalog))
|
http.HandleFunc("/search", wrap(handlers.HandleSearch))
|
||||||
http.HandleFunc("/directory/all_items", handlers.OptionalAccessKey(handlers.HandleCatalog))
|
http.HandleFunc("/detail", wrap(handlers.HandleDetail))
|
||||||
http.HandleFunc("/multi-detail", handlers.OptionalAccessKey(handlers.HandleMultiDetail))
|
http.HandleFunc("/info", wrap(handlers.HandleDetail))
|
||||||
http.HandleFunc("/multi-content", handlers.OptionalAccessKey(handlers.HandleMultiContent))
|
http.HandleFunc("/catalog", wrap(handlers.HandleCatalog))
|
||||||
http.HandleFunc("/content", handlers.OptionalAccessKey(handlers.HandleContent))
|
http.HandleFunc("/directory/all_items", wrap(handlers.HandleCatalog))
|
||||||
http.HandleFunc("/item-summary", handlers.OptionalAccessKey(handlers.HandleItemSummary))
|
http.HandleFunc("/multi-detail", wrap(handlers.HandleMultiDetail))
|
||||||
http.HandleFunc("/category-front", handlers.OptionalAccessKey(handlers.HandleCategoryFront))
|
http.HandleFunc("/multi-content", wrap(handlers.HandleMultiContent))
|
||||||
http.HandleFunc("/category-landing", handlers.OptionalAccessKey(handlers.HandleCategoryLanding))
|
http.HandleFunc("/content", wrap(handlers.HandleContent))
|
||||||
http.HandleFunc("/audio", handlers.OptionalAccessKey(handlers.HandleAudio))
|
http.HandleFunc("/item-summary", wrap(handlers.HandleItemSummary))
|
||||||
http.HandleFunc("/audio/proxy/", handlers.HandleAudioProxy)
|
http.HandleFunc("/category-front", wrap(handlers.HandleCategoryFront))
|
||||||
http.HandleFunc("/video", handlers.OptionalAccessKey(handlers.HandleVideo))
|
http.HandleFunc("/category-landing", wrap(handlers.HandleCategoryLanding))
|
||||||
http.HandleFunc("/manga", handlers.OptionalAccessKey(handlers.HandleManga))
|
http.HandleFunc("/audio", wrap(handlers.HandleAudio))
|
||||||
http.HandleFunc("/manga/image/", handlers.HandleMangaImageProxy)
|
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("/chapter_review", wrap(handlers.HandleChapterReview))
|
||||||
http.HandleFunc("/review", handlers.OptionalAccessKey(handlers.HandleReview))
|
http.HandleFunc("/review", wrap(handlers.HandleReview))
|
||||||
http.HandleFunc("/review_html", handlers.OptionalAccessKey(handlers.HandleReviewHTML))
|
http.HandleFunc("/review_html", wrap(handlers.HandleReviewHTML))
|
||||||
|
|
||||||
// 表情图片静态文件服务
|
// 表情图片静态文件服务
|
||||||
http.Handle("/emoji/", http.StripPrefix("/emoji/", http.FileServer(http.Dir("emoji"))))
|
http.Handle("/emoji/", http.StripPrefix("/emoji/", http.FileServer(http.Dir("emoji"))))
|
||||||
}
|
}
|
||||||
@@ -171,7 +174,7 @@ func setupRoutes() {
|
|||||||
func startServer() {
|
func startServer() {
|
||||||
host := "0.0.0.0"
|
host := "0.0.0.0"
|
||||||
port := "40180"
|
port := "40180"
|
||||||
|
|
||||||
if config.GetAppConfig() != nil {
|
if config.GetAppConfig() != nil {
|
||||||
if config.GetAppConfig().Server.Host != "" {
|
if config.GetAppConfig().Server.Host != "" {
|
||||||
host = config.GetAppConfig().Server.Host
|
host = config.GetAppConfig().Server.Host
|
||||||
@@ -180,7 +183,7 @@ func startServer() {
|
|||||||
port = config.GetAppConfig().Server.Port
|
port = config.GetAppConfig().Server.Port
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
addr := host + ":" + port
|
addr := host + ":" + port
|
||||||
server := &http.Server{
|
server := &http.Server{
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ require (
|
|||||||
github.com/mattn/go-sqlite3 v1.14.18
|
github.com/mattn/go-sqlite3 v1.14.18
|
||||||
github.com/redis/go-redis/v9 v9.22.0
|
github.com/redis/go-redis/v9 v9.22.0
|
||||||
github.com/spf13/viper v1.18.2
|
github.com/spf13/viper v1.18.2
|
||||||
|
golang.org/x/time v0.5.0
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
|||||||
@@ -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.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 h1:yznKA/E9zq54KzlzBEAWn1NXSQ8DIp/NYMy88xJjl4k=
|
||||||
golang.org/x/text v0.30.0/go.mod h1:yDdHFIX9t+tORqspjENWgzaCVXgk0yYnYuSZ8UzzBVM=
|
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-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.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||||
|
|||||||
@@ -19,10 +19,11 @@ type Config struct {
|
|||||||
|
|
||||||
// ServerConfig 服务器配置
|
// ServerConfig 服务器配置
|
||||||
type ServerConfig struct {
|
type ServerConfig struct {
|
||||||
Port string `mapstructure:"port"`
|
Port string `mapstructure:"port"`
|
||||||
Host string `mapstructure:"host"`
|
Host string `mapstructure:"host"`
|
||||||
AccessKey string `mapstructure:"access_key"`
|
AccessKey string `mapstructure:"access_key"`
|
||||||
ProtectAll bool `mapstructure:"protect_all"` // 业务接口也要求访问密钥(公网部署建议开启)
|
ProtectAll bool `mapstructure:"protect_all"` // 业务接口也要求访问密钥(公网部署建议开启)
|
||||||
|
RateLimitQPS float64 `mapstructure:"rate_limit_qps"` // 每 IP 每秒请求上限,0=不限制
|
||||||
}
|
}
|
||||||
|
|
||||||
// FanqieConfig 番茄小说配置
|
// FanqieConfig 番茄小说配置
|
||||||
|
|||||||
@@ -132,4 +132,3 @@ func HandleAudio(itemIDs interface{}, toneID interface{}, output interface{}) (s
|
|||||||
audioLogger.Error(fmt.Sprintf("获取音频失败: code=%v, msg=%s", respCode, errMsg))
|
audioLogger.Error(fmt.Sprintf("获取音频失败: code=%v, msg=%s", respCode, errMsg))
|
||||||
return BuildErrorResponse(errMsg), nil
|
return BuildErrorResponse(errMsg), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4,15 +4,16 @@ import (
|
|||||||
"database/sql"
|
"database/sql"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// AudioCacheItem 音频缓存项
|
// AudioCacheItem 音频缓存项
|
||||||
type AudioCacheItem struct {
|
type AudioCacheItem struct {
|
||||||
OriginalURL string `json:"original_url"` // 原始CDN URL
|
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"` // 请求头信息
|
Headers map[string]string `json:"headers"` // 请求头信息
|
||||||
CachedAt time.Time `json:"cached_at"` // 缓存时间
|
CachedAt time.Time `json:"cached_at"` // 缓存时间
|
||||||
}
|
}
|
||||||
|
|
||||||
// GenerateAudioProxyURL 生成音频代理URL
|
// GenerateAudioProxyURL 生成音频代理URL
|
||||||
@@ -49,8 +50,8 @@ func GenerateAudioProxyURL(originalURL, deviceID string, headers map[string]stri
|
|||||||
return fmt.Sprintf("/audio/proxy/%s", key)
|
return fmt.Sprintf("/audio/proxy/%s", key)
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleAudioProxy 处理音频代理请求
|
// HandleAudioProxy 处理音频代理请求(流式返回,调用方负责 Close)
|
||||||
func HandleAudioProxy(key string) ([]byte, string, error) {
|
func HandleAudioProxy(key string) (io.ReadCloser, string, error) {
|
||||||
var originalURL, deviceID string
|
var originalURL, deviceID string
|
||||||
var headers map[string]string
|
var headers map[string]string
|
||||||
|
|
||||||
@@ -95,13 +96,13 @@ func HandleAudioProxy(key string) ([]byte, string, error) {
|
|||||||
headers = make(map[string]string)
|
headers = make(map[string]string)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 下载音频内容,使用关联的设备信息
|
// 下载音频内容(流式),使用关联的设备信息
|
||||||
data, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 3)
|
body, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 3)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", fmt.Errorf("下载音频失败: %w", err)
|
return nil, "", fmt.Errorf("下载音频失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
return data, contentType, nil
|
return body, contentType, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CleanExpiredAudioCache 清理过期的音频缓存
|
// CleanExpiredAudioCache 清理过期的音频缓存
|
||||||
|
|||||||
@@ -379,7 +379,7 @@ func CleanupAllCache() error {
|
|||||||
freeBytes := freelistCount * pageSize
|
freeBytes := freelistCount * pageSize
|
||||||
// 阈值:空闲空间超过 5MB 时才执行压缩
|
// 阈值:空闲空间超过 5MB 时才执行压缩
|
||||||
const vacuumThreshold = 5 * 1024 * 1024 // 5MB
|
const vacuumThreshold = 5 * 1024 * 1024 // 5MB
|
||||||
|
|
||||||
if freeBytes >= vacuumThreshold {
|
if freeBytes >= vacuumThreshold {
|
||||||
cacheLogger.Info(fmt.Sprintf("空闲空间 %.2f MB,开始执行压缩...", float64(freeBytes)/(1024*1024)))
|
cacheLogger.Info(fmt.Sprintf("空闲空间 %.2f MB,开始执行压缩...", float64(freeBytes)/(1024*1024)))
|
||||||
_, err = cacheDB.Exec("VACUUM")
|
_, err = cacheDB.Exec("VACUUM")
|
||||||
@@ -550,7 +550,7 @@ func GetDatabaseStats() (map[string]interface{}, error) {
|
|||||||
if err == nil {
|
if err == nil {
|
||||||
stats["page_count"] = pageCount
|
stats["page_count"] = pageCount
|
||||||
}
|
}
|
||||||
|
|
||||||
err = cacheDB.QueryRow("PRAGMA page_size").Scan(&pageSize)
|
err = cacheDB.QueryRow("PRAGMA page_size").Scan(&pageSize)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
stats["page_size"] = pageSize
|
stats["page_size"] = pageSize
|
||||||
@@ -589,7 +589,7 @@ func SaveStatistics(stats map[string]int64) error {
|
|||||||
`), stats["total"], stats["search"], stats["detail"], stats["catalog"],
|
`), stats["total"], stats["search"], stats["detail"], stats["catalog"],
|
||||||
stats["content"], stats["manga"], stats["audio"], stats["video"], stats["category"],
|
stats["content"], stats["manga"], stats["audio"], stats["video"], stats["category"],
|
||||||
time.Now().Unix())
|
time.Now().Unix())
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
cacheLogger.Error("保存统计数据失败: " + err.Error())
|
cacheLogger.Error("保存统计数据失败: " + err.Error())
|
||||||
return err
|
return err
|
||||||
@@ -605,13 +605,13 @@ func LoadStatistics() (map[string]int64, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var total, search, detail, catalog, content, manga, audio, video, category int64
|
var total, search, detail, catalog, content, manga, audio, video, category int64
|
||||||
|
|
||||||
err := cacheDB.QueryRow(`
|
err := cacheDB.QueryRow(`
|
||||||
SELECT total_requests, search_requests, detail_requests, catalog_requests,
|
SELECT total_requests, search_requests, detail_requests, catalog_requests,
|
||||||
content_requests, manga_requests, audio_requests, video_requests, category_requests
|
content_requests, manga_requests, audio_requests, video_requests, category_requests
|
||||||
FROM statistics WHERE id = 1
|
FROM statistics WHERE id = 1
|
||||||
`).Scan(&total, &search, &detail, &catalog, &content, &manga, &audio, &video, &category)
|
`).Scan(&total, &search, &detail, &catalog, &content, &manga, &audio, &video, &category)
|
||||||
|
|
||||||
if err == sql.ErrNoRows {
|
if err == sql.ErrNoRows {
|
||||||
// 没有数据,返回空统计
|
// 没有数据,返回空统计
|
||||||
return map[string]int64{
|
return map[string]int64{
|
||||||
@@ -619,7 +619,7 @@ func LoadStatistics() (map[string]int64, error) {
|
|||||||
"content": 0, "manga": 0, "audio": 0, "video": 0, "category": 0,
|
"content": 0, "manga": 0, "audio": 0, "video": 0, "category": 0,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
cacheLogger.Error("加载统计数据失败: " + err.Error())
|
cacheLogger.Error("加载统计数据失败: " + err.Error())
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -638,4 +638,4 @@ func LoadStatistics() (map[string]int64, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return stats, nil
|
return stats, nil
|
||||||
}
|
}
|
||||||
@@ -12,7 +12,7 @@ var catalogLogger = common.NewLogger("catalog", "INFO", "")
|
|||||||
|
|
||||||
// HandleGetCatalog 处理获取书籍目录,目录数据基本不变,缓存 24 小时
|
// HandleGetCatalog 处理获取书籍目录,目录数据基本不变,缓存 24 小时
|
||||||
func HandleGetCatalog(bookID string) (string, error) {
|
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)
|
return fetchCatalog(bookID)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -210,4 +210,3 @@ func itemMultiDetail(itemList []string) ([]map[string]interface{}, error) {
|
|||||||
|
|
||||||
return nil, fmt.Errorf("请求失败")
|
return nil, fmt.Errorf("请求失败")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,4 +47,3 @@ func fetchCategoryFront(tab interface{}) (string, error) {
|
|||||||
|
|
||||||
return BuildErrorResponse("获取失败"), nil
|
return BuildErrorResponse("获取失败"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -59,4 +59,3 @@ func fetchCategoryLanding(categoryID, offset, wordNumber, bookStatus, sortBy int
|
|||||||
|
|
||||||
return BuildErrorResponse("获取失败"), nil
|
return BuildErrorResponse("获取失败"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +66,7 @@ func fetchContentWithRetry(itemID string, textMode, imageMode bool, retryCount i
|
|||||||
contentLogger.Warning(fmt.Sprintf("已重试 %d 次,尝试备用接口", maxRetries))
|
contentLogger.Warning(fmt.Sprintf("已重试 %d 次,尝试备用接口", maxRetries))
|
||||||
return tryBackupAPI(itemID, textMode, imageMode)
|
return tryBackupAPI(itemID, textMode, imageMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从设备密钥池获取设备
|
// 从设备密钥池获取设备
|
||||||
pool := GetDeviceKeyPool()
|
pool := GetDeviceKeyPool()
|
||||||
item, err := pool.GetNext()
|
item, err := pool.GetNext()
|
||||||
@@ -74,7 +74,7 @@ func fetchContentWithRetry(itemID string, textMode, imageMode bool, retryCount i
|
|||||||
contentLogger.Error("从设备池获取设备失败: " + err.Error())
|
contentLogger.Error("从设备池获取设备失败: " + err.Error())
|
||||||
return `{"code": -1, "msg": "设备池暂无可用设备"}`, err
|
return `{"code": -1, "msg": "设备池暂无可用设备"}`, err
|
||||||
}
|
}
|
||||||
|
|
||||||
header := item.DeviceHeader
|
header := item.DeviceHeader
|
||||||
currentKeyInfo := &KeyInfo{
|
currentKeyInfo := &KeyInfo{
|
||||||
Key: item.Key,
|
Key: item.Key,
|
||||||
@@ -142,7 +142,7 @@ func fetchContentWithRetry(itemID string, textMode, imageMode bool, retryCount i
|
|||||||
keyVersion, _ := data["key_version"].(float64)
|
keyVersion, _ := data["key_version"].(float64)
|
||||||
if currentKeyInfo != nil && int(keyVersion) != currentKeyInfo.Ver {
|
if currentKeyInfo != nil && int(keyVersion) != currentKeyInfo.Ver {
|
||||||
contentLogger.Warning("密钥版本不匹配,重新获取密钥")
|
contentLogger.Warning("密钥版本不匹配,重新获取密钥")
|
||||||
|
|
||||||
// 更新池中的密钥
|
// 更新池中的密钥
|
||||||
newKeyInfo, err := GetKey(header)
|
newKeyInfo, err := GetKey(header)
|
||||||
if err == nil {
|
if err == nil {
|
||||||
@@ -276,4 +276,3 @@ func tryBackupAPI(itemID string, textMode, imageMode bool) (string, error) {
|
|||||||
contentLogger.Warning("备用接口1获取正文出错!")
|
contentLogger.Warning("备用接口1获取正文出错!")
|
||||||
return `{"code": -1, "msg": "获取失败"}`, fmt.Errorf("所有接口都失败")
|
return `{"code": -1, "msg": "获取失败"}`, fmt.Errorf("所有接口都失败")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13,7 +13,6 @@ var (
|
|||||||
parserLogger = common.NewLogger("content_parser", "INFO", "")
|
parserLogger = common.NewLogger("content_parser", "INFO", "")
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
// ContentParser 内容解析器
|
// ContentParser 内容解析器
|
||||||
type ContentParser struct {
|
type ContentParser struct {
|
||||||
cfg config.ContentConfig
|
cfg config.ContentConfig
|
||||||
@@ -143,13 +142,13 @@ func (p *ContentParser) extractText(content string) string {
|
|||||||
|
|
||||||
// 拼接结果
|
// 拼接结果
|
||||||
var result string
|
var result string
|
||||||
|
|
||||||
// 根据配置决定段落间的换行符
|
// 根据配置决定段落间的换行符
|
||||||
separator := "\n"
|
separator := "\n"
|
||||||
if p.cfg.DoubleNewline {
|
if p.cfg.DoubleNewline {
|
||||||
separator = "\n\n"
|
separator = "\n\n"
|
||||||
}
|
}
|
||||||
|
|
||||||
if p.cfg.AddParagraphIndent && len(finalResult) > 0 {
|
if p.cfg.AddParagraphIndent && len(finalResult) > 0 {
|
||||||
// 添加段落缩进(两个全角空格)
|
// 添加段落缩进(两个全角空格)
|
||||||
result = "\u3000\u3000" + strings.Join(finalResult, separator+"\u3000\u3000")
|
result = "\u3000\u3000" + strings.Join(finalResult, separator+"\u3000\u3000")
|
||||||
@@ -170,10 +169,10 @@ func (p *ContentParser) extractText(content string) string {
|
|||||||
func (p *ContentParser) processHTMLMode(content string) string {
|
func (p *ContentParser) processHTMLMode(content string) string {
|
||||||
// 标准化img属性
|
// 标准化img属性
|
||||||
content = normalizeImgAttributes(content)
|
content = normalizeImgAttributes(content)
|
||||||
|
|
||||||
// 解码HTML实体
|
// 解码HTML实体
|
||||||
content = decodeHTMLEntities(content)
|
content = decodeHTMLEntities(content)
|
||||||
|
|
||||||
// 根据配置决定是否移除空行
|
// 根据配置决定是否移除空行
|
||||||
if p.cfg.RemoveBlankLines {
|
if p.cfg.RemoveBlankLines {
|
||||||
// 对HTML内容移除空的<p>标签
|
// 对HTML内容移除空的<p>标签
|
||||||
@@ -184,4 +183,3 @@ func (p *ContentParser) processHTMLMode(content string) string {
|
|||||||
|
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,10 +57,10 @@ func removeBlankLines(content string) string {
|
|||||||
for strings.Contains(content, "\n\n\n") {
|
for strings.Contains(content, "\n\n\n") {
|
||||||
content = strings.ReplaceAll(content, "\n\n\n", "\n\n")
|
content = strings.ReplaceAll(content, "\n\n\n", "\n\n")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 移除首尾的空白
|
// 移除首尾的空白
|
||||||
content = strings.TrimSpace(content)
|
content = strings.TrimSpace(content)
|
||||||
|
|
||||||
return content
|
return content
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,22 +127,22 @@ func BuildURL(fullURL string, customParams ...string) string {
|
|||||||
"os_version=0",
|
"os_version=0",
|
||||||
"version_code=58932",
|
"version_code=58932",
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加设备header
|
// 添加设备header
|
||||||
header := getDeviceHeader()
|
header := getDeviceHeader()
|
||||||
if header != "" {
|
if header != "" {
|
||||||
allParams = append(allParams, header)
|
allParams = append(allParams, header)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 添加自定义参数
|
// 添加自定义参数
|
||||||
allParams = append(allParams, customParams...)
|
allParams = append(allParams, customParams...)
|
||||||
|
|
||||||
// 合并、拆分、排序
|
// 合并、拆分、排序
|
||||||
joined := strings.Join(allParams, "&")
|
joined := strings.Join(allParams, "&")
|
||||||
paramList := strings.Split(joined, "&")
|
paramList := strings.Split(joined, "&")
|
||||||
sort.Strings(paramList)
|
sort.Strings(paramList)
|
||||||
params := strings.Join(paramList, "&")
|
params := strings.Join(paramList, "&")
|
||||||
|
|
||||||
return fullURL + "?" + params
|
return fullURL + "?" + params
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,11 +218,11 @@ func parseStringToInt(s string) (int, error) {
|
|||||||
// 简单实现,避免导入strconv
|
// 简单实现,避免导入strconv
|
||||||
result := 0
|
result := 0
|
||||||
negative := false
|
negative := false
|
||||||
|
|
||||||
if len(s) == 0 {
|
if len(s) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
start := 0
|
start := 0
|
||||||
if s[0] == '-' {
|
if s[0] == '-' {
|
||||||
negative = true
|
negative = true
|
||||||
@@ -230,18 +230,18 @@ func parseStringToInt(s string) (int, error) {
|
|||||||
} else if s[0] == '+' {
|
} else if s[0] == '+' {
|
||||||
start = 1
|
start = 1
|
||||||
}
|
}
|
||||||
|
|
||||||
for i := start; i < len(s); i++ {
|
for i := start; i < len(s); i++ {
|
||||||
if s[i] < '0' || s[i] > '9' {
|
if s[i] < '0' || s[i] > '9' {
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
result = result*10 + int(s[i]-'0')
|
result = result*10 + int(s[i]-'0')
|
||||||
}
|
}
|
||||||
|
|
||||||
if negative {
|
if negative {
|
||||||
result = -result
|
result = -result
|
||||||
}
|
}
|
||||||
|
|
||||||
return result, nil
|
return result, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,7 +250,7 @@ func ParseStringParam(param interface{}, defaultVal string) string {
|
|||||||
if param == nil || param == "" {
|
if param == nil || param == "" {
|
||||||
return defaultVal
|
return defaultVal
|
||||||
}
|
}
|
||||||
|
|
||||||
switch v := param.(type) {
|
switch v := param.(type) {
|
||||||
case string:
|
case string:
|
||||||
if v != "" {
|
if v != "" {
|
||||||
@@ -262,4 +262,3 @@ func ParseStringParam(param interface{}, defaultVal string) string {
|
|||||||
}
|
}
|
||||||
return defaultVal
|
return defaultVal
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ var detailLogger = common.NewLogger("detail", "INFO", "")
|
|||||||
|
|
||||||
// HandleGetDetail 处理获取书籍详情,详情数据基本不变,缓存 24 小时
|
// HandleGetDetail 处理获取书籍详情,详情数据基本不变,缓存 24 小时
|
||||||
func HandleGetDetail(bookID string) (string, error) {
|
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)
|
return fetchDetail(bookID)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -58,4 +58,3 @@ func fetchDetail(bookID string) (string, error) {
|
|||||||
|
|
||||||
return BuildErrorResponse("获取失败"), nil
|
return BuildErrorResponse("获取失败"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
+543
-547
File diff suppressed because it is too large.
Load diff
@@ -40,7 +40,7 @@ func currentMillis() int64 {
|
|||||||
// custom_bt = current_millis - elapsed_ms_since_boot
|
// custom_bt = current_millis - elapsed_ms_since_boot
|
||||||
func getCustomBT() string {
|
func getCustomBT() string {
|
||||||
var uptimeSeconds float64
|
var uptimeSeconds float64
|
||||||
|
|
||||||
if runtime.GOOS == "linux" {
|
if runtime.GOOS == "linux" {
|
||||||
// 在Linux上读取/proc/uptime
|
// 在Linux上读取/proc/uptime
|
||||||
data, err := os.ReadFile("/proc/uptime")
|
data, err := os.ReadFile("/proc/uptime")
|
||||||
@@ -54,7 +54,7 @@ func getCustomBT() string {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果读取失败,使用time.monotonic作为备选
|
// 如果读取失败,使用time.monotonic作为备选
|
||||||
if uptimeSeconds == 0 {
|
if uptimeSeconds == 0 {
|
||||||
// Go没有直接的monotonic API,使用启动时间估算
|
// Go没有直接的monotonic API,使用启动时间估算
|
||||||
@@ -65,17 +65,17 @@ func getCustomBT() string {
|
|||||||
// 这里可以使用进程启动时间作为近似
|
// 这里可以使用进程启动时间作为近似
|
||||||
uptimeSeconds = float64(time.Now().Unix() % 86400)
|
uptimeSeconds = float64(time.Now().Unix() % 86400)
|
||||||
}
|
}
|
||||||
|
|
||||||
return fmt.Sprintf("%d", currentMillis()-int64(uptimeSeconds*1000))
|
return fmt.Sprintf("%d", currentMillis()-int64(uptimeSeconds*1000))
|
||||||
}
|
}
|
||||||
|
|
||||||
// generateDeviceInfo 随机生成设备及操作系统信息
|
// generateDeviceInfo 随机生成设备及操作系统信息
|
||||||
func generateDeviceInfo() map[string]interface{} {
|
func generateDeviceInfo() map[string]interface{} {
|
||||||
osVersion := androidVersions[randInt(len(androidVersions))]
|
osVersion := androidVersions[randInt(len(androidVersions))]
|
||||||
|
|
||||||
// 随机选择品牌
|
// 随机选择品牌
|
||||||
deviceBrand := deviceBrands[randInt(len(deviceBrands))]
|
deviceBrand := deviceBrands[randInt(len(deviceBrands))]
|
||||||
|
|
||||||
// 根据品牌选择对应的型号
|
// 根据品牌选择对应的型号
|
||||||
models := brandModels[deviceBrand]
|
models := brandModels[deviceBrand]
|
||||||
deviceModel := models[randInt(len(models))]
|
deviceModel := models[randInt(len(models))]
|
||||||
@@ -88,19 +88,19 @@ func generateDeviceInfo() map[string]interface{} {
|
|||||||
rand.Read(openUDIDBytes)
|
rand.Read(openUDIDBytes)
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"os": "Android",
|
"os": "Android",
|
||||||
"os_version": osVersion[0],
|
"os_version": osVersion[0],
|
||||||
"os_api": osVersion[1],
|
"os_api": osVersion[1],
|
||||||
"device_model": deviceModel,
|
"device_model": deviceModel,
|
||||||
"device_brand": deviceBrand,
|
"device_brand": deviceBrand,
|
||||||
"device_manufacturer": deviceBrand,
|
"device_manufacturer": deviceBrand,
|
||||||
"cpu_abi": "arm64-v8a",
|
"cpu_abi": "arm64-v8a",
|
||||||
"release_build": releaseBuild,
|
"release_build": releaseBuild,
|
||||||
"cdid": generateUUID(),
|
"cdid": generateUUID(),
|
||||||
"sig_hash": "a4a27c2633195374c15651ffc3c4a497",
|
"sig_hash": "a4a27c2633195374c15651ffc3c4a497",
|
||||||
"openudid": hex.EncodeToString(openUDIDBytes),
|
"openudid": hex.EncodeToString(openUDIDBytes),
|
||||||
"clientudid": generateUUID(),
|
"clientudid": generateUUID(),
|
||||||
"req_id": generateUUID(),
|
"req_id": generateUUID(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -130,9 +130,9 @@ func generateOptionalFields() (map[string]interface{}, map[string]int64) {
|
|||||||
|
|
||||||
genTime := currentMillis()
|
genTime := currentMillis()
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"rom": rom,
|
"rom": rom,
|
||||||
"rom_version": fmt.Sprintf("coloros__%s.%s.%s release-keys", part1, part2, part3),
|
"rom_version": fmt.Sprintf("coloros__%s.%s.%s release-keys", part1, part2, part3),
|
||||||
"apk_first_install_time": genTime - int64(randInt(365))*86400000,
|
"apk_first_install_time": genTime - int64(randInt(365))*86400000,
|
||||||
}, map[string]int64{
|
}, map[string]int64{
|
||||||
"_gen_time": genTime,
|
"_gen_time": genTime,
|
||||||
}
|
}
|
||||||
@@ -307,7 +307,7 @@ func Register() (string, error) {
|
|||||||
|
|
||||||
// 生成完整请求体数据
|
// 生成完整请求体数据
|
||||||
data := GenerateFullRequestBody()
|
data := GenerateFullRequestBody()
|
||||||
|
|
||||||
// 只记录关键设备信息
|
// 只记录关键设备信息
|
||||||
header := data["header"].(map[string]interface{})
|
header := data["header"].(map[string]interface{})
|
||||||
logger.Info(fmt.Sprintf("生成设备信息 - 品牌: %s, 型号: %s, 系统: Android %v",
|
logger.Info(fmt.Sprintf("生成设备信息 - 品牌: %s, 型号: %s, 系统: Android %v",
|
||||||
@@ -370,7 +370,7 @@ func Register() (string, error) {
|
|||||||
deviceModel,
|
deviceModel,
|
||||||
respData["install_id_str"])
|
respData["install_id_str"])
|
||||||
|
|
||||||
logger.Info("设备注册成功!" )
|
logger.Info("设备注册成功!")
|
||||||
|
|
||||||
// 尝试激活特权
|
// 尝试激活特权
|
||||||
tryActivatePremium(header)
|
tryActivatePremium(header)
|
||||||
@@ -381,4 +381,3 @@ func Register() (string, error) {
|
|||||||
logger.Warning("设备注册失败!")
|
logger.Warning("设备注册失败!")
|
||||||
return "", fmt.Errorf("设备注册失败")
|
return "", fmt.Errorf("设备注册失败")
|
||||||
}
|
}
|
||||||
|
|
||||||
+184
-185
@@ -1,185 +1,184 @@
|
|||||||
package fqapi
|
package fqapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/aes"
|
"crypto/aes"
|
||||||
"crypto/cipher"
|
"crypto/cipher"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"fmt"
|
"fmt"
|
||||||
"math/big"
|
"math/big"
|
||||||
)
|
)
|
||||||
|
|
||||||
// CM 加密管理器
|
// CM 加密管理器
|
||||||
type CM struct {
|
type CM struct {
|
||||||
bigC *big.Int // 大素数C
|
bigC *big.Int // 大素数C
|
||||||
bigB int64 // 底数B
|
bigB int64 // 底数B
|
||||||
arryD []byte // 固定密钥
|
arryD []byte // 固定密钥
|
||||||
thisD [2]*big.Int // 密钥对(私钥, 公钥)
|
thisD [2]*big.Int // 密钥对(私钥, 公钥)
|
||||||
thisC []byte // 随机IV
|
thisC []byte // 随机IV
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewCM 创建新的CM实例
|
// NewCM 创建新的CM实例
|
||||||
func NewCM() *CM {
|
func NewCM() *CM {
|
||||||
// 大素数C
|
// 大素数C
|
||||||
bigCStr := "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"
|
bigCStr := "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"
|
||||||
bigC := new(big.Int)
|
bigC := new(big.Int)
|
||||||
bigC.SetString(bigCStr, 10)
|
bigC.SetString(bigCStr, 10)
|
||||||
|
|
||||||
// 固定密钥(base64解码)
|
// 固定密钥(base64解码)
|
||||||
arryD, _ := base64.StdEncoding.DecodeString("rCXGfd2POMGzeiNIgo4iLg==")
|
arryD, _ := base64.StdEncoding.DecodeString("rCXGfd2POMGzeiNIgo4iLg==")
|
||||||
|
|
||||||
return &CM{
|
return &CM{
|
||||||
bigC: bigC,
|
bigC: bigC,
|
||||||
bigB: 2,
|
bigB: 2,
|
||||||
arryD: arryD,
|
arryD: arryD,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// generateKeyPair 生成密钥对
|
// generateKeyPair 生成密钥对
|
||||||
func (cm *CM) generateKeyPair() [2]*big.Int {
|
func (cm *CM) generateKeyPair() [2]*big.Int {
|
||||||
// 生成随机私钥
|
// 生成随机私钥
|
||||||
randomBytes := make([]byte, 32)
|
randomBytes := make([]byte, 32)
|
||||||
rand.Read(randomBytes)
|
rand.Read(randomBytes)
|
||||||
|
|
||||||
x := new(big.Int).SetBytes(randomBytes)
|
x := new(big.Int).SetBytes(randomBytes)
|
||||||
x = x.Mod(x, new(big.Int).Sub(cm.bigC, big.NewInt(1)))
|
x = x.Mod(x, new(big.Int).Sub(cm.bigC, big.NewInt(1)))
|
||||||
|
|
||||||
// 计算公钥: y = b^x mod c
|
// 计算公钥: y = b^x mod c
|
||||||
y := new(big.Int).Exp(big.NewInt(cm.bigB), x, cm.bigC)
|
y := new(big.Int).Exp(big.NewInt(cm.bigB), x, cm.bigC)
|
||||||
|
|
||||||
cm.thisD = [2]*big.Int{x, y}
|
cm.thisD = [2]*big.Int{x, y}
|
||||||
return cm.thisD
|
return cm.thisD
|
||||||
}
|
}
|
||||||
|
|
||||||
// pairToBytes 将公钥转换为字节数组
|
// pairToBytes 将公钥转换为字节数组
|
||||||
func (cm *CM) pairToBytes(keyPair [2]*big.Int) []byte {
|
func (cm *CM) pairToBytes(keyPair [2]*big.Int) []byte {
|
||||||
return keyPair[1].Bytes()
|
return keyPair[1].Bytes()
|
||||||
}
|
}
|
||||||
|
|
||||||
// randIV 生成随机IV
|
// randIV 生成随机IV
|
||||||
func (cm *CM) randIV() []byte {
|
func (cm *CM) randIV() []byte {
|
||||||
iv := make([]byte, 16)
|
iv := make([]byte, 16)
|
||||||
rand.Read(iv)
|
rand.Read(iv)
|
||||||
return iv
|
return iv
|
||||||
}
|
}
|
||||||
|
|
||||||
// encodeAES AES-CBC加密
|
// encodeAES AES-CBC加密
|
||||||
func (cm *CM) encodeAES(key, iv, data []byte) ([]byte, error) {
|
func (cm *CM) encodeAES(key, iv, data []byte) ([]byte, error) {
|
||||||
block, err := aes.NewCipher(key)
|
block, err := aes.NewCipher(key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// PKCS7填充
|
// PKCS7填充
|
||||||
padding := aes.BlockSize - len(data)%aes.BlockSize
|
padding := aes.BlockSize - len(data)%aes.BlockSize
|
||||||
padText := make([]byte, padding)
|
padText := make([]byte, padding)
|
||||||
for i := range padText {
|
for i := range padText {
|
||||||
padText[i] = byte(padding)
|
padText[i] = byte(padding)
|
||||||
}
|
}
|
||||||
paddedData := append(data, padText...)
|
paddedData := append(data, padText...)
|
||||||
|
|
||||||
ciphertext := make([]byte, len(paddedData))
|
ciphertext := make([]byte, len(paddedData))
|
||||||
mode := cipher.NewCBCEncrypter(block, iv)
|
mode := cipher.NewCBCEncrypter(block, iv)
|
||||||
mode.CryptBlocks(ciphertext, paddedData)
|
mode.CryptBlocks(ciphertext, paddedData)
|
||||||
|
|
||||||
return ciphertext, nil
|
return ciphertext, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// decodeAES AES-CBC解密
|
// decodeAES AES-CBC解密
|
||||||
func (cm *CM) decodeAES(key, iv, data []byte) ([]byte, error) {
|
func (cm *CM) decodeAES(key, iv, data []byte) ([]byte, error) {
|
||||||
block, err := aes.NewCipher(key)
|
block, err := aes.NewCipher(key)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
mode := cipher.NewCBCDecrypter(block, iv)
|
mode := cipher.NewCBCDecrypter(block, iv)
|
||||||
decrypted := make([]byte, len(data))
|
decrypted := make([]byte, len(data))
|
||||||
mode.CryptBlocks(decrypted, data)
|
mode.CryptBlocks(decrypted, data)
|
||||||
|
|
||||||
// 移除PKCS7填充
|
// 移除PKCS7填充
|
||||||
padding := int(decrypted[len(decrypted)-1])
|
padding := int(decrypted[len(decrypted)-1])
|
||||||
if padding > len(decrypted) || padding > aes.BlockSize {
|
if padding > len(decrypted) || padding > aes.BlockSize {
|
||||||
return nil, fmt.Errorf("无效的填充")
|
return nil, fmt.Errorf("无效的填充")
|
||||||
}
|
}
|
||||||
|
|
||||||
return decrypted[:len(decrypted)-padding], nil
|
return decrypted[:len(decrypted)-padding], nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ClientHandshake 客户端握手,生成请求头y
|
// ClientHandshake 客户端握手,生成请求头y
|
||||||
func (cm *CM) ClientHandshake() string {
|
func (cm *CM) ClientHandshake() string {
|
||||||
keyPair := cm.generateKeyPair()
|
keyPair := cm.generateKeyPair()
|
||||||
cm.thisC = cm.randIV()
|
cm.thisC = cm.randIV()
|
||||||
|
|
||||||
publicKeyBytes := cm.pairToBytes(keyPair)
|
publicKeyBytes := cm.pairToBytes(keyPair)
|
||||||
encrypted, _ := cm.encodeAES(cm.arryD, cm.thisC, publicKeyBytes)
|
encrypted, _ := cm.encodeAES(cm.arryD, cm.thisC, publicKeyBytes)
|
||||||
|
|
||||||
combined := append(cm.thisC, encrypted...)
|
combined := append(cm.thisC, encrypted...)
|
||||||
return base64.StdEncoding.EncodeToString(combined)
|
return base64.StdEncoding.EncodeToString(combined)
|
||||||
}
|
}
|
||||||
|
|
||||||
// decryptF 解密函数
|
// decryptF 解密函数
|
||||||
func (cm *CM) decryptF(peerPublicKey []byte, keyPair [2]*big.Int, iv, data []byte) ([]byte, error) {
|
func (cm *CM) decryptF(peerPublicKey []byte, keyPair [2]*big.Int, iv, data []byte) ([]byte, error) {
|
||||||
x := keyPair[0]
|
x := keyPair[0]
|
||||||
|
|
||||||
// 计算共享密钥: shared_secret = peer_public_key^x mod c
|
// 计算共享密钥: shared_secret = peer_public_key^x mod c
|
||||||
peerPubInt := new(big.Int).SetBytes(peerPublicKey)
|
peerPubInt := new(big.Int).SetBytes(peerPublicKey)
|
||||||
sharedSecret := new(big.Int).Exp(peerPubInt, x, cm.bigC)
|
sharedSecret := new(big.Int).Exp(peerPubInt, x, cm.bigC)
|
||||||
|
|
||||||
key := sharedSecret.Bytes()
|
key := sharedSecret.Bytes()
|
||||||
// 确保key长度为32字节
|
// 确保key长度为32字节
|
||||||
if len(key) < 32 {
|
if len(key) < 32 {
|
||||||
// 前面补0
|
// 前面补0
|
||||||
paddedKey := make([]byte, 32)
|
paddedKey := make([]byte, 32)
|
||||||
copy(paddedKey[32-len(key):], key)
|
copy(paddedKey[32-len(key):], key)
|
||||||
key = paddedKey
|
key = paddedKey
|
||||||
} else if len(key) > 32 {
|
} else if len(key) > 32 {
|
||||||
key = key[:32]
|
key = key[:32]
|
||||||
}
|
}
|
||||||
|
|
||||||
return cm.decodeAES(key, iv, data)
|
return cm.decodeAES(key, iv, data)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decrypt 解密响应内容
|
// Decrypt 解密响应内容
|
||||||
func (cm *CM) Decrypt(c, y, content string) (string, error) {
|
func (cm *CM) Decrypt(c, y, content string) (string, error) {
|
||||||
// c 应该为 "1" 表示启用加密
|
// c 应该为 "1" 表示启用加密
|
||||||
// y 是服务器返回的公钥
|
// y 是服务器返回的公钥
|
||||||
// content 是加密的内容
|
// content 是加密的内容
|
||||||
|
|
||||||
if c != "1" || y == "" {
|
if c != "1" || y == "" {
|
||||||
return content, nil
|
return content, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解码content
|
// 解码content
|
||||||
contentDecoded, err := base64.StdEncoding.DecodeString(content)
|
contentDecoded, err := base64.StdEncoding.DecodeString(content)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(contentDecoded) < 16 {
|
if len(contentDecoded) < 16 {
|
||||||
return "", fmt.Errorf("内容太短")
|
return "", fmt.Errorf("内容太短")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 提取IV和数据
|
// 提取IV和数据
|
||||||
iv := contentDecoded[:16]
|
iv := contentDecoded[:16]
|
||||||
data := contentDecoded[16:]
|
data := contentDecoded[16:]
|
||||||
|
|
||||||
// 解码服务器公钥
|
// 解码服务器公钥
|
||||||
peerPublicKey, err := base64.StdEncoding.DecodeString(y)
|
peerPublicKey, err := base64.StdEncoding.DecodeString(y)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查密钥对是否已初始化
|
// 检查密钥对是否已初始化
|
||||||
if cm.thisD[0] == nil {
|
if cm.thisD[0] == nil {
|
||||||
return "", fmt.Errorf("密钥对未初始化")
|
return "", fmt.Errorf("密钥对未初始化")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解密
|
// 解密
|
||||||
decrypted, err := cm.decryptF(peerPublicKey, cm.thisD, iv, data)
|
decrypted, err := cm.decryptF(peerPublicKey, cm.thisD, iv, data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
return string(decrypted), nil
|
return string(decrypted), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
+229
-230
@@ -1,230 +1,229 @@
|
|||||||
package fqapi
|
package fqapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// EmojiManager 表情管理器
|
// EmojiManager 表情管理器
|
||||||
type EmojiManager struct {
|
type EmojiManager struct {
|
||||||
emojiMap map[string]string // 表情文本 -> 图片URL的映射
|
emojiMap map[string]string // 表情文本 -> 图片URL的映射
|
||||||
mutex sync.RWMutex
|
mutex sync.RWMutex
|
||||||
lastUpdate time.Time
|
lastUpdate time.Time
|
||||||
cacheExpiry time.Duration
|
cacheExpiry time.Duration
|
||||||
}
|
}
|
||||||
|
|
||||||
// DouyinEmojiResponse 抖音表情API响应结构
|
// DouyinEmojiResponse 抖音表情API响应结构
|
||||||
type DouyinEmojiResponse struct {
|
type DouyinEmojiResponse struct {
|
||||||
EmojiList []DouyinEmoji `json:"emoji_list"`
|
EmojiList []DouyinEmoji `json:"emoji_list"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// DouyinEmoji 抖音单个表情结构
|
// DouyinEmoji 抖音单个表情结构
|
||||||
type DouyinEmoji struct {
|
type DouyinEmoji struct {
|
||||||
OriginURI string `json:"origin_uri"`
|
OriginURI string `json:"origin_uri"`
|
||||||
DisplayName string `json:"display_name"`
|
DisplayName string `json:"display_name"`
|
||||||
Hide int `json:"hide"`
|
Hide int `json:"hide"`
|
||||||
EmojiURL struct {
|
EmojiURL struct {
|
||||||
URI string `json:"uri"`
|
URI string `json:"uri"`
|
||||||
URLList []string `json:"url_list"`
|
URLList []string `json:"url_list"`
|
||||||
} `json:"emoji_url"`
|
} `json:"emoji_url"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// LocalEmojiData 本地表情数据结构
|
// LocalEmojiData 本地表情数据结构
|
||||||
type LocalEmojiData struct {
|
type LocalEmojiData struct {
|
||||||
Version int `json:"version"`
|
Version int `json:"version"`
|
||||||
Size int `json:"size"`
|
Size int `json:"size"`
|
||||||
Datas map[string]string `json:"datas"`
|
Datas map[string]string `json:"datas"`
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
globalEmojiManager *EmojiManager
|
globalEmojiManager *EmojiManager
|
||||||
emojiOnce sync.Once
|
emojiOnce sync.Once
|
||||||
)
|
)
|
||||||
|
|
||||||
// GetEmojiManager 获取全局表情管理器实例
|
// GetEmojiManager 获取全局表情管理器实例
|
||||||
func GetEmojiManager() *EmojiManager {
|
func GetEmojiManager() *EmojiManager {
|
||||||
emojiOnce.Do(func() {
|
emojiOnce.Do(func() {
|
||||||
globalEmojiManager = &EmojiManager{
|
globalEmojiManager = &EmojiManager{
|
||||||
emojiMap: make(map[string]string),
|
emojiMap: make(map[string]string),
|
||||||
cacheExpiry: 24 * time.Hour, // 缓存24小时
|
cacheExpiry: 24 * time.Hour, // 缓存24小时
|
||||||
}
|
}
|
||||||
// 初始化时加载表情
|
// 初始化时加载表情
|
||||||
globalEmojiManager.LoadEmojis()
|
globalEmojiManager.LoadEmojis()
|
||||||
})
|
})
|
||||||
return globalEmojiManager
|
return globalEmojiManager
|
||||||
}
|
}
|
||||||
|
|
||||||
// LoadEmojis 加载表情映射(优先API,其次本地)
|
// LoadEmojis 加载表情映射(优先API,其次本地)
|
||||||
func (em *EmojiManager) LoadEmojis() error {
|
func (em *EmojiManager) LoadEmojis() error {
|
||||||
em.mutex.Lock()
|
em.mutex.Lock()
|
||||||
defer em.mutex.Unlock()
|
defer em.mutex.Unlock()
|
||||||
|
|
||||||
// 检查缓存是否过期
|
// 检查缓存是否过期
|
||||||
if time.Since(em.lastUpdate) < em.cacheExpiry && len(em.emojiMap) > 0 {
|
if time.Since(em.lastUpdate) < em.cacheExpiry && len(em.emojiMap) > 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
newMap := make(map[string]string)
|
newMap := make(map[string]string)
|
||||||
|
|
||||||
// 1. 先尝试从抖音API获取表情
|
// 1. 先尝试从抖音API获取表情
|
||||||
apiEmojis, err := em.fetchDouyinEmojis()
|
apiEmojis, err := em.fetchDouyinEmojis()
|
||||||
if err == nil && len(apiEmojis) > 0 {
|
if err == nil && len(apiEmojis) > 0 {
|
||||||
for displayName, url := range apiEmojis {
|
for displayName, url := range apiEmojis {
|
||||||
newMap[displayName] = url
|
newMap[displayName] = url
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 加载本地表情作为补充
|
// 2. 加载本地表情作为补充
|
||||||
localEmojis, err := em.loadLocalEmojis()
|
localEmojis, err := em.loadLocalEmojis()
|
||||||
if err == nil {
|
if err == nil {
|
||||||
for displayName, url := range localEmojis {
|
for displayName, url := range localEmojis {
|
||||||
// 如果API中没有,则使用本地的
|
// 如果API中没有,则使用本地的
|
||||||
if _, exists := newMap[displayName]; !exists {
|
if _, exists := newMap[displayName]; !exists {
|
||||||
newMap[displayName] = url
|
newMap[displayName] = url
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 更新缓存
|
// 3. 更新缓存
|
||||||
if len(newMap) > 0 {
|
if len(newMap) > 0 {
|
||||||
em.emojiMap = newMap
|
em.emojiMap = newMap
|
||||||
em.lastUpdate = time.Now()
|
em.lastUpdate = time.Now()
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// fetchDouyinEmojis 从抖音API获取表情映射
|
// fetchDouyinEmojis 从抖音API获取表情映射
|
||||||
func (em *EmojiManager) fetchDouyinEmojis() (map[string]string, error) {
|
func (em *EmojiManager) fetchDouyinEmojis() (map[string]string, error) {
|
||||||
client := &http.Client{
|
client := &http.Client{
|
||||||
Timeout: 10 * time.Second,
|
Timeout: 10 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := client.Get("https://www.douyin.com/aweme/v1/web/emoji/list")
|
resp, err := client.Get("https://www.douyin.com/aweme/v1/web/emoji/list")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("获取抖音表情API失败: %w", err)
|
return nil, fmt.Errorf("获取抖音表情API失败: %w", err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
if resp.StatusCode != http.StatusOK {
|
if resp.StatusCode != http.StatusOK {
|
||||||
return nil, fmt.Errorf("抖音表情API返回状态码: %d", resp.StatusCode)
|
return nil, fmt.Errorf("抖音表情API返回状态码: %d", resp.StatusCode)
|
||||||
}
|
}
|
||||||
|
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("读取响应失败: %w", err)
|
return nil, fmt.Errorf("读取响应失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var apiResp DouyinEmojiResponse
|
var apiResp DouyinEmojiResponse
|
||||||
if err := json.Unmarshal(body, &apiResp); err != nil {
|
if err := json.Unmarshal(body, &apiResp); err != nil {
|
||||||
return nil, fmt.Errorf("解析JSON失败: %w", err)
|
return nil, fmt.Errorf("解析JSON失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
emojiMap := make(map[string]string)
|
emojiMap := make(map[string]string)
|
||||||
for _, emoji := range apiResp.EmojiList {
|
for _, emoji := range apiResp.EmojiList {
|
||||||
if len(emoji.EmojiURL.URLList) > 0 {
|
if len(emoji.EmojiURL.URLList) > 0 {
|
||||||
// 使用第一个URL
|
// 使用第一个URL
|
||||||
emojiMap[emoji.DisplayName] = emoji.EmojiURL.URLList[0]
|
emojiMap[emoji.DisplayName] = emoji.EmojiURL.URLList[0]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return emojiMap, nil
|
return emojiMap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// loadLocalEmojis 从本地文件加载表情映射
|
// loadLocalEmojis 从本地文件加载表情映射
|
||||||
func (em *EmojiManager) loadLocalEmojis() (map[string]string, error) {
|
func (em *EmojiManager) loadLocalEmojis() (map[string]string, error) {
|
||||||
// 读取 data.json
|
// 读取 data.json
|
||||||
dataPath := filepath.Join("emoji", "data.json")
|
dataPath := filepath.Join("emoji", "data.json")
|
||||||
data, err := ioutil.ReadFile(dataPath)
|
data, err := ioutil.ReadFile(dataPath)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("读取emoji/data.json失败: %w", err)
|
return nil, fmt.Errorf("读取emoji/data.json失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
var localData LocalEmojiData
|
var localData LocalEmojiData
|
||||||
if err := json.Unmarshal(data, &localData); err != nil {
|
if err := json.Unmarshal(data, &localData); err != nil {
|
||||||
return nil, fmt.Errorf("解析emoji/data.json失败: %w", err)
|
return nil, fmt.Errorf("解析emoji/data.json失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
emojiMap := make(map[string]string)
|
emojiMap := make(map[string]string)
|
||||||
for id, displayName := range localData.Datas {
|
for id, displayName := range localData.Datas {
|
||||||
// 生成本地图片路径:emoji/images/emoji_dr_{id}.png
|
// 生成本地图片路径:emoji/images/emoji_dr_{id}.png
|
||||||
// 转换为相对URL路径
|
// 转换为相对URL路径
|
||||||
localPath := fmt.Sprintf("/emoji/images/emoji_dr_%s.png", id)
|
localPath := fmt.Sprintf("/emoji/images/emoji_dr_%s.png", id)
|
||||||
emojiMap[displayName] = localPath
|
emojiMap[displayName] = localPath
|
||||||
}
|
}
|
||||||
|
|
||||||
return emojiMap, nil
|
return emojiMap, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetEmojiURL 获取表情图片URL
|
// GetEmojiURL 获取表情图片URL
|
||||||
func (em *EmojiManager) GetEmojiURL(displayName string) (string, bool) {
|
func (em *EmojiManager) GetEmojiURL(displayName string) (string, bool) {
|
||||||
em.mutex.RLock()
|
em.mutex.RLock()
|
||||||
defer em.mutex.RUnlock()
|
defer em.mutex.RUnlock()
|
||||||
|
|
||||||
url, exists := em.emojiMap[displayName]
|
url, exists := em.emojiMap[displayName]
|
||||||
return url, exists
|
return url, exists
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetAllEmojis 获取所有表情映射(用于生成JavaScript代码)
|
// GetAllEmojis 获取所有表情映射(用于生成JavaScript代码)
|
||||||
func (em *EmojiManager) GetAllEmojis() map[string]string {
|
func (em *EmojiManager) GetAllEmojis() map[string]string {
|
||||||
em.mutex.RLock()
|
em.mutex.RLock()
|
||||||
defer em.mutex.RUnlock()
|
defer em.mutex.RUnlock()
|
||||||
|
|
||||||
// 返回副本
|
// 返回副本
|
||||||
result := make(map[string]string, len(em.emojiMap))
|
result := make(map[string]string, len(em.emojiMap))
|
||||||
for k, v := range em.emojiMap {
|
for k, v := range em.emojiMap {
|
||||||
result[k] = v
|
result[k] = v
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// RefreshEmojis 手动刷新表情缓存
|
// RefreshEmojis 手动刷新表情缓存
|
||||||
func (em *EmojiManager) RefreshEmojis() error {
|
func (em *EmojiManager) RefreshEmojis() error {
|
||||||
em.mutex.Lock()
|
em.mutex.Lock()
|
||||||
em.lastUpdate = time.Time{} // 重置更新时间
|
em.lastUpdate = time.Time{} // 重置更新时间
|
||||||
em.mutex.Unlock()
|
em.mutex.Unlock()
|
||||||
|
|
||||||
return em.LoadEmojis()
|
return em.LoadEmojis()
|
||||||
}
|
}
|
||||||
|
|
||||||
// CheckLocalEmojiFiles 检查本地表情文件是否存在
|
// CheckLocalEmojiFiles 检查本地表情文件是否存在
|
||||||
func CheckLocalEmojiFiles() error {
|
func CheckLocalEmojiFiles() error {
|
||||||
dataPath := filepath.Join("emoji", "data.json")
|
dataPath := filepath.Join("emoji", "data.json")
|
||||||
if _, err := os.Stat(dataPath); os.IsNotExist(err) {
|
if _, err := os.Stat(dataPath); os.IsNotExist(err) {
|
||||||
return fmt.Errorf("emoji/data.json 文件不存在")
|
return fmt.Errorf("emoji/data.json 文件不存在")
|
||||||
}
|
}
|
||||||
|
|
||||||
imagesDir := filepath.Join("emoji", "images")
|
imagesDir := filepath.Join("emoji", "images")
|
||||||
if _, err := os.Stat(imagesDir); os.IsNotExist(err) {
|
if _, err := os.Stat(imagesDir); os.IsNotExist(err) {
|
||||||
return fmt.Errorf("emoji/images 目录不存在")
|
return fmt.Errorf("emoji/images 目录不存在")
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ReplaceEmojisInText 替换文本中的表情为HTML img标签
|
// ReplaceEmojisInText 替换文本中的表情为HTML img标签
|
||||||
func ReplaceEmojisInText(text string) string {
|
func ReplaceEmojisInText(text string) string {
|
||||||
em := GetEmojiManager()
|
em := GetEmojiManager()
|
||||||
|
|
||||||
// 匹配 [表情] 格式
|
// 匹配 [表情] 格式
|
||||||
result := text
|
result := text
|
||||||
for displayName, url := range em.GetAllEmojis() {
|
for displayName, url := range em.GetAllEmojis() {
|
||||||
// 转义特殊字符
|
// 转义特殊字符
|
||||||
escapedName := strings.ReplaceAll(displayName, "[", "\\[")
|
escapedName := strings.ReplaceAll(displayName, "[", "\\[")
|
||||||
escapedName = strings.ReplaceAll(escapedName, "]", "\\]")
|
escapedName = strings.ReplaceAll(escapedName, "]", "\\]")
|
||||||
|
|
||||||
// 替换为 img 标签
|
// 替换为 img 标签
|
||||||
imgTag := fmt.Sprintf(`<img src="%s" class="emoji-img" alt="%s" />`, url, displayName)
|
imgTag := fmt.Sprintf(`<img src="%s" class="emoji-img" alt="%s" />`, url, displayName)
|
||||||
result = strings.ReplaceAll(result, displayName, imgTag)
|
result = strings.ReplaceAll(result, displayName, imgTag)
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,4 +114,3 @@ func ContentRequest(urlStr string, options map[string]interface{}) (*common.Clie
|
|||||||
client := common.NewHTTPClient()
|
client := common.NewHTTPClient()
|
||||||
return client.Request(urlStr, options)
|
return client.Request(urlStr, options)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -9,7 +9,7 @@ var itemSummaryLogger = common.NewLogger("item_summary", "INFO", "")
|
|||||||
|
|
||||||
// HandleItemSummary 处理获取章节摘要,章节摘要数据基本不变,缓存 24 小时
|
// HandleItemSummary 处理获取章节摘要,章节摘要数据基本不变,缓存 24 小时
|
||||||
func HandleItemSummary(itemIDs, bookID string) (string, error) {
|
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)
|
return fetchItemSummary(itemIDs, bookID)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -48,4 +48,3 @@ func fetchItemSummary(itemIDs, bookID string) (string, error) {
|
|||||||
|
|
||||||
return BuildErrorResponse("获取失败"), nil
|
return BuildErrorResponse("获取失败"), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
+18
-19
@@ -71,14 +71,14 @@ func getMangaWithRetry(itemID string, showHTML bool, urlOutputMode string, retry
|
|||||||
mangaLogger.Warning(fmt.Sprintf("已重试 %d 次,获取漫画失败", maxRetries))
|
mangaLogger.Warning(fmt.Sprintf("已重试 %d 次,获取漫画失败", maxRetries))
|
||||||
return nil, fmt.Errorf("已重试 %d 次,所有设备均失败", maxRetries)
|
return nil, fmt.Errorf("已重试 %d 次,所有设备均失败", maxRetries)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 1. 从设备密钥池获取设备
|
// 1. 从设备密钥池获取设备
|
||||||
pool := GetDeviceKeyPool()
|
pool := GetDeviceKeyPool()
|
||||||
item, err := pool.GetNext()
|
item, err := pool.GetNext()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("从设备池获取设备失败: %w", err)
|
return nil, fmt.Errorf("从设备池获取设备失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
header := item.DeviceHeader
|
header := item.DeviceHeader
|
||||||
keyInfo := &KeyInfo{
|
keyInfo := &KeyInfo{
|
||||||
Key: item.Key,
|
Key: item.Key,
|
||||||
@@ -171,18 +171,18 @@ func getMangaWithRetry(itemID string, showHTML bool, urlOutputMode string, retry
|
|||||||
// 是漫画,决定输出模式
|
// 是漫画,决定输出模式
|
||||||
// 优先级:URL参数 > 配置文件 > 默认值
|
// 优先级:URL参数 > 配置文件 > 默认值
|
||||||
outputMode := "proxy" // 默认值
|
outputMode := "proxy" // 默认值
|
||||||
|
|
||||||
// 从配置文件读取
|
// 从配置文件读取
|
||||||
cfg := config.GetConfig()
|
cfg := config.GetConfig()
|
||||||
if cfg != nil && cfg.Fanqie.Manga.OutputMode != "" {
|
if cfg != nil && cfg.Fanqie.Manga.OutputMode != "" {
|
||||||
outputMode = cfg.Fanqie.Manga.OutputMode
|
outputMode = cfg.Fanqie.Manga.OutputMode
|
||||||
}
|
}
|
||||||
|
|
||||||
// URL参数优先级最高
|
// URL参数优先级最高
|
||||||
if urlOutputMode != "" {
|
if urlOutputMode != "" {
|
||||||
outputMode = urlOutputMode
|
outputMode = urlOutputMode
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析漫画图片(传入keyInfo用于解密模式)
|
// 解析漫画图片(传入keyInfo用于解密模式)
|
||||||
images, err := parseMangaImages(decrypted, showHTML, outputMode, itemID, keyInfo)
|
images, err := parseMangaImages(decrypted, showHTML, outputMode, itemID, keyInfo)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -279,7 +279,7 @@ func buildMangaResponse(images []ImageResult, showHTML bool) interface{} {
|
|||||||
"content": htmlContent.String(),
|
"content": htmlContent.String(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"images": images,
|
"images": images,
|
||||||
}
|
}
|
||||||
@@ -289,7 +289,7 @@ func buildMangaResponse(images []ImageResult, showHTML bool) interface{} {
|
|||||||
func processURLMode(mangaData *MangaData) []ImageResult {
|
func processURLMode(mangaData *MangaData) []ImageResult {
|
||||||
baseDomain := "https://p6-novel.byteimg.com/origin/"
|
baseDomain := "https://p6-novel.byteimg.com/origin/"
|
||||||
validPath := detectMangaPath(baseDomain, mangaData.PicInfos[0].Md5)
|
validPath := detectMangaPath(baseDomain, mangaData.PicInfos[0].Md5)
|
||||||
|
|
||||||
images := make([]ImageResult, len(mangaData.PicInfos))
|
images := make([]ImageResult, len(mangaData.PicInfos))
|
||||||
for i, pic := range mangaData.PicInfos {
|
for i, pic := range mangaData.PicInfos {
|
||||||
imageURL := baseDomain + validPath + pic.Md5
|
imageURL := baseDomain + validPath + pic.Md5
|
||||||
@@ -309,7 +309,7 @@ func processProxyMode(mangaData *MangaData, itemID string) []ImageResult {
|
|||||||
images := make([]ImageResult, len(mangaData.PicInfos))
|
images := make([]ImageResult, len(mangaData.PicInfos))
|
||||||
for i, pic := range mangaData.PicInfos {
|
for i, pic := range mangaData.PicInfos {
|
||||||
cacheKey := fmt.Sprintf("%s_%d", itemID, i)
|
cacheKey := fmt.Sprintf("%s_%d", itemID, i)
|
||||||
|
|
||||||
// 存储图片信息到缓存
|
// 存储图片信息到缓存
|
||||||
mangaCacheMutex.Lock()
|
mangaCacheMutex.Lock()
|
||||||
mangaImageCache[cacheKey] = &MangaImageInfo{
|
mangaImageCache[cacheKey] = &MangaImageInfo{
|
||||||
@@ -320,7 +320,7 @@ func processProxyMode(mangaData *MangaData, itemID string) []ImageResult {
|
|||||||
CachedAt: time.Now(),
|
CachedAt: time.Now(),
|
||||||
}
|
}
|
||||||
mangaCacheMutex.Unlock()
|
mangaCacheMutex.Unlock()
|
||||||
|
|
||||||
// 返回短的代理URL
|
// 返回短的代理URL
|
||||||
imageData := fmt.Sprintf("/manga/image/%s/%d", itemID, i)
|
imageData := fmt.Sprintf("/manga/image/%s/%d", itemID, i)
|
||||||
images[i] = ImageResult{
|
images[i] = ImageResult{
|
||||||
@@ -390,7 +390,7 @@ func processDataURIMode(mangaData *MangaData) []ImageResult {
|
|||||||
|
|
||||||
// Base64编码图片数据
|
// Base64编码图片数据
|
||||||
base64Data := base64.StdEncoding.EncodeToString(decryptedData)
|
base64Data := base64.StdEncoding.EncodeToString(decryptedData)
|
||||||
|
|
||||||
// Data URI模式:返回完整的Base64编码
|
// Data URI模式:返回完整的Base64编码
|
||||||
mimeType := fmt.Sprintf("image/%s", format)
|
mimeType := fmt.Sprintf("image/%s", format)
|
||||||
if format == "jpg" {
|
if format == "jpg" {
|
||||||
@@ -542,31 +542,31 @@ func decryptImage(encryptedData, keyBytes []byte) ([]byte, error) {
|
|||||||
func detectMangaPath(baseDomain, firstMd5 string) string {
|
func detectMangaPath(baseDomain, firstMd5 string) string {
|
||||||
// 优先尝试 novel-images/
|
// 优先尝试 novel-images/
|
||||||
testURL := baseDomain + "novel-images/" + firstMd5
|
testURL := baseDomain + "novel-images/" + firstMd5
|
||||||
|
|
||||||
client := &http.Client{
|
client := &http.Client{
|
||||||
Timeout: 8 * time.Second,
|
Timeout: 8 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
resp, err := client.Get(testURL)
|
resp, err := client.Get(testURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// 请求失败,使用novel-pic/
|
// 请求失败,使用novel-pic/
|
||||||
return "novel-pic/"
|
return "novel-pic/"
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
|
|
||||||
// 读取响应内容
|
// 读取响应内容
|
||||||
body, err := io.ReadAll(resp.Body)
|
body, err := io.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "novel-pic/"
|
return "novel-pic/"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否为JSON响应(错误响应通常是JSON)
|
// 检查是否为JSON响应(错误响应通常是JSON)
|
||||||
var jsonData interface{}
|
var jsonData interface{}
|
||||||
if json.Unmarshal(body, &jsonData) == nil {
|
if json.Unmarshal(body, &jsonData) == nil {
|
||||||
// 是JSON,说明路径无效,切换到novel-pic/
|
// 是JSON,说明路径无效,切换到novel-pic/
|
||||||
return "novel-pic/"
|
return "novel-pic/"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 不是JSON,说明返回的是图片,路径有效
|
// 不是JSON,说明返回的是图片,路径有效
|
||||||
return "novel-images/"
|
return "novel-images/"
|
||||||
}
|
}
|
||||||
@@ -605,12 +605,11 @@ func getImageFormat(data []byte, url string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// WEBP: RIFF...WEBP
|
// WEBP: RIFF...WEBP
|
||||||
if bytes.HasPrefix(data, []byte{0x52, 0x49, 0x46, 0x46}) &&
|
if bytes.HasPrefix(data, []byte{0x52, 0x49, 0x46, 0x46}) &&
|
||||||
len(data) >= 12 &&
|
len(data) >= 12 &&
|
||||||
bytes.Equal(data[8:12], []byte{0x57, 0x45, 0x42, 0x50}) {
|
bytes.Equal(data[8:12], []byte{0x57, 0x45, 0x42, 0x50}) {
|
||||||
return "webp"
|
return "webp"
|
||||||
}
|
}
|
||||||
|
|
||||||
return "png"
|
return "png"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,72 +1,71 @@
|
|||||||
package fqapi
|
package fqapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"fmt"
|
"fmt"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
// HandleMangaImageProxy 处理漫画图片代理请求
|
// HandleMangaImageProxy 处理漫画图片代理请求
|
||||||
func HandleMangaImageProxy(itemID string, index int) ([]byte, string, error) {
|
func HandleMangaImageProxy(itemID string, index int) ([]byte, string, error) {
|
||||||
// 从缓存获取图片信息
|
// 从缓存获取图片信息
|
||||||
cacheKey := fmt.Sprintf("%s_%d", itemID, index)
|
cacheKey := fmt.Sprintf("%s_%d", itemID, index)
|
||||||
|
|
||||||
mangaCacheMutex.RLock()
|
mangaCacheMutex.RLock()
|
||||||
imageInfo, exists := mangaImageCache[cacheKey]
|
imageInfo, exists := mangaImageCache[cacheKey]
|
||||||
mangaCacheMutex.RUnlock()
|
mangaCacheMutex.RUnlock()
|
||||||
|
|
||||||
if !exists {
|
if !exists {
|
||||||
return nil, "", fmt.Errorf("图片信息不存在,请先调用 /manga 接口")
|
return nil, "", fmt.Errorf("图片信息不存在,请先调用 /manga 接口")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查缓存是否过期(5分钟)
|
// 检查缓存是否过期(5分钟)
|
||||||
if time.Since(imageInfo.CachedAt) > 5*time.Minute {
|
if time.Since(imageInfo.CachedAt) > 5*time.Minute {
|
||||||
// 清理过期缓存
|
// 清理过期缓存
|
||||||
mangaCacheMutex.Lock()
|
mangaCacheMutex.Lock()
|
||||||
delete(mangaImageCache, cacheKey)
|
delete(mangaImageCache, cacheKey)
|
||||||
mangaCacheMutex.Unlock()
|
mangaCacheMutex.Unlock()
|
||||||
return nil, "", fmt.Errorf("图片信息已过期,请重新调用 /manga 接口")
|
return nil, "", fmt.Errorf("图片信息已过期,请重新调用 /manga 接口")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 下载加密图片
|
// 下载加密图片
|
||||||
encryptedData, err := downloadImageWithRetry(imageInfo.PicURL, 2)
|
encryptedData, err := downloadImageWithRetry(imageInfo.PicURL, 2)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", fmt.Errorf("下载图片失败: %w", err)
|
return nil, "", fmt.Errorf("下载图片失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解密图片
|
// 解密图片
|
||||||
keyBytes, err := hex.DecodeString(imageInfo.EncryptKey)
|
keyBytes, err := hex.DecodeString(imageInfo.EncryptKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", fmt.Errorf("密钥解码失败: %w", err)
|
return nil, "", fmt.Errorf("密钥解码失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
decryptedData, err := decryptImage(encryptedData, keyBytes)
|
decryptedData, err := decryptImage(encryptedData, keyBytes)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, "", fmt.Errorf("解密失败: %w", err)
|
return nil, "", fmt.Errorf("解密失败: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 识别格式
|
// 识别格式
|
||||||
format := getImageFormat(decryptedData, imageInfo.PicURL)
|
format := getImageFormat(decryptedData, imageInfo.PicURL)
|
||||||
|
|
||||||
// 返回图片数据和MIME类型
|
// 返回图片数据和MIME类型
|
||||||
mimeType := fmt.Sprintf("image/%s", format)
|
mimeType := fmt.Sprintf("image/%s", format)
|
||||||
if format == "jpg" {
|
if format == "jpg" {
|
||||||
mimeType = "image/jpeg"
|
mimeType = "image/jpeg"
|
||||||
}
|
}
|
||||||
|
|
||||||
return decryptedData, mimeType, nil
|
return decryptedData, mimeType, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CleanExpiredMangaCache 清理过期的漫画图片缓存
|
// CleanExpiredMangaCache 清理过期的漫画图片缓存
|
||||||
func CleanExpiredMangaCache() {
|
func CleanExpiredMangaCache() {
|
||||||
mangaCacheMutex.Lock()
|
mangaCacheMutex.Lock()
|
||||||
defer mangaCacheMutex.Unlock()
|
defer mangaCacheMutex.Unlock()
|
||||||
|
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
for key, info := range mangaImageCache {
|
for key, info := range mangaImageCache {
|
||||||
if now.Sub(info.CachedAt) > 5*time.Minute {
|
if now.Sub(info.CachedAt) > 5*time.Minute {
|
||||||
delete(mangaImageCache, key)
|
delete(mangaImageCache, key)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,15 +32,15 @@ func extractDeviceParam(deviceHeader, paramName string) string {
|
|||||||
return ""
|
return ""
|
||||||
}
|
}
|
||||||
|
|
||||||
// downloadMediaWithRetry 带重试的媒体下载,自动切换设备
|
// downloadMediaWithRetry 带重试的流式媒体下载,自动切换设备(仅响应阶段可重试)
|
||||||
func downloadMediaWithRetry(url, deviceID string, headers map[string]string, maxRetries int) ([]byte, string, error) {
|
func downloadMediaWithRetry(url, deviceID string, headers map[string]string, maxRetries int) (io.ReadCloser, string, error) {
|
||||||
var lastErr error
|
var lastErr error
|
||||||
currentDeviceID := deviceID
|
currentDeviceID := deviceID
|
||||||
|
|
||||||
for i := 0; i <= maxRetries; i++ {
|
for i := 0; i <= maxRetries; i++ {
|
||||||
data, contentType, err := downloadMedia(url, currentDeviceID, headers)
|
body, contentType, err := downloadMedia(url, currentDeviceID, headers)
|
||||||
if err == nil && len(data) > 0 {
|
if err == nil {
|
||||||
return data, contentType, nil
|
return body, contentType, nil
|
||||||
}
|
}
|
||||||
lastErr = err
|
lastErr = err
|
||||||
|
|
||||||
@@ -58,9 +58,10 @@ func downloadMediaWithRetry(url, deviceID string, headers map[string]string, max
|
|||||||
return nil, "", fmt.Errorf("下载失败(已重试%d次): %w", maxRetries, lastErr)
|
return nil, "", fmt.Errorf("下载失败(已重试%d次): %w", maxRetries, lastErr)
|
||||||
}
|
}
|
||||||
|
|
||||||
// downloadMedia 下载媒体内容
|
// downloadMedia 流式下载媒体内容:拿到响应头即返回,Body 由调用方消费
|
||||||
func downloadMedia(url, deviceID string, headers map[string]string) ([]byte, string, error) {
|
// 大文件不再整体驻留内存;Body 读取中途的错误无法重试,由客户端自行重试
|
||||||
// 创建专用的媒体下载客户端,超时时间更长
|
func downloadMedia(url, deviceID string, headers map[string]string) (io.ReadCloser, string, error) {
|
||||||
|
// 创建专用的媒体下载客户端,超时时间更长(Timeout 覆盖整个响应周期含 Body 传输)
|
||||||
client := &http.Client{
|
client := &http.Client{
|
||||||
Timeout: 300 * time.Second, // 5分钟超时,适合大文件
|
Timeout: 300 * time.Second, // 5分钟超时,适合大文件
|
||||||
}
|
}
|
||||||
@@ -70,6 +71,30 @@ func downloadMedia(url, deviceID string, headers map[string]string) ([]byte, str
|
|||||||
return nil, "", err
|
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请求头,模拟安卓客户端请求
|
// 设置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("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", "*/*")
|
req.Header.Set("Accept", "*/*")
|
||||||
@@ -89,31 +114,6 @@ func downloadMedia(url, deviceID string, headers map[string]string) ([]byte, str
|
|||||||
for k, v := range headers {
|
for k, v := range headers {
|
||||||
req.Header.Set(k, v)
|
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
|
// getContentTypeFromURL 根据URL推断Content-Type
|
||||||
@@ -179,11 +179,16 @@ func processMediaURL(originalURL, deviceID string, headers map[string]string, ou
|
|||||||
// 其他类型返回原始URL
|
// 其他类型返回原始URL
|
||||||
return originalURL
|
return originalURL
|
||||||
case "data_uri":
|
case "data_uri":
|
||||||
// 直接下载并返回base64
|
// 直接下载并返回base64(data_uri 模式本就要求全量驻留内存)
|
||||||
data, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 2)
|
body, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 2)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return originalURL
|
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))
|
return fmt.Sprintf("data:%s;base64,%s", contentType, base64.StdEncoding.EncodeToString(data))
|
||||||
default:
|
default:
|
||||||
// 直接返回原始URL
|
// 直接返回原始URL
|
||||||
|
|||||||
@@ -116,7 +116,7 @@ func MultiContent(itemIDs interface{}, bookID string, textMode, imageMode, ignor
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return `{"code": -1, "msg": "从设备池获取设备失败"}`, err
|
return `{"code": -1, "msg": "从设备池获取设备失败"}`, err
|
||||||
}
|
}
|
||||||
|
|
||||||
header := item.DeviceHeader
|
header := item.DeviceHeader
|
||||||
currentKeyInfo := &KeyInfo{
|
currentKeyInfo := &KeyInfo{
|
||||||
Key: item.Key,
|
Key: item.Key,
|
||||||
@@ -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) {
|
func HandleMultiContent(itemIDs interface{}, bookID string, textMode, imageMode, ignoreFailed interface{}) (string, error) {
|
||||||
return MultiContent(itemIDs, bookID, textMode, imageMode, ignoreFailed, 0)
|
return MultiContent(itemIDs, bookID, textMode, imageMode, ignoreFailed, 0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,4 +218,3 @@ func fetchMultiDetail(bookID interface{}) (string, error) {
|
|||||||
resultBytes, _ := json.Marshal(response)
|
resultBytes, _ := json.Marshal(response)
|
||||||
return string(resultBytes), nil
|
return string(resultBytes), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,4 +246,3 @@ func GetKeyInfo() *KeyInfo {
|
|||||||
func init() {
|
func init() {
|
||||||
rand.Seed(time.Now().UnixNano())
|
rand.Seed(time.Now().UnixNano())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
package fqapi
|
package fqapi
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
|
"encoding/json"
|
||||||
"fanqie/internal/common"
|
"fanqie/internal/common"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/url"
|
"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 {
|
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
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -193,4 +193,3 @@ func Decrypt(encryptedStr string) ([]byte, error) {
|
|||||||
}
|
}
|
||||||
return TTDecrypt(encryptedData)
|
return TTDecrypt(encryptedData)
|
||||||
}
|
}
|
||||||
|
|
||||||
+17
-18
@@ -144,10 +144,10 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
|||||||
// 解析失败,返回空对象
|
// 解析失败,返回空对象
|
||||||
return map[string]interface{}{}
|
return map[string]interface{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 构建精简的返回结果,只包含关键字段
|
// 构建精简的返回结果,只包含关键字段
|
||||||
result := make(map[string]interface{})
|
result := make(map[string]interface{})
|
||||||
|
|
||||||
// 提取关键字段
|
// 提取关键字段
|
||||||
if videoID, ok := videoModel["video_id"].(string); ok {
|
if videoID, ok := videoModel["video_id"].(string); ok {
|
||||||
result["video_id"] = videoID
|
result["video_id"] = videoID
|
||||||
@@ -158,16 +158,16 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
|||||||
if posterURL, ok := videoModel["poster_url"].(string); ok {
|
if posterURL, ok := videoModel["poster_url"].(string); ok {
|
||||||
result["poster_url"] = posterURL
|
result["poster_url"] = posterURL
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理 video_list
|
// 处理 video_list
|
||||||
if videoList, ok := videoModel["video_list"].(map[string]interface{}); ok {
|
if videoList, ok := videoModel["video_list"].(map[string]interface{}); ok {
|
||||||
processedVideoList := make(map[string]interface{})
|
processedVideoList := make(map[string]interface{})
|
||||||
|
|
||||||
for quality, qualityData := range videoList {
|
for quality, qualityData := range videoList {
|
||||||
if qualityMap, ok := qualityData.(map[string]interface{}); ok {
|
if qualityMap, ok := qualityData.(map[string]interface{}); ok {
|
||||||
// 只保留关键字段
|
// 只保留关键字段
|
||||||
qualityInfo := make(map[string]interface{})
|
qualityInfo := make(map[string]interface{})
|
||||||
|
|
||||||
if definition, ok := qualityMap["definition"].(string); ok {
|
if definition, ok := qualityMap["definition"].(string); ok {
|
||||||
qualityInfo["definition"] = definition
|
qualityInfo["definition"] = definition
|
||||||
}
|
}
|
||||||
@@ -189,39 +189,39 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
|||||||
if fps, ok := qualityMap["fps"].(float64); ok {
|
if fps, ok := qualityMap["fps"].(float64); ok {
|
||||||
qualityInfo["fps"] = int(fps)
|
qualityInfo["fps"] = int(fps)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解码 main_url
|
// 解码 main_url
|
||||||
if mainURL, ok := qualityMap["main_url"].(string); ok {
|
if mainURL, ok := qualityMap["main_url"].(string); ok {
|
||||||
if decoded, err := base64.StdEncoding.DecodeString(mainURL); err == nil {
|
if decoded, err := base64.StdEncoding.DecodeString(mainURL); err == nil {
|
||||||
qualityInfo["main_url"] = string(decoded)
|
qualityInfo["main_url"] = string(decoded)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解码 backup_url_1
|
// 解码 backup_url_1
|
||||||
if backupURL, ok := qualityMap["backup_url_1"].(string); ok {
|
if backupURL, ok := qualityMap["backup_url_1"].(string); ok {
|
||||||
if decoded, err := base64.StdEncoding.DecodeString(backupURL); err == nil {
|
if decoded, err := base64.StdEncoding.DecodeString(backupURL); err == nil {
|
||||||
qualityInfo["backup_url_1"] = string(decoded)
|
qualityInfo["backup_url_1"] = string(decoded)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
processedVideoList[quality] = qualityInfo
|
processedVideoList[quality] = qualityInfo
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
result["video_list"] = processedVideoList
|
result["video_list"] = processedVideoList
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatDuration 将秒数转换为可读的时间格式
|
// formatDuration 将秒数转换为可读的时间格式
|
||||||
func formatDuration(seconds float64) string {
|
func formatDuration(seconds float64) string {
|
||||||
totalSeconds := int(math.Round(seconds))
|
totalSeconds := int(math.Round(seconds))
|
||||||
|
|
||||||
hours := totalSeconds / 3600
|
hours := totalSeconds / 3600
|
||||||
minutes := (totalSeconds % 3600) / 60
|
minutes := (totalSeconds % 3600) / 60
|
||||||
secs := totalSeconds % 60
|
secs := totalSeconds % 60
|
||||||
|
|
||||||
if hours > 0 {
|
if hours > 0 {
|
||||||
return fmt.Sprintf("%d小时%d分%d秒", hours, minutes, secs)
|
return fmt.Sprintf("%d小时%d分%d秒", hours, minutes, secs)
|
||||||
} else if minutes > 0 {
|
} else if minutes > 0 {
|
||||||
@@ -236,17 +236,17 @@ func formatFileSize(bytes float64) string {
|
|||||||
if bytes < unit {
|
if bytes < unit {
|
||||||
return fmt.Sprintf("%.0f B", bytes)
|
return fmt.Sprintf("%.0f B", bytes)
|
||||||
}
|
}
|
||||||
|
|
||||||
kb := bytes / unit
|
kb := bytes / unit
|
||||||
if kb < unit {
|
if kb < unit {
|
||||||
return fmt.Sprintf("%.2f KB", kb)
|
return fmt.Sprintf("%.2f KB", kb)
|
||||||
}
|
}
|
||||||
|
|
||||||
mb := kb / unit
|
mb := kb / unit
|
||||||
if mb < unit {
|
if mb < unit {
|
||||||
return fmt.Sprintf("%.2f MB", mb)
|
return fmt.Sprintf("%.2f MB", mb)
|
||||||
}
|
}
|
||||||
|
|
||||||
gb := mb / unit
|
gb := mb / unit
|
||||||
return fmt.Sprintf("%.2f GB", gb)
|
return fmt.Sprintf("%.2f GB", gb)
|
||||||
}
|
}
|
||||||
@@ -255,12 +255,11 @@ func formatFileSize(bytes float64) string {
|
|||||||
func formatBitrate(bitrate float64) string {
|
func formatBitrate(bitrate float64) string {
|
||||||
const unit = 1000.0
|
const unit = 1000.0
|
||||||
kbps := bitrate / unit
|
kbps := bitrate / unit
|
||||||
|
|
||||||
if kbps < unit {
|
if kbps < unit {
|
||||||
return fmt.Sprintf("%.0f Kbps", kbps)
|
return fmt.Sprintf("%.0f Kbps", kbps)
|
||||||
}
|
}
|
||||||
|
|
||||||
mbps := kbps / unit
|
mbps := kbps / unit
|
||||||
return fmt.Sprintf("%.2f Mbps", mbps)
|
return fmt.Sprintf("%.2f Mbps", mbps)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,4 +103,3 @@ func HandleMultiDetail(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
fmt.Fprint(w, result)
|
fmt.Fprint(w, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -41,4 +41,3 @@ func HandleCategoryLanding(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
fmt.Fprint(w, result)
|
fmt.Fprint(w, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -6,9 +6,14 @@ import (
|
|||||||
"fanqie/internal/config"
|
"fanqie/internal/config"
|
||||||
"fanqie/internal/fqapi"
|
"fanqie/internal/fqapi"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/time/rate"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -62,7 +67,7 @@ func LoadStatistics() {
|
|||||||
fmt.Printf("加载统计数据失败: %v\n", err)
|
fmt.Printf("加载统计数据失败: %v\n", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
for k, v := range stats {
|
for k, v := range stats {
|
||||||
if c, ok := requestStats[k]; ok {
|
if c, ok := requestStats[k]; ok {
|
||||||
c.Store(v)
|
c.Store(v)
|
||||||
@@ -106,23 +111,85 @@ func respondError(w http.ResponseWriter, msg string, isClientErr bool) {
|
|||||||
respondJSON(w, status, map[string]interface{}{"code": -1, "msg": msg})
|
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 验证访问密钥中间件
|
// RequireAccessKey 验证访问密钥中间件
|
||||||
func RequireAccessKey(handler http.HandlerFunc) http.HandlerFunc {
|
func RequireAccessKey(handler http.HandlerFunc) http.HandlerFunc {
|
||||||
return func(w http.ResponseWriter, r *http.Request) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
cfg := config.GetConfig()
|
cfg := config.GetConfig()
|
||||||
|
|
||||||
// 如果未配置 access_key 或为空,则不启用验证
|
// 如果未配置 access_key 或为空,则不启用验证
|
||||||
if cfg == nil || cfg.Server.AccessKey == "" {
|
if cfg == nil || cfg.Server.AccessKey == "" {
|
||||||
handler(w, r)
|
handler(w, r)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从查询参数或 Header 中获取 key
|
// 从查询参数或 Header 中获取 key
|
||||||
key := r.URL.Query().Get("key")
|
key := r.URL.Query().Get("key")
|
||||||
if key == "" {
|
if key == "" {
|
||||||
key = r.Header.Get("X-Access-Key")
|
key = r.Header.Get("X-Access-Key")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 验证密钥(常量时间比较,防时序攻击)
|
// 验证密钥(常量时间比较,防时序攻击)
|
||||||
if subtle.ConstantTimeCompare([]byte(key), []byte(cfg.Server.AccessKey)) != 1 {
|
if subtle.ConstantTimeCompare([]byte(key), []byte(cfg.Server.AccessKey)) != 1 {
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
@@ -164,11 +231,11 @@ func HandleMain(w http.ResponseWriter, r *http.Request) {
|
|||||||
// HandleSelfInfo 设备信息处理
|
// HandleSelfInfo 设备信息处理
|
||||||
func HandleSelfInfo(w http.ResponseWriter, r *http.Request) {
|
func HandleSelfInfo(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
|
||||||
// 获取设备池统计信息
|
// 获取设备池统计信息
|
||||||
pool := fqapi.GetDeviceKeyPool()
|
pool := fqapi.GetDeviceKeyPool()
|
||||||
poolStats := pool.GetStats()
|
poolStats := pool.GetStats()
|
||||||
|
|
||||||
response := map[string]interface{}{
|
response := map[string]interface{}{
|
||||||
"code": 0,
|
"code": 0,
|
||||||
"message": "SUCCESS",
|
"message": "SUCCESS",
|
||||||
|
|||||||
@@ -20,9 +20,9 @@ func HandleContent(w http.ResponseWriter, r *http.Request) {
|
|||||||
itemID := params["item_id"]
|
itemID := params["item_id"]
|
||||||
|
|
||||||
// 获取URL参数(支持动态覆盖配置)
|
// 获取URL参数(支持动态覆盖配置)
|
||||||
textMode := r.URL.Query().Get("text_mode") // 1=纯文本模式
|
textMode := r.URL.Query().Get("text_mode") // 1=纯文本模式
|
||||||
imageMode := r.URL.Query().Get("image_mode") // 0=移除图片, 1=保留图片
|
imageMode := r.URL.Query().Get("image_mode") // 0=移除图片, 1=保留图片
|
||||||
reviewParam := r.URL.Query().Get("review") // 1=启用段评, 0=禁用段评
|
reviewParam := r.URL.Query().Get("review") // 1=启用段评, 0=禁用段评
|
||||||
|
|
||||||
result, err := fqapi.HandleGetContent(itemID, textMode, imageMode)
|
result, err := fqapi.HandleGetContent(itemID, textMode, imageMode)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -103,19 +103,19 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
|||||||
if err := fqapi.ParseJSON([]byte(jsonResult), &resultData); err != nil {
|
if err := fqapi.ParseJSON([]byte(jsonResult), &resultData); err != nil {
|
||||||
return jsonResult
|
return jsonResult
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取 data 字段
|
// 获取 data 字段
|
||||||
data, ok := resultData["data"].(map[string]interface{})
|
data, ok := resultData["data"].(map[string]interface{})
|
||||||
if !ok {
|
if !ok {
|
||||||
return jsonResult
|
return jsonResult
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取 content 字段
|
// 获取 content 字段
|
||||||
content, ok := data["content"].(string)
|
content, ok := data["content"].(string)
|
||||||
if !ok || content == "" {
|
if !ok || content == "" {
|
||||||
return jsonResult
|
return jsonResult
|
||||||
}
|
}
|
||||||
|
|
||||||
// 从响应数据中提取 book_id (data.novel_data.book_id)
|
// 从响应数据中提取 book_id (data.novel_data.book_id)
|
||||||
bookID := ""
|
bookID := ""
|
||||||
if novelData, ok := data["novel_data"].(map[string]interface{}); ok {
|
if novelData, ok := data["novel_data"].(map[string]interface{}); ok {
|
||||||
@@ -125,7 +125,7 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
|||||||
bookID = fmt.Sprintf("%.0f", bookIDVal)
|
bookID = fmt.Sprintf("%.0f", bookIDVal)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取基础 URL
|
// 获取基础 URL
|
||||||
cfg := config.GetConfig()
|
cfg := config.GetConfig()
|
||||||
baseURL := ""
|
baseURL := ""
|
||||||
@@ -136,7 +136,7 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
|||||||
}
|
}
|
||||||
port := cfg.Server.Port
|
port := cfg.Server.Port
|
||||||
scheme := "http"
|
scheme := "http"
|
||||||
|
|
||||||
// 检查是否来自外部请求
|
// 检查是否来自外部请求
|
||||||
if r.Host != "" {
|
if r.Host != "" {
|
||||||
baseURL = scheme + "://" + r.Host
|
baseURL = scheme + "://" + r.Host
|
||||||
@@ -144,24 +144,23 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
|||||||
baseURL = scheme + "://" + host + ":" + port
|
baseURL = scheme + "://" + host + ":" + port
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 生成带段评标记的内容
|
// 生成带段评标记的内容
|
||||||
newContent, err := fqapi.GenerateParagraphsWithComments(itemID, bookID, content, baseURL)
|
newContent, err := fqapi.GenerateParagraphsWithComments(itemID, bookID, content, baseURL)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// 如果失败,返回原始内容
|
// 如果失败,返回原始内容
|
||||||
return jsonResult
|
return jsonResult
|
||||||
}
|
}
|
||||||
|
|
||||||
// 替换 content 字段
|
// 替换 content 字段
|
||||||
data["content"] = newContent
|
data["content"] = newContent
|
||||||
resultData["data"] = data
|
resultData["data"] = data
|
||||||
|
|
||||||
// 重新序列化为 JSON
|
// 重新序列化为 JSON
|
||||||
newJSON, err := fqapi.ToJSON(resultData)
|
newJSON, err := fqapi.ToJSON(resultData)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return jsonResult
|
return jsonResult
|
||||||
}
|
}
|
||||||
|
|
||||||
return newJSON
|
return newJSON
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13,32 +13,31 @@ func HandleMangaImageProxy(w http.ResponseWriter, r *http.Request) {
|
|||||||
// 从URL路径提取参数: /manga/image/{itemID}/{index}
|
// 从URL路径提取参数: /manga/image/{itemID}/{index}
|
||||||
path := strings.TrimPrefix(r.URL.Path, "/manga/image/")
|
path := strings.TrimPrefix(r.URL.Path, "/manga/image/")
|
||||||
parts := strings.Split(path, "/")
|
parts := strings.Split(path, "/")
|
||||||
|
|
||||||
if len(parts) != 2 {
|
if len(parts) != 2 {
|
||||||
http.Error(w, "Invalid URL format. Expected: /manga/image/{itemID}/{index}", http.StatusBadRequest)
|
http.Error(w, "Invalid URL format. Expected: /manga/image/{itemID}/{index}", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
itemID := parts[0]
|
itemID := parts[0]
|
||||||
index, err := strconv.Atoi(parts[1])
|
index, err := strconv.Atoi(parts[1])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, "Invalid index parameter", http.StatusBadRequest)
|
http.Error(w, "Invalid index parameter", http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取解密后的图片数据
|
// 获取解密后的图片数据
|
||||||
imageData, mimeType, err := fqapi.HandleMangaImageProxy(itemID, index)
|
imageData, mimeType, err := fqapi.HandleMangaImageProxy(itemID, index)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
http.Error(w, fmt.Sprintf("Failed to get image: %s", err.Error()), http.StatusInternalServerError)
|
http.Error(w, fmt.Sprintf("Failed to get image: %s", err.Error()), http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 设置响应头
|
// 设置响应头
|
||||||
w.Header().Set("Content-Type", mimeType)
|
w.Header().Set("Content-Type", mimeType)
|
||||||
w.Header().Set("Cache-Control", "public, max-age=3600") // 缓存1小时
|
w.Header().Set("Cache-Control", "public, max-age=3600") // 缓存1小时
|
||||||
w.Header().Set("Content-Length", strconv.Itoa(len(imageData)))
|
w.Header().Set("Content-Length", strconv.Itoa(len(imageData)))
|
||||||
|
|
||||||
// 返回图片数据
|
// 返回图片数据
|
||||||
w.Write(imageData)
|
w.Write(imageData)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fanqie/internal/fqapi"
|
"fanqie/internal/fqapi"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
@@ -31,9 +32,9 @@ func HandleAudio(w http.ResponseWriter, r *http.Request) {
|
|||||||
fmt.Fprint(w, result)
|
fmt.Fprint(w, result)
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleAudioProxy 音频代理处理
|
// HandleAudioProxy 音频代理处理(流式转发,音频不全量驻留内存)
|
||||||
func HandleAudioProxy(w http.ResponseWriter, r *http.Request) {
|
func HandleAudioProxy(w http.ResponseWriter, r *http.Request) {
|
||||||
incrementStat("total")
|
incrementStat("total", "audio")
|
||||||
|
|
||||||
// 从URL路径提取key: /audio/proxy/{key}
|
// 从URL路径提取key: /audio/proxy/{key}
|
||||||
path := r.URL.Path
|
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 {
|
if err != nil {
|
||||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
defer body.Close()
|
||||||
|
|
||||||
// 设置正确的Content-Type
|
// 设置正确的Content-Type
|
||||||
if contentType != "" {
|
if contentType != "" {
|
||||||
@@ -59,7 +61,7 @@ func HandleAudioProxy(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
// 直接播放,不强制下载
|
// 直接播放,不强制下载
|
||||||
// 浏览器会根据Content-Type决定是播放还是下载
|
// 浏览器会根据Content-Type决定是播放还是下载
|
||||||
w.Write(data)
|
io.Copy(w, body)
|
||||||
}
|
}
|
||||||
|
|
||||||
// HandleVideo 视频处理
|
// HandleVideo 视频处理
|
||||||
@@ -133,4 +135,3 @@ func HandleManga(w http.ResponseWriter, r *http.Request) {
|
|||||||
fmt.Fprint(w, string(jsonData))
|
fmt.Fprint(w, string(jsonData))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
+81
-925
File diff suppressed because it is too large.
Load diff
+54
-806
@@ -1,11 +1,13 @@
|
|||||||
package handlers
|
package handlers
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
_ "embed"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fanqie/internal/algos"
|
"fanqie/internal/algos"
|
||||||
"fanqie/internal/config"
|
"fanqie/internal/config"
|
||||||
"fanqie/internal/fqapi"
|
"fanqie/internal/fqapi"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"html/template"
|
||||||
"net/http"
|
"net/http"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
@@ -13,7 +15,7 @@ import (
|
|||||||
// HandleVacuum 处理数据库压缩请求
|
// HandleVacuum 处理数据库压缩请求
|
||||||
func HandleVacuum(w http.ResponseWriter, r *http.Request) {
|
func HandleVacuum(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||||
|
|
||||||
// 只允许 POST 请求
|
// 只允许 POST 请求
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
@@ -22,7 +24,7 @@ func HandleVacuum(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 执行 VACUUM
|
// 执行 VACUUM
|
||||||
err := fqapi.VacuumDatabase()
|
err := fqapi.VacuumDatabase()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -32,18 +34,25 @@ func HandleVacuum(w http.ResponseWriter, r *http.Request) {
|
|||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||||
"success": true,
|
"success": true,
|
||||||
"message": "数据库压缩完成",
|
"message": "数据库压缩完成",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 状态页模板(embed 内嵌,动态数据由 html/template 自动转义)
|
||||||
|
//
|
||||||
|
//go:embed templates/status.html
|
||||||
|
var statusHTML string
|
||||||
|
|
||||||
|
var statusTmpl = template.Must(template.New("status").Parse(statusHTML))
|
||||||
|
|
||||||
// HandleStatus 状态页面处理
|
// HandleStatus 状态页面处理
|
||||||
func HandleStatus(w http.ResponseWriter, r *http.Request) {
|
func HandleStatus(w http.ResponseWriter, r *http.Request) {
|
||||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||||
uptime := time.Since(startTime)
|
uptime := time.Since(startTime)
|
||||||
|
|
||||||
// 格式化运行时间
|
// 格式化运行时间
|
||||||
days := int(uptime.Hours() / 24)
|
days := int(uptime.Hours() / 24)
|
||||||
hours := int(uptime.Hours()) % 24
|
hours := int(uptime.Hours()) % 24
|
||||||
@@ -59,10 +68,10 @@ func HandleStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
} else {
|
} else {
|
||||||
uptimeStr = fmt.Sprintf("%d秒", seconds)
|
uptimeStr = fmt.Sprintf("%d秒", seconds)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取签名信息
|
// 获取签名信息
|
||||||
currentSign := algos.GlobalSignatureSwitcher.GetCurrentMethod()
|
currentSign := algos.GlobalSignatureSwitcher.GetCurrentMethod()
|
||||||
|
|
||||||
// 生成签名详情显示
|
// 生成签名详情显示
|
||||||
var signatureDetails string
|
var signatureDetails string
|
||||||
if currentSign == "sign2" {
|
if currentSign == "sign2" {
|
||||||
@@ -70,800 +79,40 @@ func HandleStatus(w http.ResponseWriter, r *http.Request) {
|
|||||||
} else {
|
} else {
|
||||||
signatureDetails = "X-Gorgon + X-Ladon + X-Argus + X-Khronos"
|
signatureDetails = "X-Gorgon + X-Ladon + X-Argus + X-Khronos"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取统计数据
|
// 获取统计数据
|
||||||
stats := getStatsSnapshot()
|
stats := getStatsSnapshot()
|
||||||
|
|
||||||
// 获取设备密钥池状态
|
// 获取设备密钥池状态
|
||||||
poolStatus := getDeviceKeyPoolStatus()
|
poolStatus := getDeviceKeyPoolStatus()
|
||||||
|
|
||||||
html := fmt.Sprintf(`
|
statusTmpl.Execute(w, map[string]interface{}{
|
||||||
<!DOCTYPE html>
|
"NowTime": time.Now().Format("2006-01-02 15:04:05"),
|
||||||
<html>
|
"Uptime": uptimeStr,
|
||||||
<head>
|
"StartTime": startTime.Format("2006-01-02 15:04:05"),
|
||||||
<meta charset="UTF-8">
|
"Signature": signatureDetails,
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
"DBTotal": getDBTotalSize(),
|
||||||
<title>番茄小说API - 运行状态</title>
|
"DBUsed": getDBUsedSize(),
|
||||||
<style>
|
"DBFree": getDBFreeSize(),
|
||||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
"PoolStatus": poolStatus["status"],
|
||||||
body {
|
"PoolTotal": poolStatus["total"],
|
||||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", Arial, sans-serif;
|
"PoolValid": poolStatus["valid"],
|
||||||
background: #f5f5f5;
|
"PoolInvalid": poolStatus["invalid"],
|
||||||
min-height: 100vh;
|
"PoolIndex": poolStatus["current_index"],
|
||||||
padding: 20px;
|
"StatTotal": stats["total"],
|
||||||
}
|
"StatSearch": stats["search"],
|
||||||
.container {
|
"StatDetail": stats["detail"],
|
||||||
max-width: 1200px;
|
"StatCatalog": stats["catalog"],
|
||||||
margin: 0 auto;
|
"StatContent": stats["content"],
|
||||||
}
|
"StatManga": stats["manga"],
|
||||||
.header {
|
"StatAudio": stats["audio"],
|
||||||
text-align: center;
|
"StatVideo": stats["video"],
|
||||||
color: #333;
|
"StatCategory": stats["category"],
|
||||||
margin-bottom: 30px;
|
"CacheCount": getDBCacheCount(),
|
||||||
background: white;
|
"CacheStatus": getCacheStatus(),
|
||||||
padding: 30px;
|
"CleanupStatus": getCleanupStatus(),
|
||||||
border-radius: 8px;
|
"CleanupInterval": getCleanupInterval(),
|
||||||
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)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// getCacheStatus 获取缓存状态
|
// getCacheStatus 获取缓存状态
|
||||||
@@ -960,23 +209,23 @@ func getDBFreeSize() string {
|
|||||||
}
|
}
|
||||||
freeSize, okFree := stats["free_size_bytes"].(int64)
|
freeSize, okFree := stats["free_size_bytes"].(int64)
|
||||||
totalSize, okTotal := stats["total_size_bytes"].(int64)
|
totalSize, okTotal := stats["total_size_bytes"].(int64)
|
||||||
|
|
||||||
if !okFree {
|
if !okFree {
|
||||||
return "未知"
|
return "未知"
|
||||||
}
|
}
|
||||||
|
|
||||||
if freeSize == 0 {
|
if freeSize == 0 {
|
||||||
return "0 B"
|
return "0 B"
|
||||||
}
|
}
|
||||||
|
|
||||||
freeSizeStr := formatBytes(freeSize)
|
freeSizeStr := formatBytes(freeSize)
|
||||||
|
|
||||||
// 如果有总大小,计算并显示百分比
|
// 如果有总大小,计算并显示百分比
|
||||||
if okTotal && totalSize > 0 {
|
if okTotal && totalSize > 0 {
|
||||||
percentage := float64(freeSize) * 100 / float64(totalSize)
|
percentage := float64(freeSize) * 100 / float64(totalSize)
|
||||||
return fmt.Sprintf("%s (%.1f%%)", freeSizeStr, percentage)
|
return fmt.Sprintf("%s (%.1f%%)", freeSizeStr, percentage)
|
||||||
}
|
}
|
||||||
|
|
||||||
return freeSizeStr
|
return freeSizeStr
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -988,18 +237,18 @@ func getDBUsagePercentage() float64 {
|
|||||||
}
|
}
|
||||||
usedSize, okUsed := stats["used_size_bytes"].(int64)
|
usedSize, okUsed := stats["used_size_bytes"].(int64)
|
||||||
totalSize, okTotal := stats["total_size_bytes"].(int64)
|
totalSize, okTotal := stats["total_size_bytes"].(int64)
|
||||||
|
|
||||||
if !okUsed || !okTotal || totalSize == 0 {
|
if !okUsed || !okTotal || totalSize == 0 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
return float64(usedSize) * 100 / float64(totalSize)
|
return float64(usedSize) * 100 / float64(totalSize)
|
||||||
}
|
}
|
||||||
|
|
||||||
// getDeviceKeyPoolStatus 获取设备密钥池状态
|
// getDeviceKeyPoolStatus 获取设备密钥池状态
|
||||||
func getDeviceKeyPoolStatus() map[string]interface{} {
|
func getDeviceKeyPoolStatus() map[string]interface{} {
|
||||||
pool := fqapi.GetDeviceKeyPool()
|
pool := fqapi.GetDeviceKeyPool()
|
||||||
|
|
||||||
if !pool.IsEnabled() {
|
if !pool.IsEnabled() {
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"status": "未启用",
|
"status": "未启用",
|
||||||
@@ -1009,7 +258,7 @@ func getDeviceKeyPoolStatus() map[string]interface{} {
|
|||||||
"current_index": 0,
|
"current_index": 0,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
stats := pool.GetStats()
|
stats := pool.GetStats()
|
||||||
return map[string]interface{}{
|
return map[string]interface{}{
|
||||||
"status": "已启用",
|
"status": "已启用",
|
||||||
@@ -1019,4 +268,3 @@ func getDeviceKeyPoolStatus() map[string]interface{} {
|
|||||||
"current_index": stats["current_index"],
|
"current_index": stats["current_index"],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
+2
-2
@@ -171,12 +171,12 @@ paths:
|
|||||||
example: 0
|
example: 0
|
||||||
- name: tab_type
|
- name: tab_type
|
||||||
in: query
|
in: query
|
||||||
description: 搜索类型,默认 3
|
description: 搜索类型,默认 3;响应 search_tabs 仅保留匹配该值的 tab
|
||||||
schema: { type: integer, default: 3 }
|
schema: { type: integer, default: 3 }
|
||||||
example: 3
|
example: 3
|
||||||
responses:
|
responses:
|
||||||
"200":
|
"200":
|
||||||
description: 搜索结果(上游转发,结构以实际返回为准)
|
description: 搜索结果(search_tabs 已按请求的 tab_type 过滤,仅保留匹配项)
|
||||||
content:
|
content:
|
||||||
application/json:
|
application/json:
|
||||||
schema:
|
schema:
|
||||||
|
|||||||
Reference in new issue
Block a user