♻️ 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)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user