✨ feat(api): 统一响应格式并完善参数体系与文档
- 正文参数支持语义值(plain/html/keep/remove)与别名(img_mode/review_mode),URL 参数优先于配置 - 修复纯文本被段评强制包回 HTML、HTML 模式段评注入失效的问题 - 修复 PKCS7 填充弱校验导致漫画/正文偶发解密乱码返回 200 的问题 - 搜索结果展平:去 search_tabs 层与 selected_tab_idx/server_ab_params,提升 has_more/next_offset - 全接口解包字符串形式的 JSON 字段(category_schema 等),缓存出口幂等处理 - 序列化关闭 HTML 转义,video/audio 播放链接可直接复制播放 - video 响应透传 CENC 加密状态(key_seed/kid/encryption_method) - 新增 gzip 中间件,JSON/文本响应压缩约 81%,二进制透传 - 漫画默认输出模式改为 proxy(url 模式链接 404 且内容加密不可用) - openapi.yaml:补全 23 个路径参数定义、tab_type 完整枚举、CDN 签名说明,示例更新
This commit is contained in:
1 parent
bfb4290c15
commit
1a4997e031
25 files changed
+489
-199
No files matched your search
@@ -1,7 +1,6 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fanqie/internal/common"
|
||||
"fmt"
|
||||
)
|
||||
@@ -118,8 +117,7 @@ func HandleAudio(itemIDs interface{}, toneID interface{}, output interface{}) (s
|
||||
}
|
||||
}
|
||||
|
||||
resultBytes, _ := json.Marshal(respJSON)
|
||||
return string(resultBytes), nil
|
||||
return marshalNoEscape(UnwrapJSONStrings(respJSON)), nil
|
||||
}
|
||||
|
||||
// 返回错误信息
|
||||
|
||||
@@ -259,7 +259,9 @@ func isCacheEnabled() bool {
|
||||
// ponytail: 空参等防御分支若漏到此处,其错误 JSON 也会被缓存到 TTL 到期——handler 层 validateParams 已拦截
|
||||
func withCache(key string, ttl int, fetch func() (string, error)) (string, error) {
|
||||
if c := GetCache(key); c != "" {
|
||||
return c, nil
|
||||
// 旧缓存可能存有未解包的 JSON 字符串字段,出口幂等解包
|
||||
// (对新写入的已解包数据无影响)
|
||||
return reencodeUnwrapped(c), nil
|
||||
}
|
||||
result, err := fetch()
|
||||
if err == nil {
|
||||
|
||||
@@ -52,8 +52,8 @@ func fetchCatalog(bookID string) (string, error) {
|
||||
delete(data, "catalog_data")
|
||||
}
|
||||
|
||||
// 重新序列化
|
||||
resultBytes, err := json.Marshal(respJSON)
|
||||
// 重新序列化(解包 JSON 字符串字段)
|
||||
resultBytes, err := json.Marshal(UnwrapJSONStrings(respJSON))
|
||||
if err != nil {
|
||||
return BuildErrorResponse("序列化失败"), err
|
||||
}
|
||||
@@ -130,8 +130,7 @@ func offShelfCatalog(bookID string) (string, error) {
|
||||
},
|
||||
}
|
||||
|
||||
resultBytes, _ := json.Marshal(response)
|
||||
return string(resultBytes), nil
|
||||
return marshalNoEscape(UnwrapJSONStrings(response)), nil
|
||||
}
|
||||
|
||||
// itemMultiDetail 批量获取章节详情
|
||||
|
||||
@@ -42,7 +42,7 @@ func fetchCategoryFront(tab interface{}) (string, error) {
|
||||
}
|
||||
|
||||
if code, ok := respJSON["code"].(float64); ok && code == 0 {
|
||||
return resp.Text, nil
|
||||
return reencodeUnwrapped(resp.Text), nil
|
||||
}
|
||||
|
||||
return BuildErrorResponse("获取失败"), nil
|
||||
|
||||
@@ -54,7 +54,7 @@ func fetchCategoryLanding(categoryID, offset, wordNumber, bookStatus, sortBy int
|
||||
}
|
||||
|
||||
if code, ok := respJSON["code"].(float64); ok && code == 0 {
|
||||
return resp.Text, nil
|
||||
return reencodeUnwrapped(resp.Text), nil
|
||||
}
|
||||
|
||||
return BuildErrorResponse("获取失败"), nil
|
||||
|
||||
@@ -22,9 +22,9 @@ func HandleGetContent(itemID string, textMode, imageMode interface{}) (string, e
|
||||
return `{"code": -1, "msg": "需要参数 item_id"}`, nil
|
||||
}
|
||||
|
||||
// 参数转换
|
||||
textModeBool := parseBoolParam(textMode)
|
||||
imageModeBool := parseBoolParamDefault(imageMode, true)
|
||||
// 参数转换(URL 参数优先,未传时回退配置)
|
||||
textModeBool := parseBoolParamDefault(textMode, getContentConfig().RemoveHTMLTags)
|
||||
imageModeBool := parseBoolParamDefault(imageMode, !getContentConfig().RemoveImages)
|
||||
|
||||
// contentLogger.Info(fmt.Sprintf("获取内容 item_id=%s text_mode=%v image_mode=%v", itemID, textModeBool, imageModeBool))
|
||||
|
||||
@@ -50,7 +50,7 @@ func processCachedContent(cache string, textMode, imageMode bool) (string, error
|
||||
}
|
||||
}
|
||||
|
||||
return buildJSONResponse(d), nil
|
||||
return buildJSONResponse(UnwrapJSONStrings(d)), nil
|
||||
}
|
||||
|
||||
// fetchContentFromAPI 从API获取内容(带设备切换重试)
|
||||
@@ -193,7 +193,7 @@ func fetchContentWithRetry(itemID string, textMode, imageMode bool, retryCount i
|
||||
parser := NewContentParser()
|
||||
data["content"] = parser.Parse(contentStr, textMode, imageMode)
|
||||
|
||||
return buildJSONResponse(body), nil
|
||||
return buildJSONResponse(UnwrapJSONStrings(body)), nil
|
||||
}
|
||||
|
||||
// 响应code不为0,切换设备重试
|
||||
@@ -270,7 +270,7 @@ func tryBackupAPI(itemID string, textMode, imageMode bool) (string, error) {
|
||||
parser := NewContentParser()
|
||||
data["content"] = parser.Parse(decryptedContent, textMode, imageMode)
|
||||
|
||||
return buildJSONResponse(body), nil
|
||||
return buildJSONResponse(UnwrapJSONStrings(body)), nil
|
||||
}
|
||||
|
||||
contentLogger.Warning("备用接口1获取正文出错!")
|
||||
|
||||
@@ -40,15 +40,15 @@ func (p *ContentParser) Parse(content string, textMode bool, imageMode bool) str
|
||||
content = p.removeImageDesc(content)
|
||||
}
|
||||
|
||||
// 4. 根据参数或配置移除图片
|
||||
// URL参数 image_mode=0 或配置 remove_images=true 时移除图片
|
||||
if !imageMode || p.cfg.RemoveImages {
|
||||
// 4. 根据参数移除图片
|
||||
// imageMode=false 时移除(URL 参数与配置 remove_images 已在调用方合成:URL 优先)
|
||||
if !imageMode {
|
||||
content = p.removeImages(content)
|
||||
}
|
||||
|
||||
// 5. 根据参数或配置处理内容模式
|
||||
// URL参数 text_mode=1 或配置 remove_html_tags=true 时使用文本模式
|
||||
if textMode || p.cfg.RemoveHTMLTags {
|
||||
// 5. 根据参数处理内容模式
|
||||
// textMode=true 时提取纯文本(URL 参数与配置 remove_html_tags 已在调用方合成:URL 优先)
|
||||
if textMode {
|
||||
return p.extractText(content)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fanqie/internal/config"
|
||||
"sort"
|
||||
@@ -66,11 +67,16 @@ func removeBlankLines(content string) string {
|
||||
|
||||
// ============ 参数解析工具函数 ============
|
||||
|
||||
// parseBoolParam 解析布尔参数
|
||||
func parseBoolParam(param interface{}) bool {
|
||||
// ParseBoolParam 解析布尔参数,支持 1/0、true/false 及语义别名
|
||||
// text_mode: plain(纯文本)=true / html=false
|
||||
// image_mode、review: keep(保留/启用)=true / remove(移除/禁用)=false
|
||||
func ParseBoolParam(param interface{}) bool {
|
||||
switch v := param.(type) {
|
||||
case string:
|
||||
return v == "true" || v == "1" || strings.ToLower(v) == "true"
|
||||
switch strings.ToLower(v) {
|
||||
case "1", "true", "plain", "keep":
|
||||
return true
|
||||
}
|
||||
case bool:
|
||||
return v
|
||||
}
|
||||
@@ -82,7 +88,7 @@ func parseBoolParamDefault(param interface{}, defaultVal bool) bool {
|
||||
if param == nil || param == "" {
|
||||
return defaultVal
|
||||
}
|
||||
return parseBoolParam(param)
|
||||
return ParseBoolParam(param)
|
||||
}
|
||||
|
||||
// ============ JSON 处理工具函数 ============
|
||||
@@ -100,6 +106,78 @@ func buildJSONResponse(data interface{}) string {
|
||||
return escapeJSON(string(resultBytes))
|
||||
}
|
||||
|
||||
// marshalNoEscape 序列化 JSON 时不做 HTML 转义。
|
||||
// json.Marshal 默认把 URL 中的 & < > 转义为 & 等,直接从响应文本复制
|
||||
// URL 到浏览器会因字面转义序列打不开;含播放/下载链接的响应用本函数
|
||||
func marshalNoEscape(v interface{}) string {
|
||||
var buf bytes.Buffer
|
||||
enc := json.NewEncoder(&buf)
|
||||
enc.SetEscapeHTML(false)
|
||||
if err := enc.Encode(v); err != nil {
|
||||
return "{}"
|
||||
}
|
||||
return strings.TrimSuffix(buf.String(), "\n")
|
||||
}
|
||||
|
||||
// UnwrapJSONStrings 递归解包字符串形式的 JSON 值。上游常把对象/数组
|
||||
// 双重编码为字符串(如 category_schema: "[{\"category_id\":718,...}]"),
|
||||
// 本函数将其还原为真正的对象/数组。仅处理以 { 或 [ 开头且能完整解析
|
||||
// 为 object/array 的字符串,普通文本与数字字符串不受影响;嵌套解析使用
|
||||
// UseNumber,大整数 ID 不丢精度。
|
||||
func UnwrapJSONStrings(v interface{}) interface{} {
|
||||
switch t := v.(type) {
|
||||
case map[string]interface{}:
|
||||
for k, val := range t {
|
||||
t[k] = UnwrapJSONStrings(val)
|
||||
}
|
||||
return t
|
||||
case []interface{}:
|
||||
for i, val := range t {
|
||||
t[i] = UnwrapJSONStrings(val)
|
||||
}
|
||||
return t
|
||||
case []map[string]interface{}:
|
||||
for i, val := range t {
|
||||
t[i] = UnwrapJSONStrings(val).(map[string]interface{})
|
||||
}
|
||||
return t
|
||||
case map[string]map[string]interface{}:
|
||||
m := make(map[string]interface{}, len(t))
|
||||
for k, val := range t {
|
||||
m[k] = UnwrapJSONStrings(val)
|
||||
}
|
||||
return m
|
||||
case string:
|
||||
s := strings.TrimSpace(t)
|
||||
if len(s) > 1 && (s[0] == '{' || s[0] == '[') {
|
||||
dec := json.NewDecoder(strings.NewReader(s))
|
||||
dec.UseNumber()
|
||||
var parsed interface{}
|
||||
if err := dec.Decode(&parsed); err == nil {
|
||||
switch parsed.(type) {
|
||||
case map[string]interface{}, []interface{}:
|
||||
return UnwrapJSONStrings(parsed)
|
||||
}
|
||||
}
|
||||
}
|
||||
return t
|
||||
default:
|
||||
return v
|
||||
}
|
||||
}
|
||||
|
||||
// reencodeUnwrapped 解析上游响应文本,解包 JSON 字符串后重新序列化。
|
||||
// 解析失败时原样返回;UseNumber 保证大整数 ID 不丢精度
|
||||
func reencodeUnwrapped(text string) string {
|
||||
dec := json.NewDecoder(strings.NewReader(text))
|
||||
dec.UseNumber()
|
||||
var v interface{}
|
||||
if err := dec.Decode(&v); err != nil {
|
||||
return text
|
||||
}
|
||||
return marshalNoEscape(UnwrapJSONStrings(v))
|
||||
}
|
||||
|
||||
// ============ 设备和密钥管理 ============
|
||||
|
||||
// getDeviceHeader 获取设备header(从设备池)
|
||||
|
||||
@@ -47,8 +47,8 @@ func fetchDetail(bookID string) (string, error) {
|
||||
delete(data, "content")
|
||||
}
|
||||
|
||||
// 重新序列化
|
||||
resultBytes, err := json.Marshal(respJSON)
|
||||
// 重新序列化(解包 JSON 字符串字段)
|
||||
resultBytes, err := json.Marshal(UnwrapJSONStrings(respJSON))
|
||||
if err != nil {
|
||||
return BuildErrorResponse("序列化失败"), err
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@ func fetchItemSummary(itemIDs, bookID string) (string, error) {
|
||||
}
|
||||
|
||||
if code, ok := respJSON["code"].(float64); ok && code == 0 {
|
||||
return resp.Text, nil
|
||||
return reencodeUnwrapped(resp.Text), nil
|
||||
}
|
||||
|
||||
return BuildErrorResponse("获取失败"), nil
|
||||
|
||||
+15
-5
@@ -234,8 +234,11 @@ func decryptAESContent(encrypted, secretKey string) (string, error) {
|
||||
plaintext := make([]byte, len(ciphertext))
|
||||
mode.CryptBlocks(plaintext, ciphertext)
|
||||
|
||||
// PKCS7 unpadding
|
||||
// PKCS7 unpadding(无效填充说明密钥不匹配,返回错误触发上层重试)
|
||||
plaintext = pkcs7Unpad(plaintext)
|
||||
if plaintext == nil {
|
||||
return "", fmt.Errorf("解密失败(无效填充,密钥可能不匹配)")
|
||||
}
|
||||
|
||||
// 尝试gzip解压
|
||||
if len(plaintext) > 2 && plaintext[0] == 0x1f && plaintext[1] == 0x8b {
|
||||
@@ -257,13 +260,20 @@ func decryptAESContent(encrypted, secretKey string) (string, error) {
|
||||
func pkcs7Unpad(data []byte) []byte {
|
||||
length := len(data)
|
||||
if length == 0 {
|
||||
return data
|
||||
return nil
|
||||
}
|
||||
unpadding := int(data[length-1])
|
||||
if unpadding > length {
|
||||
return data
|
||||
// 完整校验:值 1-16 且尾部 unpadding 个字节全等于填充值。
|
||||
// 密钥错误时解密结果是随机字节,弱校验会让乱码静默通过
|
||||
if unpadding < 1 || unpadding > 16 || unpadding > length {
|
||||
return nil
|
||||
}
|
||||
return data[:(length - unpadding)]
|
||||
for _, b := range data[length-unpadding:] {
|
||||
if int(b) != unpadding {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return data[:length-unpadding]
|
||||
}
|
||||
|
||||
// buildMangaResponse 构建漫画响应(统一HTML和JSON格式输出)
|
||||
|
||||
@@ -82,9 +82,9 @@ func handleDecryptTask(itemID string, itemData map[string]interface{}, keyInfo *
|
||||
|
||||
// MultiContent 批量获取内容
|
||||
func MultiContent(itemIDs interface{}, bookID string, textMode, imageMode, ignoreFailed interface{}, depth int) (string, error) {
|
||||
// 参数转换
|
||||
textModeBool := parseBoolParam(textMode)
|
||||
imageModeBool := parseBoolParamDefault(imageMode, true)
|
||||
// 参数转换(URL 参数优先,未传时回退配置)
|
||||
textModeBool := parseBoolParamDefault(textMode, getContentConfig().RemoveHTMLTags)
|
||||
imageModeBool := parseBoolParamDefault(imageMode, !getContentConfig().RemoveImages)
|
||||
ignoreFailedBool := parseBoolParamDefault(ignoreFailed, true)
|
||||
|
||||
if depth > 3 {
|
||||
@@ -256,7 +256,7 @@ func MultiContent(itemIDs interface{}, bookID string, textMode, imageMode, ignor
|
||||
|
||||
// 构建响应
|
||||
response := buildCacheData(results)
|
||||
return buildJSONResponse(response), nil
|
||||
return buildJSONResponse(UnwrapJSONStrings(response)), nil
|
||||
}
|
||||
|
||||
// 响应code不为0,切换设备重试
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fanqie/internal/common"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -215,6 +214,5 @@ func fetchMultiDetail(bookID interface{}) (string, error) {
|
||||
"data": res,
|
||||
}
|
||||
|
||||
resultBytes, _ := json.Marshal(response)
|
||||
return string(resultBytes), nil
|
||||
return marshalNoEscape(UnwrapJSONStrings(response)), nil
|
||||
}
|
||||
@@ -70,11 +70,17 @@ func createSymmetricCrypto(algorithm string, key, iv []byte) (func([]byte) ([]by
|
||||
decrypted := make([]byte, len(data))
|
||||
mode.CryptBlocks(decrypted, data)
|
||||
|
||||
// 移除PKCS7填充
|
||||
// 移除PKCS7填充(完整校验:密钥错误时尾部为随机字节,
|
||||
// 弱校验会让乱码静默通过并返回 200)
|
||||
padding := int(decrypted[len(decrypted)-1])
|
||||
if padding > len(decrypted) || padding > aes.BlockSize {
|
||||
if padding < 1 || padding > len(decrypted) || padding > aes.BlockSize {
|
||||
return nil, fmt.Errorf("无效的填充")
|
||||
}
|
||||
for _, b := range decrypted[len(decrypted)-padding:] {
|
||||
if int(b) != padding {
|
||||
return nil, fmt.Errorf("无效的填充")
|
||||
}
|
||||
}
|
||||
|
||||
return decrypted[:len(decrypted)-padding], nil
|
||||
}
|
||||
|
||||
+33
-95
@@ -6,6 +6,8 @@ import (
|
||||
"encoding/json"
|
||||
"fanqie/internal/common"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -62,8 +64,11 @@ func postReviewAPI(url string, requestBody interface{}) (map[string]interface{},
|
||||
return nil, fmt.Errorf("解析响应失败: %w", err)
|
||||
}
|
||||
|
||||
// 提取 data 字段
|
||||
// 提取 data 字段(并解包 JSON 字符串字段,如 post_data.content)
|
||||
if data, ok := result["data"].(map[string]interface{}); ok {
|
||||
if unwrapped, ok := UnwrapJSONStrings(data).(map[string]interface{}); ok {
|
||||
return unwrapped, nil
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
@@ -169,8 +174,11 @@ func GetParaReview(itemID, bookID, commentID string, para, sort, offset, count i
|
||||
return nil, fmt.Errorf("解析响应失败: %w", err)
|
||||
}
|
||||
|
||||
// 提取 data 字段
|
||||
// 提取 data 字段(并解包 JSON 字符串字段,如 post_data.content)
|
||||
if data, ok := result["data"].(map[string]interface{}); ok {
|
||||
if unwrapped, ok := UnwrapJSONStrings(data).(map[string]interface{}); ok {
|
||||
return unwrapped, nil
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
@@ -235,103 +243,33 @@ func GenerateParagraphsWithComments(itemID, bookID, content, baseURL string) (st
|
||||
strings.Contains(content, "<div") ||
|
||||
strings.Contains(content, "<article")
|
||||
|
||||
// 关键:如果检测到有段评数据,强制使用HTML模式(包裹<p>标签)
|
||||
// 因为<comment>标签需要XML兼容的格式
|
||||
hasAnyComments := len(commentData) > 0
|
||||
if hasAnyComments && !isHTMLContent {
|
||||
isHTMLContent = true
|
||||
// 纯文本模式下 <comment> 标签无法承载,保持纯文本原样返回(不注入段评);
|
||||
// 需要段评标记时配置 remove_html_tags: false 或 text_mode=html
|
||||
if !isHTMLContent {
|
||||
return content, nil
|
||||
}
|
||||
|
||||
lines := strings.Split(content, "\n")
|
||||
var result strings.Builder
|
||||
paragraphIndex := 0
|
||||
|
||||
for i, line := range lines {
|
||||
isLastLine := i == len(lines)-1
|
||||
trimmedLine := strings.TrimSpace(line)
|
||||
|
||||
// 完全空行:直接输出换行符
|
||||
if trimmedLine == "" {
|
||||
if !isLastLine {
|
||||
result.WriteString("\n")
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 跳过图片标签和div标签
|
||||
if strings.HasPrefix(trimmedLine, "<img") ||
|
||||
strings.HasPrefix(trimmedLine, "<div") ||
|
||||
strings.HasPrefix(trimmedLine, "</div>") ||
|
||||
strings.HasPrefix(trimmedLine, "<article") ||
|
||||
strings.HasPrefix(trimmedLine, "</article") {
|
||||
result.WriteString(line)
|
||||
if !isLastLine {
|
||||
result.WriteString("\n")
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 如果原内容已经有<p>标签,在</p>之前插入段评标记
|
||||
if strings.HasPrefix(trimmedLine, "<p>") && strings.HasSuffix(trimmedLine, "</p>") {
|
||||
// 提取<p>和</p>之间的内容
|
||||
innerContent := trimmedLine[3 : len(trimmedLine)-4]
|
||||
result.WriteString("<p>")
|
||||
result.WriteString(innerContent)
|
||||
|
||||
// 添加评论标记
|
||||
key := fmt.Sprintf("%d", paragraphIndex)
|
||||
if commentInfo, exists := commentData[key]; exists && commentInfo.Count > 0 {
|
||||
commentTag := fmt.Sprintf(`<comment ident="%s/review_html?item_id=%s&book_id=%s¶=%d" count="%d" />`,
|
||||
baseURL, itemID, bookID, paragraphIndex, commentInfo.Count)
|
||||
result.WriteString(commentTag)
|
||||
}
|
||||
|
||||
result.WriteString("</p>")
|
||||
if !isLastLine {
|
||||
result.WriteString("\n")
|
||||
}
|
||||
paragraphIndex++
|
||||
continue
|
||||
}
|
||||
|
||||
// 如果是HTML模式,包裹<p>标签
|
||||
if isHTMLContent {
|
||||
result.WriteString("<p>")
|
||||
result.WriteString(line)
|
||||
|
||||
// 添加评论标记
|
||||
key := fmt.Sprintf("%d", paragraphIndex)
|
||||
if commentInfo, exists := commentData[key]; exists && commentInfo.Count > 0 {
|
||||
commentTag := fmt.Sprintf(`<comment ident="%s/review_html?item_id=%s&book_id=%s¶=%d" count="%d" />`,
|
||||
baseURL, itemID, bookID, paragraphIndex, commentInfo.Count)
|
||||
result.WriteString(commentTag)
|
||||
}
|
||||
|
||||
result.WriteString("</p>")
|
||||
if !isLastLine {
|
||||
result.WriteString("\n")
|
||||
}
|
||||
} else {
|
||||
// 纯文本模式:只在行尾添加comment标记
|
||||
result.WriteString(line)
|
||||
|
||||
// 添加评论标记(纯文本格式)
|
||||
key := fmt.Sprintf("%d", paragraphIndex)
|
||||
if commentInfo, exists := commentData[key]; exists && commentInfo.Count > 0 {
|
||||
commentTag := fmt.Sprintf(`<comment ident="%s/review_html?item_id=%s&book_id=%s¶=%d" count="%d" />`,
|
||||
baseURL, itemID, bookID, paragraphIndex, commentInfo.Count)
|
||||
result.WriteString(commentTag)
|
||||
}
|
||||
|
||||
if !isLastLine {
|
||||
result.WriteString("\n")
|
||||
// HTML 内容:在每个 </p> 前插入段评标记。
|
||||
// 兼容 <p idx="n">(HTML 模式结构)与无属性的 <p>;段号取 idx,无 idx 时按出现顺序。
|
||||
// header/article/div/img 等非段落标签不受影响。
|
||||
pRe := regexp.MustCompile(`(?s)<p\b[^>]*>.*?</p>`)
|
||||
idxRe := regexp.MustCompile(`idx="(\d+)"`)
|
||||
order := 0
|
||||
return pRe.ReplaceAllStringFunc(content, func(m string) string {
|
||||
defer func() { order++ }()
|
||||
para := order
|
||||
if idx := idxRe.FindStringSubmatch(m); idx != nil {
|
||||
if n, err := strconv.Atoi(idx[1]); err == nil {
|
||||
para = n
|
||||
}
|
||||
}
|
||||
|
||||
paragraphIndex++
|
||||
}
|
||||
|
||||
return result.String(), nil
|
||||
if commentInfo, exists := commentData[fmt.Sprintf("%d", para)]; exists && commentInfo.Count > 0 {
|
||||
commentTag := fmt.Sprintf(`<comment ident="%s/review_html?item_id=%s&book_id=%s¶=%d" count="%d" />`,
|
||||
baseURL, itemID, bookID, para, commentInfo.Count)
|
||||
return m[:len(m)-len("</p>")] + commentTag + "</p>"
|
||||
}
|
||||
return m
|
||||
}), nil
|
||||
}
|
||||
|
||||
// extractDeviceID 从 device header 中提取 device_id
|
||||
|
||||
@@ -69,6 +69,8 @@ func fetchBookSearch(key string, offset int, tabType int) (string, error) {
|
||||
return resp.Text, nil // 解析失败时退回原样转发
|
||||
}
|
||||
filterSearchTabs(numJSON, tabType)
|
||||
unwrapSearchTab(numJSON)
|
||||
UnwrapJSONStrings(numJSON)
|
||||
return ToJSON(numJSON)
|
||||
}
|
||||
|
||||
@@ -97,3 +99,27 @@ func filterSearchTabs(respJSON map[string]interface{}, tabType int) {
|
||||
respJSON["search_tabs"] = filtered
|
||||
}
|
||||
}
|
||||
|
||||
// unwrapSearchTab 将过滤后的唯一 tab 展平:去掉 search_tabs 包装,
|
||||
// tab 的 data 直接作为顶层 data,并提升分页字段 has_more/next_offset
|
||||
func unwrapSearchTab(respJSON map[string]interface{}) {
|
||||
tabs, ok := respJSON["search_tabs"].([]interface{})
|
||||
if !ok || len(tabs) != 1 {
|
||||
return
|
||||
}
|
||||
tab, ok := tabs[0].(map[string]interface{})
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
delete(respJSON, "search_tabs")
|
||||
delete(respJSON, "selected_tab_idx") // tab 已展平,索引无意义
|
||||
delete(respJSON, "server_ab_params") // 上游 AB 实验参数,透传无意义
|
||||
if data, ok := tab["data"]; ok {
|
||||
respJSON["data"] = data
|
||||
}
|
||||
for _, k := range []string{"has_more", "next_offset"} {
|
||||
if v, ok := tab[k]; ok {
|
||||
respJSON[k] = v
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
-4
@@ -95,8 +95,7 @@ func HandleVideo(itemIDs interface{}) (string, error) {
|
||||
"data": decodedModel,
|
||||
}
|
||||
|
||||
resultBytes, _ := json.Marshal(response)
|
||||
return string(resultBytes), nil
|
||||
return marshalNoEscape(response), nil
|
||||
} else {
|
||||
// 批量接口:data 是一个map,key是ID,value包含video_model
|
||||
result := make(map[string]interface{})
|
||||
@@ -119,8 +118,7 @@ func HandleVideo(itemIDs interface{}) (string, error) {
|
||||
"data": result,
|
||||
}
|
||||
|
||||
resultBytes, _ := json.Marshal(response)
|
||||
return string(resultBytes), nil
|
||||
return marshalNoEscape(response), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,6 +142,10 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
// 解析失败,返回空对象
|
||||
return map[string]interface{}{}
|
||||
}
|
||||
// 解包嵌套的 JSON 字符串字段(category_schema、recommend_info 等)
|
||||
if unwrapped, ok := UnwrapJSONStrings(videoModel).(map[string]interface{}); ok {
|
||||
videoModel = unwrapped
|
||||
}
|
||||
|
||||
// 构建精简的返回结果,只包含关键字段
|
||||
result := make(map[string]interface{})
|
||||
@@ -158,6 +160,10 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
if posterURL, ok := videoModel["poster_url"].(string); ok {
|
||||
result["poster_url"] = posterURL
|
||||
}
|
||||
// 加密信息:视频为 CENC 加密(encrypt=true),解密需要 key_seed/kid
|
||||
if keySeed, ok := videoModel["key_seed"].(string); ok {
|
||||
result["key_seed"] = keySeed
|
||||
}
|
||||
|
||||
// 处理 video_list
|
||||
if videoList, ok := videoModel["video_list"].(map[string]interface{}); ok {
|
||||
@@ -189,6 +195,15 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
if fps, ok := qualityMap["fps"].(float64); ok {
|
||||
qualityInfo["fps"] = int(fps)
|
||||
}
|
||||
if encrypt, ok := qualityMap["encrypt"].(bool); ok && encrypt {
|
||||
qualityInfo["encrypt"] = true
|
||||
if em, ok := qualityMap["encryption_method"].(string); ok {
|
||||
qualityInfo["encryption_method"] = em
|
||||
}
|
||||
if kid, ok := qualityMap["kid"].(string); ok {
|
||||
qualityInfo["kid"] = kid
|
||||
}
|
||||
}
|
||||
|
||||
// 解码 main_url
|
||||
if mainURL, ok := qualityMap["main_url"].(string); ok {
|
||||
|
||||
Reference in new issue
Block a user