♻️ refactor(handlers): status 与 review 页面模板化
- HTML 提取至 templates/status.html、templates/review.html(go:embed 内嵌) - status.go 1022→271 行、review.go 1281→438 行,动态数据全部经 html/template 按上下文自动转义 - 评论循环/作者徽章/贴纸/图片条件渲染翻译为模板 range/if;emojiMap 以 template.JS 注入 - 与旧版渲染输出实测对比:22 条评论结构完全一致;差异仅为 JS 上下文安全转义(& 等)与 html/template 剥除 CSS 注释,均无功能影响 - 其余文件为 gofmt 顺手格式化
This commit is contained in:
1 parent
ad6d28fd85
commit
5bcc8a962e
29 files changed
+1267
-2893
No files matched your search
@@ -132,4 +132,3 @@ func HandleAudio(itemIDs interface{}, toneID interface{}, output interface{}) (s
|
||||
audioLogger.Error(fmt.Sprintf("获取音频失败: code=%v, msg=%s", respCode, errMsg))
|
||||
return BuildErrorResponse(errMsg), nil
|
||||
}
|
||||
|
||||
@@ -379,7 +379,7 @@ func CleanupAllCache() error {
|
||||
freeBytes := freelistCount * pageSize
|
||||
// 阈值:空闲空间超过 5MB 时才执行压缩
|
||||
const vacuumThreshold = 5 * 1024 * 1024 // 5MB
|
||||
|
||||
|
||||
if freeBytes >= vacuumThreshold {
|
||||
cacheLogger.Info(fmt.Sprintf("空闲空间 %.2f MB,开始执行压缩...", float64(freeBytes)/(1024*1024)))
|
||||
_, err = cacheDB.Exec("VACUUM")
|
||||
@@ -550,7 +550,7 @@ func GetDatabaseStats() (map[string]interface{}, error) {
|
||||
if err == nil {
|
||||
stats["page_count"] = pageCount
|
||||
}
|
||||
|
||||
|
||||
err = cacheDB.QueryRow("PRAGMA page_size").Scan(&pageSize)
|
||||
if err == nil {
|
||||
stats["page_size"] = pageSize
|
||||
@@ -589,7 +589,7 @@ func SaveStatistics(stats map[string]int64) error {
|
||||
`), stats["total"], stats["search"], stats["detail"], stats["catalog"],
|
||||
stats["content"], stats["manga"], stats["audio"], stats["video"], stats["category"],
|
||||
time.Now().Unix())
|
||||
|
||||
|
||||
if err != nil {
|
||||
cacheLogger.Error("保存统计数据失败: " + err.Error())
|
||||
return err
|
||||
@@ -605,13 +605,13 @@ func LoadStatistics() (map[string]int64, error) {
|
||||
}
|
||||
|
||||
var total, search, detail, catalog, content, manga, audio, video, category int64
|
||||
|
||||
|
||||
err := cacheDB.QueryRow(`
|
||||
SELECT total_requests, search_requests, detail_requests, catalog_requests,
|
||||
content_requests, manga_requests, audio_requests, video_requests, category_requests
|
||||
FROM statistics WHERE id = 1
|
||||
`).Scan(&total, &search, &detail, &catalog, &content, &manga, &audio, &video, &category)
|
||||
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
// 没有数据,返回空统计
|
||||
return map[string]int64{
|
||||
@@ -619,7 +619,7 @@ func LoadStatistics() (map[string]int64, error) {
|
||||
"content": 0, "manga": 0, "audio": 0, "video": 0, "category": 0,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
if err != nil {
|
||||
cacheLogger.Error("加载统计数据失败: " + err.Error())
|
||||
return nil, err
|
||||
@@ -638,4 +638,4 @@ func LoadStatistics() (map[string]int64, error) {
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ var catalogLogger = common.NewLogger("catalog", "INFO", "")
|
||||
|
||||
// HandleGetCatalog 处理获取书籍目录,目录数据基本不变,缓存 24 小时
|
||||
func HandleGetCatalog(bookID string) (string, error) {
|
||||
return withCache("catalog_" + bookID, 86400, func() (string, error) {
|
||||
return withCache("catalog_"+bookID, 86400, func() (string, error) {
|
||||
return fetchCatalog(bookID)
|
||||
})
|
||||
}
|
||||
@@ -210,4 +210,3 @@ func itemMultiDetail(itemList []string) ([]map[string]interface{}, error) {
|
||||
|
||||
return nil, fmt.Errorf("请求失败")
|
||||
}
|
||||
|
||||
@@ -47,4 +47,3 @@ func fetchCategoryFront(tab interface{}) (string, error) {
|
||||
|
||||
return BuildErrorResponse("获取失败"), nil
|
||||
}
|
||||
|
||||
@@ -59,4 +59,3 @@ func fetchCategoryLanding(categoryID, offset, wordNumber, bookStatus, sortBy int
|
||||
|
||||
return BuildErrorResponse("获取失败"), nil
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ func fetchContentWithRetry(itemID string, textMode, imageMode bool, retryCount i
|
||||
contentLogger.Warning(fmt.Sprintf("已重试 %d 次,尝试备用接口", maxRetries))
|
||||
return tryBackupAPI(itemID, textMode, imageMode)
|
||||
}
|
||||
|
||||
|
||||
// 从设备密钥池获取设备
|
||||
pool := GetDeviceKeyPool()
|
||||
item, err := pool.GetNext()
|
||||
@@ -74,7 +74,7 @@ func fetchContentWithRetry(itemID string, textMode, imageMode bool, retryCount i
|
||||
contentLogger.Error("从设备池获取设备失败: " + err.Error())
|
||||
return `{"code": -1, "msg": "设备池暂无可用设备"}`, err
|
||||
}
|
||||
|
||||
|
||||
header := item.DeviceHeader
|
||||
currentKeyInfo := &KeyInfo{
|
||||
Key: item.Key,
|
||||
@@ -142,7 +142,7 @@ func fetchContentWithRetry(itemID string, textMode, imageMode bool, retryCount i
|
||||
keyVersion, _ := data["key_version"].(float64)
|
||||
if currentKeyInfo != nil && int(keyVersion) != currentKeyInfo.Ver {
|
||||
contentLogger.Warning("密钥版本不匹配,重新获取密钥")
|
||||
|
||||
|
||||
// 更新池中的密钥
|
||||
newKeyInfo, err := GetKey(header)
|
||||
if err == nil {
|
||||
@@ -276,4 +276,3 @@ func tryBackupAPI(itemID string, textMode, imageMode bool) (string, error) {
|
||||
contentLogger.Warning("备用接口1获取正文出错!")
|
||||
return `{"code": -1, "msg": "获取失败"}`, fmt.Errorf("所有接口都失败")
|
||||
}
|
||||
|
||||
@@ -13,7 +13,6 @@ var (
|
||||
parserLogger = common.NewLogger("content_parser", "INFO", "")
|
||||
)
|
||||
|
||||
|
||||
// ContentParser 内容解析器
|
||||
type ContentParser struct {
|
||||
cfg config.ContentConfig
|
||||
@@ -143,13 +142,13 @@ func (p *ContentParser) extractText(content string) string {
|
||||
|
||||
// 拼接结果
|
||||
var result string
|
||||
|
||||
|
||||
// 根据配置决定段落间的换行符
|
||||
separator := "\n"
|
||||
if p.cfg.DoubleNewline {
|
||||
separator = "\n\n"
|
||||
}
|
||||
|
||||
|
||||
if p.cfg.AddParagraphIndent && len(finalResult) > 0 {
|
||||
// 添加段落缩进(两个全角空格)
|
||||
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 {
|
||||
// 标准化img属性
|
||||
content = normalizeImgAttributes(content)
|
||||
|
||||
|
||||
// 解码HTML实体
|
||||
content = decodeHTMLEntities(content)
|
||||
|
||||
|
||||
// 根据配置决定是否移除空行
|
||||
if p.cfg.RemoveBlankLines {
|
||||
// 对HTML内容移除空的<p>标签
|
||||
@@ -184,4 +183,3 @@ func (p *ContentParser) processHTMLMode(content string) string {
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
@@ -57,10 +57,10 @@ func removeBlankLines(content string) string {
|
||||
for strings.Contains(content, "\n\n\n") {
|
||||
content = strings.ReplaceAll(content, "\n\n\n", "\n\n")
|
||||
}
|
||||
|
||||
|
||||
// 移除首尾的空白
|
||||
content = strings.TrimSpace(content)
|
||||
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
@@ -127,22 +127,22 @@ func BuildURL(fullURL string, customParams ...string) string {
|
||||
"os_version=0",
|
||||
"version_code=58932",
|
||||
}
|
||||
|
||||
|
||||
// 添加设备header
|
||||
header := getDeviceHeader()
|
||||
if header != "" {
|
||||
allParams = append(allParams, header)
|
||||
}
|
||||
|
||||
|
||||
// 添加自定义参数
|
||||
allParams = append(allParams, customParams...)
|
||||
|
||||
|
||||
// 合并、拆分、排序
|
||||
joined := strings.Join(allParams, "&")
|
||||
paramList := strings.Split(joined, "&")
|
||||
sort.Strings(paramList)
|
||||
params := strings.Join(paramList, "&")
|
||||
|
||||
|
||||
return fullURL + "?" + params
|
||||
}
|
||||
|
||||
@@ -218,11 +218,11 @@ func parseStringToInt(s string) (int, error) {
|
||||
// 简单实现,避免导入strconv
|
||||
result := 0
|
||||
negative := false
|
||||
|
||||
|
||||
if len(s) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
|
||||
start := 0
|
||||
if s[0] == '-' {
|
||||
negative = true
|
||||
@@ -230,18 +230,18 @@ func parseStringToInt(s string) (int, error) {
|
||||
} else if s[0] == '+' {
|
||||
start = 1
|
||||
}
|
||||
|
||||
|
||||
for i := start; i < len(s); i++ {
|
||||
if s[i] < '0' || s[i] > '9' {
|
||||
break
|
||||
}
|
||||
result = result*10 + int(s[i]-'0')
|
||||
}
|
||||
|
||||
|
||||
if negative {
|
||||
result = -result
|
||||
}
|
||||
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
@@ -250,7 +250,7 @@ func ParseStringParam(param interface{}, defaultVal string) string {
|
||||
if param == nil || param == "" {
|
||||
return defaultVal
|
||||
}
|
||||
|
||||
|
||||
switch v := param.(type) {
|
||||
case string:
|
||||
if v != "" {
|
||||
@@ -262,4 +262,3 @@ func ParseStringParam(param interface{}, defaultVal string) string {
|
||||
}
|
||||
return defaultVal
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ var detailLogger = common.NewLogger("detail", "INFO", "")
|
||||
|
||||
// HandleGetDetail 处理获取书籍详情,详情数据基本不变,缓存 24 小时
|
||||
func HandleGetDetail(bookID string) (string, error) {
|
||||
return withCache("detail_" + bookID, 86400, func() (string, error) {
|
||||
return withCache("detail_"+bookID, 86400, func() (string, error) {
|
||||
return fetchDetail(bookID)
|
||||
})
|
||||
}
|
||||
@@ -58,4 +58,3 @@ func fetchDetail(bookID string) (string, error) {
|
||||
|
||||
return BuildErrorResponse("获取失败"), nil
|
||||
}
|
||||
|
||||
+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
|
||||
func getCustomBT() string {
|
||||
var uptimeSeconds float64
|
||||
|
||||
|
||||
if runtime.GOOS == "linux" {
|
||||
// 在Linux上读取/proc/uptime
|
||||
data, err := os.ReadFile("/proc/uptime")
|
||||
@@ -54,7 +54,7 @@ func getCustomBT() string {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 如果读取失败,使用time.monotonic作为备选
|
||||
if uptimeSeconds == 0 {
|
||||
// Go没有直接的monotonic API,使用启动时间估算
|
||||
@@ -65,17 +65,17 @@ func getCustomBT() string {
|
||||
// 这里可以使用进程启动时间作为近似
|
||||
uptimeSeconds = float64(time.Now().Unix() % 86400)
|
||||
}
|
||||
|
||||
|
||||
return fmt.Sprintf("%d", currentMillis()-int64(uptimeSeconds*1000))
|
||||
}
|
||||
|
||||
// generateDeviceInfo 随机生成设备及操作系统信息
|
||||
func generateDeviceInfo() map[string]interface{} {
|
||||
osVersion := androidVersions[randInt(len(androidVersions))]
|
||||
|
||||
|
||||
// 随机选择品牌
|
||||
deviceBrand := deviceBrands[randInt(len(deviceBrands))]
|
||||
|
||||
|
||||
// 根据品牌选择对应的型号
|
||||
models := brandModels[deviceBrand]
|
||||
deviceModel := models[randInt(len(models))]
|
||||
@@ -88,19 +88,19 @@ func generateDeviceInfo() map[string]interface{} {
|
||||
rand.Read(openUDIDBytes)
|
||||
|
||||
return map[string]interface{}{
|
||||
"os": "Android",
|
||||
"os_version": osVersion[0],
|
||||
"os_api": osVersion[1],
|
||||
"device_model": deviceModel,
|
||||
"device_brand": deviceBrand,
|
||||
"device_manufacturer": deviceBrand,
|
||||
"cpu_abi": "arm64-v8a",
|
||||
"release_build": releaseBuild,
|
||||
"cdid": generateUUID(),
|
||||
"sig_hash": "a4a27c2633195374c15651ffc3c4a497",
|
||||
"openudid": hex.EncodeToString(openUDIDBytes),
|
||||
"clientudid": generateUUID(),
|
||||
"req_id": generateUUID(),
|
||||
"os": "Android",
|
||||
"os_version": osVersion[0],
|
||||
"os_api": osVersion[1],
|
||||
"device_model": deviceModel,
|
||||
"device_brand": deviceBrand,
|
||||
"device_manufacturer": deviceBrand,
|
||||
"cpu_abi": "arm64-v8a",
|
||||
"release_build": releaseBuild,
|
||||
"cdid": generateUUID(),
|
||||
"sig_hash": "a4a27c2633195374c15651ffc3c4a497",
|
||||
"openudid": hex.EncodeToString(openUDIDBytes),
|
||||
"clientudid": generateUUID(),
|
||||
"req_id": generateUUID(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,9 +130,9 @@ func generateOptionalFields() (map[string]interface{}, map[string]int64) {
|
||||
|
||||
genTime := currentMillis()
|
||||
return map[string]interface{}{
|
||||
"rom": rom,
|
||||
"rom_version": fmt.Sprintf("coloros__%s.%s.%s release-keys", part1, part2, part3),
|
||||
"apk_first_install_time": genTime - int64(randInt(365))*86400000,
|
||||
"rom": rom,
|
||||
"rom_version": fmt.Sprintf("coloros__%s.%s.%s release-keys", part1, part2, part3),
|
||||
"apk_first_install_time": genTime - int64(randInt(365))*86400000,
|
||||
}, map[string]int64{
|
||||
"_gen_time": genTime,
|
||||
}
|
||||
@@ -307,7 +307,7 @@ func Register() (string, error) {
|
||||
|
||||
// 生成完整请求体数据
|
||||
data := GenerateFullRequestBody()
|
||||
|
||||
|
||||
// 只记录关键设备信息
|
||||
header := data["header"].(map[string]interface{})
|
||||
logger.Info(fmt.Sprintf("生成设备信息 - 品牌: %s, 型号: %s, 系统: Android %v",
|
||||
@@ -370,7 +370,7 @@ func Register() (string, error) {
|
||||
deviceModel,
|
||||
respData["install_id_str"])
|
||||
|
||||
logger.Info("设备注册成功!" )
|
||||
logger.Info("设备注册成功!")
|
||||
|
||||
// 尝试激活特权
|
||||
tryActivatePremium(header)
|
||||
@@ -381,4 +381,3 @@ func Register() (string, error) {
|
||||
logger.Warning("设备注册失败!")
|
||||
return "", fmt.Errorf("设备注册失败")
|
||||
}
|
||||
|
||||
+184
-185
@@ -1,185 +1,184 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// CM 加密管理器
|
||||
type CM struct {
|
||||
bigC *big.Int // 大素数C
|
||||
bigB int64 // 底数B
|
||||
arryD []byte // 固定密钥
|
||||
thisD [2]*big.Int // 密钥对(私钥, 公钥)
|
||||
thisC []byte // 随机IV
|
||||
}
|
||||
|
||||
// NewCM 创建新的CM实例
|
||||
func NewCM() *CM {
|
||||
// 大素数C
|
||||
bigCStr := "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"
|
||||
bigC := new(big.Int)
|
||||
bigC.SetString(bigCStr, 10)
|
||||
|
||||
// 固定密钥(base64解码)
|
||||
arryD, _ := base64.StdEncoding.DecodeString("rCXGfd2POMGzeiNIgo4iLg==")
|
||||
|
||||
return &CM{
|
||||
bigC: bigC,
|
||||
bigB: 2,
|
||||
arryD: arryD,
|
||||
}
|
||||
}
|
||||
|
||||
// generateKeyPair 生成密钥对
|
||||
func (cm *CM) generateKeyPair() [2]*big.Int {
|
||||
// 生成随机私钥
|
||||
randomBytes := make([]byte, 32)
|
||||
rand.Read(randomBytes)
|
||||
|
||||
x := new(big.Int).SetBytes(randomBytes)
|
||||
x = x.Mod(x, new(big.Int).Sub(cm.bigC, big.NewInt(1)))
|
||||
|
||||
// 计算公钥: y = b^x mod c
|
||||
y := new(big.Int).Exp(big.NewInt(cm.bigB), x, cm.bigC)
|
||||
|
||||
cm.thisD = [2]*big.Int{x, y}
|
||||
return cm.thisD
|
||||
}
|
||||
|
||||
// pairToBytes 将公钥转换为字节数组
|
||||
func (cm *CM) pairToBytes(keyPair [2]*big.Int) []byte {
|
||||
return keyPair[1].Bytes()
|
||||
}
|
||||
|
||||
// randIV 生成随机IV
|
||||
func (cm *CM) randIV() []byte {
|
||||
iv := make([]byte, 16)
|
||||
rand.Read(iv)
|
||||
return iv
|
||||
}
|
||||
|
||||
// encodeAES AES-CBC加密
|
||||
func (cm *CM) encodeAES(key, iv, data []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// PKCS7填充
|
||||
padding := aes.BlockSize - len(data)%aes.BlockSize
|
||||
padText := make([]byte, padding)
|
||||
for i := range padText {
|
||||
padText[i] = byte(padding)
|
||||
}
|
||||
paddedData := append(data, padText...)
|
||||
|
||||
ciphertext := make([]byte, len(paddedData))
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
mode.CryptBlocks(ciphertext, paddedData)
|
||||
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
// decodeAES AES-CBC解密
|
||||
func (cm *CM) decodeAES(key, iv, data []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCDecrypter(block, iv)
|
||||
decrypted := make([]byte, len(data))
|
||||
mode.CryptBlocks(decrypted, data)
|
||||
|
||||
// 移除PKCS7填充
|
||||
padding := int(decrypted[len(decrypted)-1])
|
||||
if padding > len(decrypted) || padding > aes.BlockSize {
|
||||
return nil, fmt.Errorf("无效的填充")
|
||||
}
|
||||
|
||||
return decrypted[:len(decrypted)-padding], nil
|
||||
}
|
||||
|
||||
// ClientHandshake 客户端握手,生成请求头y
|
||||
func (cm *CM) ClientHandshake() string {
|
||||
keyPair := cm.generateKeyPair()
|
||||
cm.thisC = cm.randIV()
|
||||
|
||||
publicKeyBytes := cm.pairToBytes(keyPair)
|
||||
encrypted, _ := cm.encodeAES(cm.arryD, cm.thisC, publicKeyBytes)
|
||||
|
||||
combined := append(cm.thisC, encrypted...)
|
||||
return base64.StdEncoding.EncodeToString(combined)
|
||||
}
|
||||
|
||||
// decryptF 解密函数
|
||||
func (cm *CM) decryptF(peerPublicKey []byte, keyPair [2]*big.Int, iv, data []byte) ([]byte, error) {
|
||||
x := keyPair[0]
|
||||
|
||||
// 计算共享密钥: shared_secret = peer_public_key^x mod c
|
||||
peerPubInt := new(big.Int).SetBytes(peerPublicKey)
|
||||
sharedSecret := new(big.Int).Exp(peerPubInt, x, cm.bigC)
|
||||
|
||||
key := sharedSecret.Bytes()
|
||||
// 确保key长度为32字节
|
||||
if len(key) < 32 {
|
||||
// 前面补0
|
||||
paddedKey := make([]byte, 32)
|
||||
copy(paddedKey[32-len(key):], key)
|
||||
key = paddedKey
|
||||
} else if len(key) > 32 {
|
||||
key = key[:32]
|
||||
}
|
||||
|
||||
return cm.decodeAES(key, iv, data)
|
||||
}
|
||||
|
||||
// Decrypt 解密响应内容
|
||||
func (cm *CM) Decrypt(c, y, content string) (string, error) {
|
||||
// c 应该为 "1" 表示启用加密
|
||||
// y 是服务器返回的公钥
|
||||
// content 是加密的内容
|
||||
|
||||
if c != "1" || y == "" {
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// 解码content
|
||||
contentDecoded, err := base64.StdEncoding.DecodeString(content)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if len(contentDecoded) < 16 {
|
||||
return "", fmt.Errorf("内容太短")
|
||||
}
|
||||
|
||||
// 提取IV和数据
|
||||
iv := contentDecoded[:16]
|
||||
data := contentDecoded[16:]
|
||||
|
||||
// 解码服务器公钥
|
||||
peerPublicKey, err := base64.StdEncoding.DecodeString(y)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 检查密钥对是否已初始化
|
||||
if cm.thisD[0] == nil {
|
||||
return "", fmt.Errorf("密钥对未初始化")
|
||||
}
|
||||
|
||||
// 解密
|
||||
decrypted, err := cm.decryptF(peerPublicKey, cm.thisD, iv, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(decrypted), nil
|
||||
}
|
||||
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"math/big"
|
||||
)
|
||||
|
||||
// CM 加密管理器
|
||||
type CM struct {
|
||||
bigC *big.Int // 大素数C
|
||||
bigB int64 // 底数B
|
||||
arryD []byte // 固定密钥
|
||||
thisD [2]*big.Int // 密钥对(私钥, 公钥)
|
||||
thisC []byte // 随机IV
|
||||
}
|
||||
|
||||
// NewCM 创建新的CM实例
|
||||
func NewCM() *CM {
|
||||
// 大素数C
|
||||
bigCStr := "2410312426921032588552076022197566074856950548502459942654116941958108831682612228890093858261341614673227141477904012196503648957050582631942730706805009223062734745341073406696246014589361659774041027169249453200378729434170325843778659198143763193776859869524088940195577346119843545301547043747207749969763750084308926339295559968882457872412993810129130294592999947926365264059284647209730384947211681434464714438488520940127459844288859336526896320919633919"
|
||||
bigC := new(big.Int)
|
||||
bigC.SetString(bigCStr, 10)
|
||||
|
||||
// 固定密钥(base64解码)
|
||||
arryD, _ := base64.StdEncoding.DecodeString("rCXGfd2POMGzeiNIgo4iLg==")
|
||||
|
||||
return &CM{
|
||||
bigC: bigC,
|
||||
bigB: 2,
|
||||
arryD: arryD,
|
||||
}
|
||||
}
|
||||
|
||||
// generateKeyPair 生成密钥对
|
||||
func (cm *CM) generateKeyPair() [2]*big.Int {
|
||||
// 生成随机私钥
|
||||
randomBytes := make([]byte, 32)
|
||||
rand.Read(randomBytes)
|
||||
|
||||
x := new(big.Int).SetBytes(randomBytes)
|
||||
x = x.Mod(x, new(big.Int).Sub(cm.bigC, big.NewInt(1)))
|
||||
|
||||
// 计算公钥: y = b^x mod c
|
||||
y := new(big.Int).Exp(big.NewInt(cm.bigB), x, cm.bigC)
|
||||
|
||||
cm.thisD = [2]*big.Int{x, y}
|
||||
return cm.thisD
|
||||
}
|
||||
|
||||
// pairToBytes 将公钥转换为字节数组
|
||||
func (cm *CM) pairToBytes(keyPair [2]*big.Int) []byte {
|
||||
return keyPair[1].Bytes()
|
||||
}
|
||||
|
||||
// randIV 生成随机IV
|
||||
func (cm *CM) randIV() []byte {
|
||||
iv := make([]byte, 16)
|
||||
rand.Read(iv)
|
||||
return iv
|
||||
}
|
||||
|
||||
// encodeAES AES-CBC加密
|
||||
func (cm *CM) encodeAES(key, iv, data []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// PKCS7填充
|
||||
padding := aes.BlockSize - len(data)%aes.BlockSize
|
||||
padText := make([]byte, padding)
|
||||
for i := range padText {
|
||||
padText[i] = byte(padding)
|
||||
}
|
||||
paddedData := append(data, padText...)
|
||||
|
||||
ciphertext := make([]byte, len(paddedData))
|
||||
mode := cipher.NewCBCEncrypter(block, iv)
|
||||
mode.CryptBlocks(ciphertext, paddedData)
|
||||
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
// decodeAES AES-CBC解密
|
||||
func (cm *CM) decodeAES(key, iv, data []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
mode := cipher.NewCBCDecrypter(block, iv)
|
||||
decrypted := make([]byte, len(data))
|
||||
mode.CryptBlocks(decrypted, data)
|
||||
|
||||
// 移除PKCS7填充
|
||||
padding := int(decrypted[len(decrypted)-1])
|
||||
if padding > len(decrypted) || padding > aes.BlockSize {
|
||||
return nil, fmt.Errorf("无效的填充")
|
||||
}
|
||||
|
||||
return decrypted[:len(decrypted)-padding], nil
|
||||
}
|
||||
|
||||
// ClientHandshake 客户端握手,生成请求头y
|
||||
func (cm *CM) ClientHandshake() string {
|
||||
keyPair := cm.generateKeyPair()
|
||||
cm.thisC = cm.randIV()
|
||||
|
||||
publicKeyBytes := cm.pairToBytes(keyPair)
|
||||
encrypted, _ := cm.encodeAES(cm.arryD, cm.thisC, publicKeyBytes)
|
||||
|
||||
combined := append(cm.thisC, encrypted...)
|
||||
return base64.StdEncoding.EncodeToString(combined)
|
||||
}
|
||||
|
||||
// decryptF 解密函数
|
||||
func (cm *CM) decryptF(peerPublicKey []byte, keyPair [2]*big.Int, iv, data []byte) ([]byte, error) {
|
||||
x := keyPair[0]
|
||||
|
||||
// 计算共享密钥: shared_secret = peer_public_key^x mod c
|
||||
peerPubInt := new(big.Int).SetBytes(peerPublicKey)
|
||||
sharedSecret := new(big.Int).Exp(peerPubInt, x, cm.bigC)
|
||||
|
||||
key := sharedSecret.Bytes()
|
||||
// 确保key长度为32字节
|
||||
if len(key) < 32 {
|
||||
// 前面补0
|
||||
paddedKey := make([]byte, 32)
|
||||
copy(paddedKey[32-len(key):], key)
|
||||
key = paddedKey
|
||||
} else if len(key) > 32 {
|
||||
key = key[:32]
|
||||
}
|
||||
|
||||
return cm.decodeAES(key, iv, data)
|
||||
}
|
||||
|
||||
// Decrypt 解密响应内容
|
||||
func (cm *CM) Decrypt(c, y, content string) (string, error) {
|
||||
// c 应该为 "1" 表示启用加密
|
||||
// y 是服务器返回的公钥
|
||||
// content 是加密的内容
|
||||
|
||||
if c != "1" || y == "" {
|
||||
return content, nil
|
||||
}
|
||||
|
||||
// 解码content
|
||||
contentDecoded, err := base64.StdEncoding.DecodeString(content)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
if len(contentDecoded) < 16 {
|
||||
return "", fmt.Errorf("内容太短")
|
||||
}
|
||||
|
||||
// 提取IV和数据
|
||||
iv := contentDecoded[:16]
|
||||
data := contentDecoded[16:]
|
||||
|
||||
// 解码服务器公钥
|
||||
peerPublicKey, err := base64.StdEncoding.DecodeString(y)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
// 检查密钥对是否已初始化
|
||||
if cm.thisD[0] == nil {
|
||||
return "", fmt.Errorf("密钥对未初始化")
|
||||
}
|
||||
|
||||
// 解密
|
||||
decrypted, err := cm.decryptF(peerPublicKey, cm.thisD, iv, data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(decrypted), nil
|
||||
}
|
||||
+229
-230
@@ -1,230 +1,229 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// EmojiManager 表情管理器
|
||||
type EmojiManager struct {
|
||||
emojiMap map[string]string // 表情文本 -> 图片URL的映射
|
||||
mutex sync.RWMutex
|
||||
lastUpdate time.Time
|
||||
cacheExpiry time.Duration
|
||||
}
|
||||
|
||||
// DouyinEmojiResponse 抖音表情API响应结构
|
||||
type DouyinEmojiResponse struct {
|
||||
EmojiList []DouyinEmoji `json:"emoji_list"`
|
||||
}
|
||||
|
||||
// DouyinEmoji 抖音单个表情结构
|
||||
type DouyinEmoji struct {
|
||||
OriginURI string `json:"origin_uri"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Hide int `json:"hide"`
|
||||
EmojiURL struct {
|
||||
URI string `json:"uri"`
|
||||
URLList []string `json:"url_list"`
|
||||
} `json:"emoji_url"`
|
||||
}
|
||||
|
||||
// LocalEmojiData 本地表情数据结构
|
||||
type LocalEmojiData struct {
|
||||
Version int `json:"version"`
|
||||
Size int `json:"size"`
|
||||
Datas map[string]string `json:"datas"`
|
||||
}
|
||||
|
||||
var (
|
||||
globalEmojiManager *EmojiManager
|
||||
emojiOnce sync.Once
|
||||
)
|
||||
|
||||
// GetEmojiManager 获取全局表情管理器实例
|
||||
func GetEmojiManager() *EmojiManager {
|
||||
emojiOnce.Do(func() {
|
||||
globalEmojiManager = &EmojiManager{
|
||||
emojiMap: make(map[string]string),
|
||||
cacheExpiry: 24 * time.Hour, // 缓存24小时
|
||||
}
|
||||
// 初始化时加载表情
|
||||
globalEmojiManager.LoadEmojis()
|
||||
})
|
||||
return globalEmojiManager
|
||||
}
|
||||
|
||||
// LoadEmojis 加载表情映射(优先API,其次本地)
|
||||
func (em *EmojiManager) LoadEmojis() error {
|
||||
em.mutex.Lock()
|
||||
defer em.mutex.Unlock()
|
||||
|
||||
// 检查缓存是否过期
|
||||
if time.Since(em.lastUpdate) < em.cacheExpiry && len(em.emojiMap) > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
newMap := make(map[string]string)
|
||||
|
||||
// 1. 先尝试从抖音API获取表情
|
||||
apiEmojis, err := em.fetchDouyinEmojis()
|
||||
if err == nil && len(apiEmojis) > 0 {
|
||||
for displayName, url := range apiEmojis {
|
||||
newMap[displayName] = url
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 加载本地表情作为补充
|
||||
localEmojis, err := em.loadLocalEmojis()
|
||||
if err == nil {
|
||||
for displayName, url := range localEmojis {
|
||||
// 如果API中没有,则使用本地的
|
||||
if _, exists := newMap[displayName]; !exists {
|
||||
newMap[displayName] = url
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 更新缓存
|
||||
if len(newMap) > 0 {
|
||||
em.emojiMap = newMap
|
||||
em.lastUpdate = time.Now()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchDouyinEmojis 从抖音API获取表情映射
|
||||
func (em *EmojiManager) fetchDouyinEmojis() (map[string]string, error) {
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
resp, err := client.Get("https://www.douyin.com/aweme/v1/web/emoji/list")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取抖音表情API失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("抖音表情API返回状态码: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取响应失败: %w", err)
|
||||
}
|
||||
|
||||
var apiResp DouyinEmojiResponse
|
||||
if err := json.Unmarshal(body, &apiResp); err != nil {
|
||||
return nil, fmt.Errorf("解析JSON失败: %w", err)
|
||||
}
|
||||
|
||||
emojiMap := make(map[string]string)
|
||||
for _, emoji := range apiResp.EmojiList {
|
||||
if len(emoji.EmojiURL.URLList) > 0 {
|
||||
// 使用第一个URL
|
||||
emojiMap[emoji.DisplayName] = emoji.EmojiURL.URLList[0]
|
||||
}
|
||||
}
|
||||
|
||||
return emojiMap, nil
|
||||
}
|
||||
|
||||
// loadLocalEmojis 从本地文件加载表情映射
|
||||
func (em *EmojiManager) loadLocalEmojis() (map[string]string, error) {
|
||||
// 读取 data.json
|
||||
dataPath := filepath.Join("emoji", "data.json")
|
||||
data, err := ioutil.ReadFile(dataPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取emoji/data.json失败: %w", err)
|
||||
}
|
||||
|
||||
var localData LocalEmojiData
|
||||
if err := json.Unmarshal(data, &localData); err != nil {
|
||||
return nil, fmt.Errorf("解析emoji/data.json失败: %w", err)
|
||||
}
|
||||
|
||||
emojiMap := make(map[string]string)
|
||||
for id, displayName := range localData.Datas {
|
||||
// 生成本地图片路径:emoji/images/emoji_dr_{id}.png
|
||||
// 转换为相对URL路径
|
||||
localPath := fmt.Sprintf("/emoji/images/emoji_dr_%s.png", id)
|
||||
emojiMap[displayName] = localPath
|
||||
}
|
||||
|
||||
return emojiMap, nil
|
||||
}
|
||||
|
||||
// GetEmojiURL 获取表情图片URL
|
||||
func (em *EmojiManager) GetEmojiURL(displayName string) (string, bool) {
|
||||
em.mutex.RLock()
|
||||
defer em.mutex.RUnlock()
|
||||
|
||||
url, exists := em.emojiMap[displayName]
|
||||
return url, exists
|
||||
}
|
||||
|
||||
// GetAllEmojis 获取所有表情映射(用于生成JavaScript代码)
|
||||
func (em *EmojiManager) GetAllEmojis() map[string]string {
|
||||
em.mutex.RLock()
|
||||
defer em.mutex.RUnlock()
|
||||
|
||||
// 返回副本
|
||||
result := make(map[string]string, len(em.emojiMap))
|
||||
for k, v := range em.emojiMap {
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// RefreshEmojis 手动刷新表情缓存
|
||||
func (em *EmojiManager) RefreshEmojis() error {
|
||||
em.mutex.Lock()
|
||||
em.lastUpdate = time.Time{} // 重置更新时间
|
||||
em.mutex.Unlock()
|
||||
|
||||
return em.LoadEmojis()
|
||||
}
|
||||
|
||||
// CheckLocalEmojiFiles 检查本地表情文件是否存在
|
||||
func CheckLocalEmojiFiles() error {
|
||||
dataPath := filepath.Join("emoji", "data.json")
|
||||
if _, err := os.Stat(dataPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("emoji/data.json 文件不存在")
|
||||
}
|
||||
|
||||
imagesDir := filepath.Join("emoji", "images")
|
||||
if _, err := os.Stat(imagesDir); os.IsNotExist(err) {
|
||||
return fmt.Errorf("emoji/images 目录不存在")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplaceEmojisInText 替换文本中的表情为HTML img标签
|
||||
func ReplaceEmojisInText(text string) string {
|
||||
em := GetEmojiManager()
|
||||
|
||||
// 匹配 [表情] 格式
|
||||
result := text
|
||||
for displayName, url := range em.GetAllEmojis() {
|
||||
// 转义特殊字符
|
||||
escapedName := strings.ReplaceAll(displayName, "[", "\\[")
|
||||
escapedName = strings.ReplaceAll(escapedName, "]", "\\]")
|
||||
|
||||
// 替换为 img 标签
|
||||
imgTag := fmt.Sprintf(`<img src="%s" class="emoji-img" alt="%s" />`, url, displayName)
|
||||
result = strings.ReplaceAll(result, displayName, imgTag)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// EmojiManager 表情管理器
|
||||
type EmojiManager struct {
|
||||
emojiMap map[string]string // 表情文本 -> 图片URL的映射
|
||||
mutex sync.RWMutex
|
||||
lastUpdate time.Time
|
||||
cacheExpiry time.Duration
|
||||
}
|
||||
|
||||
// DouyinEmojiResponse 抖音表情API响应结构
|
||||
type DouyinEmojiResponse struct {
|
||||
EmojiList []DouyinEmoji `json:"emoji_list"`
|
||||
}
|
||||
|
||||
// DouyinEmoji 抖音单个表情结构
|
||||
type DouyinEmoji struct {
|
||||
OriginURI string `json:"origin_uri"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Hide int `json:"hide"`
|
||||
EmojiURL struct {
|
||||
URI string `json:"uri"`
|
||||
URLList []string `json:"url_list"`
|
||||
} `json:"emoji_url"`
|
||||
}
|
||||
|
||||
// LocalEmojiData 本地表情数据结构
|
||||
type LocalEmojiData struct {
|
||||
Version int `json:"version"`
|
||||
Size int `json:"size"`
|
||||
Datas map[string]string `json:"datas"`
|
||||
}
|
||||
|
||||
var (
|
||||
globalEmojiManager *EmojiManager
|
||||
emojiOnce sync.Once
|
||||
)
|
||||
|
||||
// GetEmojiManager 获取全局表情管理器实例
|
||||
func GetEmojiManager() *EmojiManager {
|
||||
emojiOnce.Do(func() {
|
||||
globalEmojiManager = &EmojiManager{
|
||||
emojiMap: make(map[string]string),
|
||||
cacheExpiry: 24 * time.Hour, // 缓存24小时
|
||||
}
|
||||
// 初始化时加载表情
|
||||
globalEmojiManager.LoadEmojis()
|
||||
})
|
||||
return globalEmojiManager
|
||||
}
|
||||
|
||||
// LoadEmojis 加载表情映射(优先API,其次本地)
|
||||
func (em *EmojiManager) LoadEmojis() error {
|
||||
em.mutex.Lock()
|
||||
defer em.mutex.Unlock()
|
||||
|
||||
// 检查缓存是否过期
|
||||
if time.Since(em.lastUpdate) < em.cacheExpiry && len(em.emojiMap) > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
newMap := make(map[string]string)
|
||||
|
||||
// 1. 先尝试从抖音API获取表情
|
||||
apiEmojis, err := em.fetchDouyinEmojis()
|
||||
if err == nil && len(apiEmojis) > 0 {
|
||||
for displayName, url := range apiEmojis {
|
||||
newMap[displayName] = url
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 加载本地表情作为补充
|
||||
localEmojis, err := em.loadLocalEmojis()
|
||||
if err == nil {
|
||||
for displayName, url := range localEmojis {
|
||||
// 如果API中没有,则使用本地的
|
||||
if _, exists := newMap[displayName]; !exists {
|
||||
newMap[displayName] = url
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 更新缓存
|
||||
if len(newMap) > 0 {
|
||||
em.emojiMap = newMap
|
||||
em.lastUpdate = time.Now()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// fetchDouyinEmojis 从抖音API获取表情映射
|
||||
func (em *EmojiManager) fetchDouyinEmojis() (map[string]string, error) {
|
||||
client := &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
}
|
||||
|
||||
resp, err := client.Get("https://www.douyin.com/aweme/v1/web/emoji/list")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取抖音表情API失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("抖音表情API返回状态码: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取响应失败: %w", err)
|
||||
}
|
||||
|
||||
var apiResp DouyinEmojiResponse
|
||||
if err := json.Unmarshal(body, &apiResp); err != nil {
|
||||
return nil, fmt.Errorf("解析JSON失败: %w", err)
|
||||
}
|
||||
|
||||
emojiMap := make(map[string]string)
|
||||
for _, emoji := range apiResp.EmojiList {
|
||||
if len(emoji.EmojiURL.URLList) > 0 {
|
||||
// 使用第一个URL
|
||||
emojiMap[emoji.DisplayName] = emoji.EmojiURL.URLList[0]
|
||||
}
|
||||
}
|
||||
|
||||
return emojiMap, nil
|
||||
}
|
||||
|
||||
// loadLocalEmojis 从本地文件加载表情映射
|
||||
func (em *EmojiManager) loadLocalEmojis() (map[string]string, error) {
|
||||
// 读取 data.json
|
||||
dataPath := filepath.Join("emoji", "data.json")
|
||||
data, err := ioutil.ReadFile(dataPath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取emoji/data.json失败: %w", err)
|
||||
}
|
||||
|
||||
var localData LocalEmojiData
|
||||
if err := json.Unmarshal(data, &localData); err != nil {
|
||||
return nil, fmt.Errorf("解析emoji/data.json失败: %w", err)
|
||||
}
|
||||
|
||||
emojiMap := make(map[string]string)
|
||||
for id, displayName := range localData.Datas {
|
||||
// 生成本地图片路径:emoji/images/emoji_dr_{id}.png
|
||||
// 转换为相对URL路径
|
||||
localPath := fmt.Sprintf("/emoji/images/emoji_dr_%s.png", id)
|
||||
emojiMap[displayName] = localPath
|
||||
}
|
||||
|
||||
return emojiMap, nil
|
||||
}
|
||||
|
||||
// GetEmojiURL 获取表情图片URL
|
||||
func (em *EmojiManager) GetEmojiURL(displayName string) (string, bool) {
|
||||
em.mutex.RLock()
|
||||
defer em.mutex.RUnlock()
|
||||
|
||||
url, exists := em.emojiMap[displayName]
|
||||
return url, exists
|
||||
}
|
||||
|
||||
// GetAllEmojis 获取所有表情映射(用于生成JavaScript代码)
|
||||
func (em *EmojiManager) GetAllEmojis() map[string]string {
|
||||
em.mutex.RLock()
|
||||
defer em.mutex.RUnlock()
|
||||
|
||||
// 返回副本
|
||||
result := make(map[string]string, len(em.emojiMap))
|
||||
for k, v := range em.emojiMap {
|
||||
result[k] = v
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// RefreshEmojis 手动刷新表情缓存
|
||||
func (em *EmojiManager) RefreshEmojis() error {
|
||||
em.mutex.Lock()
|
||||
em.lastUpdate = time.Time{} // 重置更新时间
|
||||
em.mutex.Unlock()
|
||||
|
||||
return em.LoadEmojis()
|
||||
}
|
||||
|
||||
// CheckLocalEmojiFiles 检查本地表情文件是否存在
|
||||
func CheckLocalEmojiFiles() error {
|
||||
dataPath := filepath.Join("emoji", "data.json")
|
||||
if _, err := os.Stat(dataPath); os.IsNotExist(err) {
|
||||
return fmt.Errorf("emoji/data.json 文件不存在")
|
||||
}
|
||||
|
||||
imagesDir := filepath.Join("emoji", "images")
|
||||
if _, err := os.Stat(imagesDir); os.IsNotExist(err) {
|
||||
return fmt.Errorf("emoji/images 目录不存在")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReplaceEmojisInText 替换文本中的表情为HTML img标签
|
||||
func ReplaceEmojisInText(text string) string {
|
||||
em := GetEmojiManager()
|
||||
|
||||
// 匹配 [表情] 格式
|
||||
result := text
|
||||
for displayName, url := range em.GetAllEmojis() {
|
||||
// 转义特殊字符
|
||||
escapedName := strings.ReplaceAll(displayName, "[", "\\[")
|
||||
escapedName = strings.ReplaceAll(escapedName, "]", "\\]")
|
||||
|
||||
// 替换为 img 标签
|
||||
imgTag := fmt.Sprintf(`<img src="%s" class="emoji-img" alt="%s" />`, url, displayName)
|
||||
result = strings.ReplaceAll(result, displayName, imgTag)
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
@@ -114,4 +114,3 @@ func ContentRequest(urlStr string, options map[string]interface{}) (*common.Clie
|
||||
client := common.NewHTTPClient()
|
||||
return client.Request(urlStr, options)
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ var itemSummaryLogger = common.NewLogger("item_summary", "INFO", "")
|
||||
|
||||
// HandleItemSummary 处理获取章节摘要,章节摘要数据基本不变,缓存 24 小时
|
||||
func HandleItemSummary(itemIDs, bookID string) (string, error) {
|
||||
return withCache("item_summary_" + bookID + "_" + itemIDs, 86400, func() (string, error) {
|
||||
return withCache("item_summary_"+bookID+"_"+itemIDs, 86400, func() (string, error) {
|
||||
return fetchItemSummary(itemIDs, bookID)
|
||||
})
|
||||
}
|
||||
@@ -48,4 +48,3 @@ func fetchItemSummary(itemIDs, bookID string) (string, error) {
|
||||
|
||||
return BuildErrorResponse("获取失败"), nil
|
||||
}
|
||||
|
||||
+18
-19
@@ -71,14 +71,14 @@ func getMangaWithRetry(itemID string, showHTML bool, urlOutputMode string, retry
|
||||
mangaLogger.Warning(fmt.Sprintf("已重试 %d 次,获取漫画失败", maxRetries))
|
||||
return nil, fmt.Errorf("已重试 %d 次,所有设备均失败", maxRetries)
|
||||
}
|
||||
|
||||
|
||||
// 1. 从设备密钥池获取设备
|
||||
pool := GetDeviceKeyPool()
|
||||
item, err := pool.GetNext()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("从设备池获取设备失败: %w", err)
|
||||
}
|
||||
|
||||
|
||||
header := item.DeviceHeader
|
||||
keyInfo := &KeyInfo{
|
||||
Key: item.Key,
|
||||
@@ -171,18 +171,18 @@ func getMangaWithRetry(itemID string, showHTML bool, urlOutputMode string, retry
|
||||
// 是漫画,决定输出模式
|
||||
// 优先级:URL参数 > 配置文件 > 默认值
|
||||
outputMode := "proxy" // 默认值
|
||||
|
||||
|
||||
// 从配置文件读取
|
||||
cfg := config.GetConfig()
|
||||
if cfg != nil && cfg.Fanqie.Manga.OutputMode != "" {
|
||||
outputMode = cfg.Fanqie.Manga.OutputMode
|
||||
}
|
||||
|
||||
|
||||
// URL参数优先级最高
|
||||
if urlOutputMode != "" {
|
||||
outputMode = urlOutputMode
|
||||
}
|
||||
|
||||
|
||||
// 解析漫画图片(传入keyInfo用于解密模式)
|
||||
images, err := parseMangaImages(decrypted, showHTML, outputMode, itemID, keyInfo)
|
||||
if err != nil {
|
||||
@@ -279,7 +279,7 @@ func buildMangaResponse(images []ImageResult, showHTML bool) interface{} {
|
||||
"content": htmlContent.String(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return map[string]interface{}{
|
||||
"images": images,
|
||||
}
|
||||
@@ -289,7 +289,7 @@ func buildMangaResponse(images []ImageResult, showHTML bool) interface{} {
|
||||
func processURLMode(mangaData *MangaData) []ImageResult {
|
||||
baseDomain := "https://p6-novel.byteimg.com/origin/"
|
||||
validPath := detectMangaPath(baseDomain, mangaData.PicInfos[0].Md5)
|
||||
|
||||
|
||||
images := make([]ImageResult, len(mangaData.PicInfos))
|
||||
for i, pic := range mangaData.PicInfos {
|
||||
imageURL := baseDomain + validPath + pic.Md5
|
||||
@@ -309,7 +309,7 @@ func processProxyMode(mangaData *MangaData, itemID string) []ImageResult {
|
||||
images := make([]ImageResult, len(mangaData.PicInfos))
|
||||
for i, pic := range mangaData.PicInfos {
|
||||
cacheKey := fmt.Sprintf("%s_%d", itemID, i)
|
||||
|
||||
|
||||
// 存储图片信息到缓存
|
||||
mangaCacheMutex.Lock()
|
||||
mangaImageCache[cacheKey] = &MangaImageInfo{
|
||||
@@ -320,7 +320,7 @@ func processProxyMode(mangaData *MangaData, itemID string) []ImageResult {
|
||||
CachedAt: time.Now(),
|
||||
}
|
||||
mangaCacheMutex.Unlock()
|
||||
|
||||
|
||||
// 返回短的代理URL
|
||||
imageData := fmt.Sprintf("/manga/image/%s/%d", itemID, i)
|
||||
images[i] = ImageResult{
|
||||
@@ -390,7 +390,7 @@ func processDataURIMode(mangaData *MangaData) []ImageResult {
|
||||
|
||||
// Base64编码图片数据
|
||||
base64Data := base64.StdEncoding.EncodeToString(decryptedData)
|
||||
|
||||
|
||||
// Data URI模式:返回完整的Base64编码
|
||||
mimeType := fmt.Sprintf("image/%s", format)
|
||||
if format == "jpg" {
|
||||
@@ -542,31 +542,31 @@ func decryptImage(encryptedData, keyBytes []byte) ([]byte, error) {
|
||||
func detectMangaPath(baseDomain, firstMd5 string) string {
|
||||
// 优先尝试 novel-images/
|
||||
testURL := baseDomain + "novel-images/" + firstMd5
|
||||
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: 8 * time.Second,
|
||||
}
|
||||
|
||||
|
||||
resp, err := client.Get(testURL)
|
||||
if err != nil {
|
||||
// 请求失败,使用novel-pic/
|
||||
return "novel-pic/"
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
|
||||
// 读取响应内容
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return "novel-pic/"
|
||||
}
|
||||
|
||||
|
||||
// 检查是否为JSON响应(错误响应通常是JSON)
|
||||
var jsonData interface{}
|
||||
if json.Unmarshal(body, &jsonData) == nil {
|
||||
// 是JSON,说明路径无效,切换到novel-pic/
|
||||
return "novel-pic/"
|
||||
}
|
||||
|
||||
|
||||
// 不是JSON,说明返回的是图片,路径有效
|
||||
return "novel-images/"
|
||||
}
|
||||
@@ -605,12 +605,11 @@ func getImageFormat(data []byte, url string) string {
|
||||
}
|
||||
|
||||
// WEBP: RIFF...WEBP
|
||||
if bytes.HasPrefix(data, []byte{0x52, 0x49, 0x46, 0x46}) &&
|
||||
len(data) >= 12 &&
|
||||
bytes.Equal(data[8:12], []byte{0x57, 0x45, 0x42, 0x50}) {
|
||||
if bytes.HasPrefix(data, []byte{0x52, 0x49, 0x46, 0x46}) &&
|
||||
len(data) >= 12 &&
|
||||
bytes.Equal(data[8:12], []byte{0x57, 0x45, 0x42, 0x50}) {
|
||||
return "webp"
|
||||
}
|
||||
|
||||
return "png"
|
||||
}
|
||||
|
||||
@@ -1,72 +1,71 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HandleMangaImageProxy 处理漫画图片代理请求
|
||||
func HandleMangaImageProxy(itemID string, index int) ([]byte, string, error) {
|
||||
// 从缓存获取图片信息
|
||||
cacheKey := fmt.Sprintf("%s_%d", itemID, index)
|
||||
|
||||
mangaCacheMutex.RLock()
|
||||
imageInfo, exists := mangaImageCache[cacheKey]
|
||||
mangaCacheMutex.RUnlock()
|
||||
|
||||
if !exists {
|
||||
return nil, "", fmt.Errorf("图片信息不存在,请先调用 /manga 接口")
|
||||
}
|
||||
|
||||
// 检查缓存是否过期(5分钟)
|
||||
if time.Since(imageInfo.CachedAt) > 5*time.Minute {
|
||||
// 清理过期缓存
|
||||
mangaCacheMutex.Lock()
|
||||
delete(mangaImageCache, cacheKey)
|
||||
mangaCacheMutex.Unlock()
|
||||
return nil, "", fmt.Errorf("图片信息已过期,请重新调用 /manga 接口")
|
||||
}
|
||||
|
||||
// 下载加密图片
|
||||
encryptedData, err := downloadImageWithRetry(imageInfo.PicURL, 2)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %w", err)
|
||||
}
|
||||
|
||||
// 解密图片
|
||||
keyBytes, err := hex.DecodeString(imageInfo.EncryptKey)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("密钥解码失败: %w", err)
|
||||
}
|
||||
|
||||
decryptedData, err := decryptImage(encryptedData, keyBytes)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("解密失败: %w", err)
|
||||
}
|
||||
|
||||
// 识别格式
|
||||
format := getImageFormat(decryptedData, imageInfo.PicURL)
|
||||
|
||||
// 返回图片数据和MIME类型
|
||||
mimeType := fmt.Sprintf("image/%s", format)
|
||||
if format == "jpg" {
|
||||
mimeType = "image/jpeg"
|
||||
}
|
||||
|
||||
return decryptedData, mimeType, nil
|
||||
}
|
||||
|
||||
// CleanExpiredMangaCache 清理过期的漫画图片缓存
|
||||
func CleanExpiredMangaCache() {
|
||||
mangaCacheMutex.Lock()
|
||||
defer mangaCacheMutex.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
for key, info := range mangaImageCache {
|
||||
if now.Sub(info.CachedAt) > 5*time.Minute {
|
||||
delete(mangaImageCache, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HandleMangaImageProxy 处理漫画图片代理请求
|
||||
func HandleMangaImageProxy(itemID string, index int) ([]byte, string, error) {
|
||||
// 从缓存获取图片信息
|
||||
cacheKey := fmt.Sprintf("%s_%d", itemID, index)
|
||||
|
||||
mangaCacheMutex.RLock()
|
||||
imageInfo, exists := mangaImageCache[cacheKey]
|
||||
mangaCacheMutex.RUnlock()
|
||||
|
||||
if !exists {
|
||||
return nil, "", fmt.Errorf("图片信息不存在,请先调用 /manga 接口")
|
||||
}
|
||||
|
||||
// 检查缓存是否过期(5分钟)
|
||||
if time.Since(imageInfo.CachedAt) > 5*time.Minute {
|
||||
// 清理过期缓存
|
||||
mangaCacheMutex.Lock()
|
||||
delete(mangaImageCache, cacheKey)
|
||||
mangaCacheMutex.Unlock()
|
||||
return nil, "", fmt.Errorf("图片信息已过期,请重新调用 /manga 接口")
|
||||
}
|
||||
|
||||
// 下载加密图片
|
||||
encryptedData, err := downloadImageWithRetry(imageInfo.PicURL, 2)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("下载图片失败: %w", err)
|
||||
}
|
||||
|
||||
// 解密图片
|
||||
keyBytes, err := hex.DecodeString(imageInfo.EncryptKey)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("密钥解码失败: %w", err)
|
||||
}
|
||||
|
||||
decryptedData, err := decryptImage(encryptedData, keyBytes)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("解密失败: %w", err)
|
||||
}
|
||||
|
||||
// 识别格式
|
||||
format := getImageFormat(decryptedData, imageInfo.PicURL)
|
||||
|
||||
// 返回图片数据和MIME类型
|
||||
mimeType := fmt.Sprintf("image/%s", format)
|
||||
if format == "jpg" {
|
||||
mimeType = "image/jpeg"
|
||||
}
|
||||
|
||||
return decryptedData, mimeType, nil
|
||||
}
|
||||
|
||||
// CleanExpiredMangaCache 清理过期的漫画图片缓存
|
||||
func CleanExpiredMangaCache() {
|
||||
mangaCacheMutex.Lock()
|
||||
defer mangaCacheMutex.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
for key, info := range mangaImageCache {
|
||||
if now.Sub(info.CachedAt) > 5*time.Minute {
|
||||
delete(mangaImageCache, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func MultiContent(itemIDs interface{}, bookID string, textMode, imageMode, ignor
|
||||
if err != nil {
|
||||
return `{"code": -1, "msg": "从设备池获取设备失败"}`, err
|
||||
}
|
||||
|
||||
|
||||
header := item.DeviceHeader
|
||||
currentKeyInfo := &KeyInfo{
|
||||
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) {
|
||||
return MultiContent(itemIDs, bookID, textMode, imageMode, ignoreFailed, 0)
|
||||
}
|
||||
|
||||
@@ -218,4 +218,3 @@ func fetchMultiDetail(bookID interface{}) (string, error) {
|
||||
resultBytes, _ := json.Marshal(response)
|
||||
return string(resultBytes), nil
|
||||
}
|
||||
|
||||
@@ -246,4 +246,3 @@ func GetKeyInfo() *KeyInfo {
|
||||
func init() {
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
}
|
||||
|
||||
@@ -97,4 +97,3 @@ func filterSearchTabs(respJSON map[string]interface{}, tabType int) {
|
||||
respJSON["search_tabs"] = filtered
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,4 +193,3 @@ func Decrypt(encryptedStr string) ([]byte, error) {
|
||||
}
|
||||
return TTDecrypt(encryptedData)
|
||||
}
|
||||
|
||||
+17
-18
@@ -144,10 +144,10 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
// 解析失败,返回空对象
|
||||
return map[string]interface{}{}
|
||||
}
|
||||
|
||||
|
||||
// 构建精简的返回结果,只包含关键字段
|
||||
result := make(map[string]interface{})
|
||||
|
||||
|
||||
// 提取关键字段
|
||||
if videoID, ok := videoModel["video_id"].(string); ok {
|
||||
result["video_id"] = videoID
|
||||
@@ -158,16 +158,16 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
if posterURL, ok := videoModel["poster_url"].(string); ok {
|
||||
result["poster_url"] = posterURL
|
||||
}
|
||||
|
||||
|
||||
// 处理 video_list
|
||||
if videoList, ok := videoModel["video_list"].(map[string]interface{}); ok {
|
||||
processedVideoList := make(map[string]interface{})
|
||||
|
||||
|
||||
for quality, qualityData := range videoList {
|
||||
if qualityMap, ok := qualityData.(map[string]interface{}); ok {
|
||||
// 只保留关键字段
|
||||
qualityInfo := make(map[string]interface{})
|
||||
|
||||
|
||||
if definition, ok := qualityMap["definition"].(string); ok {
|
||||
qualityInfo["definition"] = definition
|
||||
}
|
||||
@@ -189,39 +189,39 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
if fps, ok := qualityMap["fps"].(float64); ok {
|
||||
qualityInfo["fps"] = int(fps)
|
||||
}
|
||||
|
||||
|
||||
// 解码 main_url
|
||||
if mainURL, ok := qualityMap["main_url"].(string); ok {
|
||||
if decoded, err := base64.StdEncoding.DecodeString(mainURL); err == nil {
|
||||
qualityInfo["main_url"] = string(decoded)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 解码 backup_url_1
|
||||
if backupURL, ok := qualityMap["backup_url_1"].(string); ok {
|
||||
if decoded, err := base64.StdEncoding.DecodeString(backupURL); err == nil {
|
||||
qualityInfo["backup_url_1"] = string(decoded)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
processedVideoList[quality] = qualityInfo
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
result["video_list"] = processedVideoList
|
||||
}
|
||||
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// formatDuration 将秒数转换为可读的时间格式
|
||||
func formatDuration(seconds float64) string {
|
||||
totalSeconds := int(math.Round(seconds))
|
||||
|
||||
|
||||
hours := totalSeconds / 3600
|
||||
minutes := (totalSeconds % 3600) / 60
|
||||
secs := totalSeconds % 60
|
||||
|
||||
|
||||
if hours > 0 {
|
||||
return fmt.Sprintf("%d小时%d分%d秒", hours, minutes, secs)
|
||||
} else if minutes > 0 {
|
||||
@@ -236,17 +236,17 @@ func formatFileSize(bytes float64) string {
|
||||
if bytes < unit {
|
||||
return fmt.Sprintf("%.0f B", bytes)
|
||||
}
|
||||
|
||||
|
||||
kb := bytes / unit
|
||||
if kb < unit {
|
||||
return fmt.Sprintf("%.2f KB", kb)
|
||||
}
|
||||
|
||||
|
||||
mb := kb / unit
|
||||
if mb < unit {
|
||||
return fmt.Sprintf("%.2f MB", mb)
|
||||
}
|
||||
|
||||
|
||||
gb := mb / unit
|
||||
return fmt.Sprintf("%.2f GB", gb)
|
||||
}
|
||||
@@ -255,12 +255,11 @@ func formatFileSize(bytes float64) string {
|
||||
func formatBitrate(bitrate float64) string {
|
||||
const unit = 1000.0
|
||||
kbps := bitrate / unit
|
||||
|
||||
|
||||
if kbps < unit {
|
||||
return fmt.Sprintf("%.0f Kbps", kbps)
|
||||
}
|
||||
|
||||
|
||||
mbps := kbps / unit
|
||||
return fmt.Sprintf("%.2f Mbps", mbps)
|
||||
}
|
||||
|
||||
@@ -103,4 +103,3 @@ func HandleMultiDetail(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
fmt.Fprint(w, result)
|
||||
}
|
||||
|
||||
@@ -41,4 +41,3 @@ func HandleCategoryLanding(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
fmt.Fprint(w, result)
|
||||
}
|
||||
|
||||
@@ -20,9 +20,9 @@ func HandleContent(w http.ResponseWriter, r *http.Request) {
|
||||
itemID := params["item_id"]
|
||||
|
||||
// 获取URL参数(支持动态覆盖配置)
|
||||
textMode := r.URL.Query().Get("text_mode") // 1=纯文本模式
|
||||
imageMode := r.URL.Query().Get("image_mode") // 0=移除图片, 1=保留图片
|
||||
reviewParam := r.URL.Query().Get("review") // 1=启用段评, 0=禁用段评
|
||||
textMode := r.URL.Query().Get("text_mode") // 1=纯文本模式
|
||||
imageMode := r.URL.Query().Get("image_mode") // 0=移除图片, 1=保留图片
|
||||
reviewParam := r.URL.Query().Get("review") // 1=启用段评, 0=禁用段评
|
||||
|
||||
result, err := fqapi.HandleGetContent(itemID, textMode, imageMode)
|
||||
if err != nil {
|
||||
@@ -103,19 +103,19 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
||||
if err := fqapi.ParseJSON([]byte(jsonResult), &resultData); err != nil {
|
||||
return jsonResult
|
||||
}
|
||||
|
||||
|
||||
// 获取 data 字段
|
||||
data, ok := resultData["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
return jsonResult
|
||||
}
|
||||
|
||||
|
||||
// 获取 content 字段
|
||||
content, ok := data["content"].(string)
|
||||
if !ok || content == "" {
|
||||
return jsonResult
|
||||
}
|
||||
|
||||
|
||||
// 从响应数据中提取 book_id (data.novel_data.book_id)
|
||||
bookID := ""
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 获取基础 URL
|
||||
cfg := config.GetConfig()
|
||||
baseURL := ""
|
||||
@@ -136,7 +136,7 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
||||
}
|
||||
port := cfg.Server.Port
|
||||
scheme := "http"
|
||||
|
||||
|
||||
// 检查是否来自外部请求
|
||||
if r.Host != "" {
|
||||
baseURL = scheme + "://" + r.Host
|
||||
@@ -144,24 +144,23 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
||||
baseURL = scheme + "://" + host + ":" + port
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 生成带段评标记的内容
|
||||
newContent, err := fqapi.GenerateParagraphsWithComments(itemID, bookID, content, baseURL)
|
||||
if err != nil {
|
||||
// 如果失败,返回原始内容
|
||||
return jsonResult
|
||||
}
|
||||
|
||||
|
||||
// 替换 content 字段
|
||||
data["content"] = newContent
|
||||
resultData["data"] = data
|
||||
|
||||
|
||||
// 重新序列化为 JSON
|
||||
newJSON, err := fqapi.ToJSON(resultData)
|
||||
if err != nil {
|
||||
return jsonResult
|
||||
}
|
||||
|
||||
|
||||
return newJSON
|
||||
}
|
||||
|
||||
@@ -13,32 +13,31 @@ func HandleMangaImageProxy(w http.ResponseWriter, r *http.Request) {
|
||||
// 从URL路径提取参数: /manga/image/{itemID}/{index}
|
||||
path := strings.TrimPrefix(r.URL.Path, "/manga/image/")
|
||||
parts := strings.Split(path, "/")
|
||||
|
||||
|
||||
if len(parts) != 2 {
|
||||
http.Error(w, "Invalid URL format. Expected: /manga/image/{itemID}/{index}", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
itemID := parts[0]
|
||||
index, err := strconv.Atoi(parts[1])
|
||||
if err != nil {
|
||||
http.Error(w, "Invalid index parameter", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 获取解密后的图片数据
|
||||
imageData, mimeType, err := fqapi.HandleMangaImageProxy(itemID, index)
|
||||
if err != nil {
|
||||
http.Error(w, fmt.Sprintf("Failed to get image: %s", err.Error()), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 设置响应头
|
||||
w.Header().Set("Content-Type", mimeType)
|
||||
w.Header().Set("Cache-Control", "public, max-age=3600") // 缓存1小时
|
||||
w.Header().Set("Content-Length", strconv.Itoa(len(imageData)))
|
||||
|
||||
|
||||
// 返回图片数据
|
||||
w.Write(imageData)
|
||||
}
|
||||
|
||||
+81
-925
File diff suppressed because it is too large.
Load diff
+54
-806
@@ -1,11 +1,13 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"fanqie/internal/algos"
|
||||
"fanqie/internal/config"
|
||||
"fanqie/internal/fqapi"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
@@ -13,7 +15,7 @@ import (
|
||||
// HandleVacuum 处理数据库压缩请求
|
||||
func HandleVacuum(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
|
||||
|
||||
// 只允许 POST 请求
|
||||
if r.Method != http.MethodPost {
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
@@ -22,7 +24,7 @@ func HandleVacuum(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
// 执行 VACUUM
|
||||
err := fqapi.VacuumDatabase()
|
||||
if err != nil {
|
||||
@@ -32,18 +34,25 @@ func HandleVacuum(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"success": true,
|
||||
"message": "数据库压缩完成",
|
||||
})
|
||||
}
|
||||
|
||||
// 状态页模板(embed 内嵌,动态数据由 html/template 自动转义)
|
||||
//
|
||||
//go:embed templates/status.html
|
||||
var statusHTML string
|
||||
|
||||
var statusTmpl = template.Must(template.New("status").Parse(statusHTML))
|
||||
|
||||
// HandleStatus 状态页面处理
|
||||
func HandleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
uptime := time.Since(startTime)
|
||||
|
||||
|
||||
// 格式化运行时间
|
||||
days := int(uptime.Hours() / 24)
|
||||
hours := int(uptime.Hours()) % 24
|
||||
@@ -59,10 +68,10 @@ func HandleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
} else {
|
||||
uptimeStr = fmt.Sprintf("%d秒", seconds)
|
||||
}
|
||||
|
||||
|
||||
// 获取签名信息
|
||||
currentSign := algos.GlobalSignatureSwitcher.GetCurrentMethod()
|
||||
|
||||
|
||||
// 生成签名详情显示
|
||||
var signatureDetails string
|
||||
if currentSign == "sign2" {
|
||||
@@ -70,800 +79,40 @@ func HandleStatus(w http.ResponseWriter, r *http.Request) {
|
||||
} else {
|
||||
signatureDetails = "X-Gorgon + X-Ladon + X-Argus + X-Khronos"
|
||||
}
|
||||
|
||||
|
||||
// 获取统计数据
|
||||
stats := getStatsSnapshot()
|
||||
|
||||
|
||||
// 获取设备密钥池状态
|
||||
poolStatus := getDeviceKeyPoolStatus()
|
||||
|
||||
html := fmt.Sprintf(`
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>番茄小说API - 运行状态</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", Arial, sans-serif;
|
||||
background: #f5f5f5;
|
||||
min-height: 100vh;
|
||||
padding: 20px;
|
||||
}
|
||||
.container {
|
||||
max-width: 1200px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
.header {
|
||||
text-align: center;
|
||||
color: #333;
|
||||
margin-bottom: 30px;
|
||||
background: white;
|
||||
padding: 30px;
|
||||
border-radius: 8px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.08);
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 2em;
|
||||
margin-bottom: 8px;
|
||||
color: #1a1a1a;
|
||||
}
|
||||
.header p {
|
||||
font-size: 1em;
|
||||
color: #666;
|
||||
}
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
|
||||
gap: 20px;
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
.card {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.08);
|
||||
border: 1px solid #e0e0e0;
|
||||
}
|
||||
.card-title {
|
||||
font-size: 1.1em;
|
||||
color: #333;
|
||||
margin-bottom: 15px;
|
||||
font-weight: 600;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 2px solid #f0f0f0;
|
||||
}
|
||||
.stat-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid #f5f5f5;
|
||||
}
|
||||
.stat-item:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
.stat-label {
|
||||
color: #666;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
.stat-value {
|
||||
color: #1a1a1a;
|
||||
font-weight: 600;
|
||||
font-size: 0.95em;
|
||||
}
|
||||
.api-docs {
|
||||
background: white;
|
||||
border-radius: 8px;
|
||||
padding: 20px;
|
||||
box-shadow: 0 2px 4px rgba(0,0,0,0.08);
|
||||
border: 1px solid #e0e0e0;
|
||||
}
|
||||
.api-section {
|
||||
margin-bottom: 25px;
|
||||
}
|
||||
.api-section:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.api-section-title {
|
||||
color: #1a1a1a;
|
||||
font-size: 1em;
|
||||
font-weight: 600;
|
||||
margin-bottom: 12px;
|
||||
padding-left: 20px;
|
||||
position: relative;
|
||||
}
|
||||
.api-section-title::before {
|
||||
content: "▸";
|
||||
position: absolute;
|
||||
left: 0;
|
||||
color: #666;
|
||||
}
|
||||
.api-endpoint {
|
||||
background: #fafafa;
|
||||
border: 1px solid #e8e8e8;
|
||||
border-radius: 6px;
|
||||
padding: 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
.api-endpoint:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.api-method {
|
||||
display: inline-block;
|
||||
background: #2196F3;
|
||||
color: white;
|
||||
padding: 2px 8px;
|
||||
border-radius: 3px;
|
||||
font-size: 0.75em;
|
||||
font-weight: 600;
|
||||
margin-right: 8px;
|
||||
}
|
||||
.api-path {
|
||||
font-family: "Consolas", "Monaco", monospace;
|
||||
font-size: 0.9em;
|
||||
color: #333;
|
||||
font-weight: 500;
|
||||
}
|
||||
.api-desc {
|
||||
color: #666;
|
||||
font-size: 0.85em;
|
||||
margin-top: 6px;
|
||||
padding-left: 4px;
|
||||
}
|
||||
.api-params {
|
||||
margin-top: 8px;
|
||||
padding-left: 4px;
|
||||
}
|
||||
.param-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
font-size: 0.8em;
|
||||
margin: 4px 0;
|
||||
color: #555;
|
||||
}
|
||||
.param-name {
|
||||
font-family: "Consolas", "Monaco", monospace;
|
||||
color: #e91e63;
|
||||
font-weight: 500;
|
||||
margin-right: 6px;
|
||||
}
|
||||
.param-required {
|
||||
background: #ff9800;
|
||||
color: white;
|
||||
padding: 1px 5px;
|
||||
border-radius: 2px;
|
||||
font-size: 0.75em;
|
||||
margin-right: 6px;
|
||||
}
|
||||
.param-optional {
|
||||
background: #2196F3;
|
||||
color: white;
|
||||
padding: 1px 5px;
|
||||
border-radius: 2px;
|
||||
font-size: 0.75em;
|
||||
margin-right: 6px;
|
||||
}
|
||||
.param-desc {
|
||||
color: #777;
|
||||
}
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 2px 8px;
|
||||
border-radius: 12px;
|
||||
font-size: 0.75em;
|
||||
font-weight: 600;
|
||||
margin-left: 8px;
|
||||
}
|
||||
.badge-success {
|
||||
background: #d4edda;
|
||||
color: #155724;
|
||||
}
|
||||
.badge-info {
|
||||
background: #d1ecf1;
|
||||
color: #0c5460;
|
||||
}
|
||||
.badge-warning {
|
||||
background: #fff3cd;
|
||||
color: #856404;
|
||||
}
|
||||
.badge-clickable {
|
||||
cursor: pointer;
|
||||
transition: all 0.2s;
|
||||
}
|
||||
.badge-clickable:hover {
|
||||
background: #ffc107;
|
||||
color: #000;
|
||||
transform: scale(1.05);
|
||||
}
|
||||
.badge-clickable:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
.toast {
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
padding: 15px 20px;
|
||||
background: #333;
|
||||
color: white;
|
||||
border-radius: 6px;
|
||||
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
|
||||
z-index: 9999;
|
||||
animation: slideIn 0.3s ease-out;
|
||||
max-width: 300px;
|
||||
}
|
||||
.toast.success {
|
||||
background: #4caf50;
|
||||
}
|
||||
.toast.error {
|
||||
background: #f44336;
|
||||
}
|
||||
@keyframes slideIn {
|
||||
from {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
to {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@keyframes slideOut {
|
||||
from {
|
||||
transform: translateX(0);
|
||||
opacity: 1;
|
||||
}
|
||||
to {
|
||||
transform: translateX(400px);
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
<script type="text/javascript">
|
||||
let autoRefreshInterval;
|
||||
|
||||
window.onload = function() {
|
||||
startAutoRefresh();
|
||||
}
|
||||
|
||||
function startAutoRefresh() {
|
||||
autoRefreshInterval = setInterval(function() {
|
||||
fetch(window.location.href)
|
||||
.then(response => response.text())
|
||||
.then(html => {
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, 'text/html');
|
||||
const newBody = doc.querySelector('body');
|
||||
document.body.innerHTML = newBody.innerHTML;
|
||||
})
|
||||
.catch(err => console.error('刷新失败:', err));
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function stopAutoRefresh() {
|
||||
if (autoRefreshInterval) {
|
||||
clearInterval(autoRefreshInterval);
|
||||
}
|
||||
}
|
||||
|
||||
function showToast(message, type = 'success') {
|
||||
const toast = document.createElement('div');
|
||||
toast.className = 'toast ' + type;
|
||||
toast.textContent = message;
|
||||
document.body.appendChild(toast);
|
||||
|
||||
setTimeout(() => {
|
||||
toast.style.animation = 'slideOut 0.3s ease-out';
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(toast);
|
||||
}, 300);
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
function performVacuum() {
|
||||
stopAutoRefresh();
|
||||
|
||||
const badge = event.target;
|
||||
const originalText = badge.textContent;
|
||||
badge.textContent = '压缩中...';
|
||||
badge.style.cursor = 'wait';
|
||||
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const key = urlParams.get('key');
|
||||
const vacuumUrl = key ? '/vacuum?key=' + encodeURIComponent(key) : '/vacuum';
|
||||
|
||||
fetch(vacuumUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
showToast(data.message, 'success');
|
||||
setTimeout(() => {
|
||||
location.reload();
|
||||
}, 1000);
|
||||
} else {
|
||||
showToast(data.message, 'error');
|
||||
badge.textContent = originalText;
|
||||
badge.style.cursor = 'pointer';
|
||||
startAutoRefresh();
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
showToast('压缩失败: ' + err.message, 'error');
|
||||
badge.textContent = originalText;
|
||||
badge.style.cursor = 'pointer';
|
||||
startAutoRefresh();
|
||||
});
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div class="header">
|
||||
<h1>番茄小说API</h1>
|
||||
<p>运行状态监控面板</p>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<div class="card">
|
||||
<div class="card-title">● 运行状态</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">服务器时间</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">运行时长</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">启动时间</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item" style="flex-direction: column; align-items: flex-start;">
|
||||
<span class="stat-label" style="margin-bottom: 8px;">签名方法</span>
|
||||
<span class="stat-value" style="font-size: 13px; line-height: 1.6;">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">数据库大小</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">已用空间</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">空闲空间</span>
|
||||
<span class="stat-value">%s <span class="badge badge-warning badge-clickable" onclick="performVacuum()" title="点击立即压缩数据库">立即压缩</span></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">◉ 设备密钥池</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">池状态</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">总设备数</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">有效设备</span>
|
||||
<span class="stat-value">%d <span class="badge badge-success">可用</span></span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">无效设备</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">当前索引</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">■ 请求统计</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">总请求数</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">搜索请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">详情请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">目录请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">内容请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">漫画请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">音频请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">视频请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">分类请求</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<div class="card-title">◆ 缓存统计</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">正文缓存数</span>
|
||||
<span class="stat-value">%d</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">正文缓存</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">自动清理</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
<div class="stat-item">
|
||||
<span class="stat-label">清理间隔</span>
|
||||
<span class="stat-value">%s</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-docs">
|
||||
<div class="card-title">◈ API 接口文档</div>
|
||||
|
||||
<!-- 书籍相关 -->
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">书籍相关</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/search</span></div>
|
||||
<div class="api-desc">◆ 搜索书籍</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">query</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">搜索关键字</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">offset</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">偏移量,默认0</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">tab_type</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">类型,默认3</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/detail</span></div>
|
||||
<div class="api-desc">◆ 获取书籍详情</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">book_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">书籍ID</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/catalog</span></div>
|
||||
<div class="api-desc">◆ 获取书籍目录</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">book_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">书籍ID</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/multi-detail</span></div>
|
||||
<div class="api-desc">◆ 批量获取书籍详情</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">book_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">书籍ID列表,逗号分隔</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 内容相关 -->
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">内容相关</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/content</span></div>
|
||||
<div class="api-desc">◆ 获取章节正文内容</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID,支持路径参数或查询参数</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">text_mode</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">纯文本模式:1/true=纯文本,0/false=HTML</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">image_mode</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">图片处理:1/true=保留图片,0/false=移除图片</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">review</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">段评功能:1=启用,0=禁用</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/multi-content</span></div>
|
||||
<div class="api-desc">◆ 批量获取多个章节正文</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">book_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">书籍ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_ids</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID列表,多个ID用逗号分隔,如:123,456,789</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">text_mode</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">纯文本模式:1/true=纯文本,0/false=HTML</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">image_mode</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">图片处理:1/true=保留图片,0/false=移除图片</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">ignore_failed</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">忽略失败章节:1/true=忽略,0/false=不忽略</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/item-summary</span></div>
|
||||
<div class="api-desc">◆ 获取章节摘要信息</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">book_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">书籍ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_ids</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID列表,逗号分隔</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 段评相关 -->
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">段评相关</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/review</span></div>
|
||||
<div class="api-desc">◆ 获取段落评论、回复</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">book_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">书籍ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">para</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">段落索引(从0开始)</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">comment_id</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">评论ID(获取回复时需要)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/review_html</span></div>
|
||||
<div class="api-desc">◆ 获取段落评论HTML页面</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">book_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">书籍ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">para</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">段落索引(从0开始)</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 多媒体 -->
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">多媒体</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/manga</span></div>
|
||||
<div class="api-desc">◆ 获取漫画内容</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_ids</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">output</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">输出格式:url/proxy/data_uri,默认url</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/audio</span></div>
|
||||
<div class="api-desc">◆ 获取音频信息</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_ids</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">tone_id</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">音色ID,默认1</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/video</span></div>
|
||||
<div class="api-desc">◆ 获取视频信息</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">item_ids</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">章节ID</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 分类 -->
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">分类</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/category-front</span></div>
|
||||
<div class="api-desc">◆ 获取分类首页</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">tab</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">标签页,默认0</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/category-landing</span></div>
|
||||
<div class="api-desc">◆ 获取分类详情页</div>
|
||||
<div class="api-params">
|
||||
<div class="param-item">
|
||||
<span class="param-name">category_id</span>
|
||||
<span class="param-required">必需</span>
|
||||
<span class="param-desc">分类ID</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">offset</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">偏移量,默认0</span>
|
||||
</div>
|
||||
<div class="param-item">
|
||||
<span class="param-name">limit</span>
|
||||
<span class="param-optional">可选</span>
|
||||
<span class="param-desc">每页数量,默认20</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 系统 -->
|
||||
<div class="api-section">
|
||||
<div class="api-section-title">系统</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/status</span></div>
|
||||
<div class="api-desc">◆ 系统状态页面(当前页面)</div>
|
||||
</div>
|
||||
|
||||
<div class="api-endpoint">
|
||||
<div><span class="api-method">GET</span><span class="api-path">/self-info</span></div>
|
||||
<div class="api-desc">◆ 设备信息(包含敏感数据)</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
`,
|
||||
time.Now().Format("2006-01-02 15:04:05"),
|
||||
uptimeStr,
|
||||
startTime.Format("2006-01-02 15:04:05"),
|
||||
signatureDetails,
|
||||
getDBTotalSize(),
|
||||
getDBUsedSize(),
|
||||
getDBFreeSize(),
|
||||
poolStatus["status"],
|
||||
poolStatus["total"],
|
||||
poolStatus["valid"],
|
||||
poolStatus["invalid"],
|
||||
poolStatus["current_index"],
|
||||
stats["total"],
|
||||
stats["search"],
|
||||
stats["detail"],
|
||||
stats["catalog"],
|
||||
stats["content"],
|
||||
stats["manga"],
|
||||
stats["audio"],
|
||||
stats["video"],
|
||||
stats["category"],
|
||||
getDBCacheCount(),
|
||||
getCacheStatus(),
|
||||
getCleanupStatus(),
|
||||
getCleanupInterval(),
|
||||
)
|
||||
fmt.Fprint(w, html)
|
||||
|
||||
statusTmpl.Execute(w, map[string]interface{}{
|
||||
"NowTime": time.Now().Format("2006-01-02 15:04:05"),
|
||||
"Uptime": uptimeStr,
|
||||
"StartTime": startTime.Format("2006-01-02 15:04:05"),
|
||||
"Signature": signatureDetails,
|
||||
"DBTotal": getDBTotalSize(),
|
||||
"DBUsed": getDBUsedSize(),
|
||||
"DBFree": getDBFreeSize(),
|
||||
"PoolStatus": poolStatus["status"],
|
||||
"PoolTotal": poolStatus["total"],
|
||||
"PoolValid": poolStatus["valid"],
|
||||
"PoolInvalid": poolStatus["invalid"],
|
||||
"PoolIndex": poolStatus["current_index"],
|
||||
"StatTotal": stats["total"],
|
||||
"StatSearch": stats["search"],
|
||||
"StatDetail": stats["detail"],
|
||||
"StatCatalog": stats["catalog"],
|
||||
"StatContent": stats["content"],
|
||||
"StatManga": stats["manga"],
|
||||
"StatAudio": stats["audio"],
|
||||
"StatVideo": stats["video"],
|
||||
"StatCategory": stats["category"],
|
||||
"CacheCount": getDBCacheCount(),
|
||||
"CacheStatus": getCacheStatus(),
|
||||
"CleanupStatus": getCleanupStatus(),
|
||||
"CleanupInterval": getCleanupInterval(),
|
||||
})
|
||||
}
|
||||
|
||||
// getCacheStatus 获取缓存状态
|
||||
@@ -960,23 +209,23 @@ func getDBFreeSize() string {
|
||||
}
|
||||
freeSize, okFree := stats["free_size_bytes"].(int64)
|
||||
totalSize, okTotal := stats["total_size_bytes"].(int64)
|
||||
|
||||
|
||||
if !okFree {
|
||||
return "未知"
|
||||
}
|
||||
|
||||
|
||||
if freeSize == 0 {
|
||||
return "0 B"
|
||||
}
|
||||
|
||||
|
||||
freeSizeStr := formatBytes(freeSize)
|
||||
|
||||
|
||||
// 如果有总大小,计算并显示百分比
|
||||
if okTotal && totalSize > 0 {
|
||||
percentage := float64(freeSize) * 100 / float64(totalSize)
|
||||
return fmt.Sprintf("%s (%.1f%%)", freeSizeStr, percentage)
|
||||
}
|
||||
|
||||
|
||||
return freeSizeStr
|
||||
}
|
||||
|
||||
@@ -988,18 +237,18 @@ func getDBUsagePercentage() float64 {
|
||||
}
|
||||
usedSize, okUsed := stats["used_size_bytes"].(int64)
|
||||
totalSize, okTotal := stats["total_size_bytes"].(int64)
|
||||
|
||||
|
||||
if !okUsed || !okTotal || totalSize == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
|
||||
return float64(usedSize) * 100 / float64(totalSize)
|
||||
}
|
||||
|
||||
// getDeviceKeyPoolStatus 获取设备密钥池状态
|
||||
func getDeviceKeyPoolStatus() map[string]interface{} {
|
||||
pool := fqapi.GetDeviceKeyPool()
|
||||
|
||||
|
||||
if !pool.IsEnabled() {
|
||||
return map[string]interface{}{
|
||||
"status": "未启用",
|
||||
@@ -1009,7 +258,7 @@ func getDeviceKeyPoolStatus() map[string]interface{} {
|
||||
"current_index": 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
stats := pool.GetStats()
|
||||
return map[string]interface{}{
|
||||
"status": "已启用",
|
||||
@@ -1019,4 +268,3 @@ func getDeviceKeyPoolStatus() map[string]interface{} {
|
||||
"current_index": stats["current_index"],
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user