Compare commits
3
Commits
9eb2567247
...
59de8cd0b9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59de8cd0b9 | ||
|
|
f90e450359 | ||
|
|
49d0a371fb |
No files matched your search
+3
-1
@@ -32,8 +32,10 @@ SRC_DIR="/root/code/novel/fanqie-go"
|
||||
DOMAIN="fq.20010117.xyz"
|
||||
|
||||
# ---------- 证书 ----------
|
||||
# Certbot 申请证书的邮箱,用于接收过期提醒
|
||||
# acme.sh 申请证书的邮箱,用于账户注册与过期提醒
|
||||
CERT_EMAIL="you@example.com"
|
||||
# 证书安装目录(acme.sh --install-cert 目标,nginx 配置从此处读取)
|
||||
# CERT_DIR="/etc/nginx/ssl"
|
||||
|
||||
# ---------- 编译 ----------
|
||||
# BUILD_TARGET="./cmd/fanqie"
|
||||
|
||||
@@ -47,6 +47,7 @@ __pycache__
|
||||
/build/
|
||||
|
||||
cache.db
|
||||
video_cache/
|
||||
|
||||
# Build output
|
||||
fanqie-*
|
||||
@@ -56,3 +57,4 @@ fanqie-*
|
||||
.env
|
||||
.finesse/
|
||||
fanqie.log
|
||||
.codegraph/
|
||||
@@ -0,0 +1,63 @@
|
||||
[
|
||||
{
|
||||
"bookSourceName": "🔅番茄聚合",
|
||||
"bookSourceGroup": "📖番茄小说",
|
||||
"bookSourceType": 0,
|
||||
"bookSourceUrl": "https://fq.20010117.xyz",
|
||||
"bookSourceComment": "番茄聚合书源(fanqie-go 后端)\n\n基础使用教程:\n1、搜索:\n 1) 基础搜索:直接搜,默认搜索当前模式内容\n 2) 快捷搜索:使用特殊关键词(x,t,m,d)搜索\n x:书名 如(x:十日终焉) 搜小说(可省略)\n t:书名 如(t:十日终焉) 搜听书\n m:书名 如(m:十日终焉) 搜漫画\n d:书名 如(d:十日终焉) 搜短剧\n 冒号支持中文英文,也可在书源设置中切换默认搜索模式\n2、发现页:\n 顶部筛选选择 类型/频道/字数/更新/排序 后,点击分类宫格浏览,下拉翻页\n3、段评:\n 阅读正文时点击段尾气泡即可查看段落评论,样式可在段评设置中调整\n4、听书/漫画/短剧:\n 听书自动用播放器播放;漫画走服务端解密代理;短剧打开章节自动唤起播放\n\n更换服务器地址:只需修改源URL(bookSourceUrl),全部规则使用相对地址自动跟随",
|
||||
"bookSourceEnabled": true,
|
||||
"enabledExplore": true,
|
||||
"enabledCookieJar": true,
|
||||
"customOrder": 0,
|
||||
"weight": 0,
|
||||
"respondTime": 180000,
|
||||
"lastUpdateTime": 1791607295124,
|
||||
"bookUrlPattern": "https?:\\/\\/(?:[a-zA-Z0-9-]+\\.)?[a-zA-Z0-9-]+(?::\\d+)?\\/detail\\?book_id=\\d+.*",
|
||||
"jsLib": "// 当前书源版本号\nlet localVersion = '26.10.10';\n\n// 初始配置\nconst defaultConfig = {\n 发现页类型: \"小说\",\n 频道: \"男频\",\n 搜索模式: \"小说\"\n};\n\n// 获取源变量\nfunction getVariable(k) {\n if (k == undefined) k = \"\";\n const { source } = this;\n let parsed = {};\n try {\n parsed = JSON.parse(source.getVariable());\n } catch {}\n if (k == \"\") {\n return parsed;\n }\n let value = parsed[k];\n if (value == undefined) {\n value = defaultConfig[k];\n }\n return value != undefined ? value : \"\";\n}\n\n// 设置源变量\nfunction setVariable(k, v, t) {\n if (t == undefined) t = true;\n const { source, java } = this;\n const vs = this.getVariable();\n vs[k] = v;\n source.setVariable(JSON.stringify(vs, null, 4));\n if (k != '搜索关键词' && t) {\n java.toast(`\\n设置 ${k} 为 ${v}`)\n }\n}\n\n// 还原\nfunction deleteVariable() {\n const { source, java } = this;\n source.setVariable('');\n java.longToast('\\n所有设置已还原到初始化导入状态');\n}\n\n// 从 URL 提取内容类型标记(n小说/t听书/m漫画/d短剧)。\n// 注意:jsLib 函数作用域看不到规则变量 baseUrl,必须由调用方显式传入\nfunction fqTab(url, def) {\n if (def == undefined) def = 'n';\n let m = String(url).match(/fqtab=([ntmd])/);\n return m ? m[1] : def;\n}\n\n// 判断当前环境\nfunction checkEnv() {\n const {\n java,\n source\n } = this;\n\n try {\n java.qread();\n return \"轻阅读\";\n } catch (e) {}\n\n try {\n if (typeof java.reLoginView == 'function') {\n return \"改版\";\n }\n new Packages.io.legato.kazusa.utils.TimeoutCancellationException('');\n return \"改版\";\n } catch (e) {}\n try {\n java.deviceID();\n return \"苹果\";\n } catch (e) {}\n\n if (typeof source.loginUi == 'function') {\n return \"安卓\";\n }\n\n return \"改版\";\n}\n\n// 备用设置方案(登录页按钮)\nfunction ste(v) {\n const { java } = this;\n let moreSettings = this.getVariable(\"更多设置\") || {};\n let paraSettings = this.getVariable(\"段评设置\") || {};\n if (v == \"段评\") {\n if (paraSettings[\"段评开关\"] != \"false\") {\n paraSettings[\"段评开关\"] = \"false\";\n java.longToast(\"\\n❌段评已关闭\");\n } else {\n paraSettings[\"段评开关\"] = \"true\";\n java.longToast(\"\\n✅段评已开启\");\n }\n }\n if (v == \"小说\" || v == \"听书\" || v == \"漫画\" || v == \"短剧\") {\n moreSettings[\"搜索模式\"] = v;\n java.longToast(`\\n已设置搜索模式为 ${v}`);\n }\n if (v == \"图片\") {\n if (moreSettings[\"显示图片\"] != \"false\") {\n moreSettings[\"显示图片\"] = \"false\";\n java.longToast(\"\\n❌已关闭图片显示\");\n } else {\n moreSettings[\"显示图片\"] = \"true\";\n java.longToast(\"\\n✅已开启图片显示\");\n }\n }\n if (v == \"简介\") {\n if (moreSettings[\"完整简介\"] != \"false\") {\n moreSettings[\"完整简介\"] = \"false\";\n java.longToast(\"\\n❌已关闭完整简介\");\n } else {\n moreSettings[\"完整简介\"] = \"true\";\n java.longToast(\"\\n✅已开启完整简介\");\n }\n }\n this.setVariable(\"更多设置\", moreSettings, false);\n this.setVariable(\"段评设置\", paraSettings, false);\n}\n\n// 按钮切换时改变源变量并刷新发现\nfunction show(m, t) {\n const { java, source } = this;\n let data = {};\n try {\n data = JSON.parse(source.getVariable())\n } catch {}\n data[t] = m;\n if (t == \"发现页类型\") {\n data[\"频道\"] = '男频';\n }\n source.setVariable(JSON.stringify(data, null, 2));\n java.refreshExplore();\n}\n\nfunction createFilter(title, chars, defaultVal, paramKey, size, viewName) {\n if (viewName == undefined) viewName = \"'请选择类型'\";\n return {\n title: title,\n type: \"select\",\n chars: chars,\n default: defaultVal,\n \"viewName\": viewName,\n action: `show(infoMap['${title}'],'${paramKey}')`,\n style: {\n layout_flexGrow: 1,\n layout_flexBasisPercent: size\n }\n };\n}\n\nfunction createText(title, action, defaultValue, size, viewName) {\n return {\n title: title,\n type: 'text',\n default: defaultValue || '',\n action: action,\n viewName: viewName || title,\n style: {\n layout_flexGrow: 1,\n layout_flexBasisPercent: size\n }\n };\n}\n\nfunction createButton(title, action, size) {\n return {\n title: title,\n type: 'butLine truncated
|
||||
"loginUi": "[\n {\n \"name\": \"⚙️ 书源设置\",\n \"type\": \"button\",\n \"action\": \"getHtmlSettings()\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.4 }\n }, {\n \"name\": \"🗨 段评设置\",\n \"type\": \"button\",\n \"action\": \"getSvgSettings()\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.4 }\n }, {\n \"name\": \"===下方为备用设置方案===\",\n \"type\": \"button\",\n \"action\": \"\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 1 }\n }, {\n \"name\": \"📖搜索小说\",\n \"type\": \"button\",\n \"action\": \"ste('小说')\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.4 }\n }, {\n \"name\": \"🎧搜索听书\",\n \"type\": \"button\",\n \"action\": \"ste('听书')\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.4 }\n }, {\n \"name\": \"🎥搜索短剧\",\n \"type\": \"button\",\n \"action\": \"ste('短剧')\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.4 }\n }, {\n \"name\": \"🎨搜索漫画\",\n \"type\": \"button\",\n \"action\": \"ste('漫画')\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.4 }\n }, {\n \"name\": \"段评开关\",\n \"type\": \"button\",\n \"action\": \"ste('段评')\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.25 }\n }, {\n \"name\": \"图片开关\",\n \"type\": \"button\",\n \"action\": \"ste('图片')\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.25 }\n }, {\n \"name\": \"简介开关\",\n \"type\": \"button\",\n \"action\": \"ste('简介')\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 0.25 }\n }, {\n \"name\": \"⛔‼️ 清空还原设置\",\n \"type\": \"button\",\n \"action\": \"deleteVariable()\",\n \"style\": { \"layout_flexGrow\": 1, \"layout_flexBasisPercent\": 1 }\n }\n]",
|
||||
"searchUrl": "<js>\nlet moreSettings = getVariable('更多设置');\nlet tab = moreSettings && moreSettings['搜索模式'] || '小说';\nvar k = String(key);\nlet m = k.match(/^[xtmdXTMD][::]\\s*/);\nif (m) {\n tab = { x: '小说', t: '听书', m: '漫画', d: '短剧' }[m[0][0].toLowerCase()];\n k = k.slice(m[0].length);\n}\nlet tabType = { 小说: 3, 听书: 2, 漫画: 8, 短剧: 11 }[tab] || 3;\n`/search?query=${encodeURIComponent(k)}&offset=${(page - 1) * 10}&tab_type=${tabType}`;\n</js>",
|
||||
"exploreUrl": "<js>\nvar base = String(source.getKey()).replace(/\\/$/, '');\nvar tab = getVariable('发现页类型') || '小说';\nvar channel = getVariable('频道') || '男频';\nvar wordNumMap = { '不限': '0', '30万字以内': '4', '100万字以内': '1', '30万-100万': '5', '100万-300万': '2', '300万字以上': '3', '100万字以上': '9' };\nvar updateMap = { '不限': '2', '完结': '0', '连载中': '1', '今日更新': '3' };\nvar sortMap = { '综合': '0', '热门': '24', '最新': '76', '评分': '12' };\nvar wordNum = getVariable('字数') || '不限';\nvar update = getVariable('更新') || '不限';\nvar sort = getVariable('排序') || '综合';\nvar q = `&word_number=${wordNumMap[wordNum] || '0'}&book_status=${updateMap[update] || '2'}&sort_by=${sortMap[sort] || '0'}`;\nvar tabCode = { 小说: 'n', 听书: 't', 漫画: 'm', 短剧: 'd' }[tab] || 'n';\n\nvar list = [];\nlist.push(createFilter('类型', ['小说', '听书', '短剧', '漫画'], tab, '发现页类型', 0.4));\nlist.push(createFilter('频道', ['男频', '女频'], channel, '频道', 0.4));\nlist.push(createText('搜索关键词', \"setVariable('搜索关键词',(infoMap['搜索关键词'] || (infoMap.get && infoMap.get('搜索关键词'))))\", getVariable('搜索关键词') || '', 0.5, \"'搜索书名或作者'\"));\nlist.push(createButton('🔍搜索', 'exploreSearch()', 0.3));\nlist.push({ title: '⚙️书源设置', type: 'button', action: 'getHtmlSettings()', style: { layout_flexGrow: 1, layout_flexBasisPercent: 0.25 } });\nlist.push({ title: '🗨段评设置', type: 'button', action: 'getSvgSettings()', style: { layout_flexGrow: 1, layout_flexBasisPercent: 0.25 } });\nlist.push(createFilter('字数', Object.keys(wordNumMap), wordNum, '字数', 0.4));\nlist.push(createFilter('更新', Object.keys(updateMap), update, '更新', 0.4));\nlist.push(createFilter('排序', Object.keys(sortMap), sort, '排序', 0.1));\n\nif (tab == '短剧') {\n list.push({ title: '短剧暂无分类,请使用上方搜索 🔍', url: '', style: { layout_flexGrow: 1, layout_flexBasisPercent: 1 } });\n} else {\n var ctab = tab == '小说' ? (channel == '女频' ? 0 : 1) : (tab == '听书' ? 3 : 5);\n try {\n var res = JSON.parse(java.ajax(base + '/category-front?tab=' + ctab));\n var cells = ((res.data || {}).category_tab_data || {}).cell_data || [];\n cells.forEach(function (cell) {\n (cell.atom_data || []).forEach(function (a) {\n var c = a.category_data;\n if (c && c.category_id != null) {\n list.push({\n title: c.name,\n url: base + '/category-landing?category_id=' + c.category_id + '&offset={{(page-1)*20}}' + q + '&fqtab=' + tabCode,\n style: { layout_flexGrow: 1, layout_flexBasisPercent: 0.25 }\n });\n }\n });\n });\n } catch (e) {\n java.toast('发现页分类获取失败');\n }\n}\nJSON.stringify(list);\n</js>",
|
||||
"ruleSearch": {
|
||||
"bookList": "<js>\nvar d = JSON.parse(result);\nvar isVideo = /tab_type=11/.test(baseUrl);\nvar arr = [];\n(d.data || []).forEach(function (b) {\n var list = isVideo ? (b.video_data || []) : (b.book_data || []);\n list.forEach(function (x) {\n if (isVideo) {\n arr.push({\n book_id: x.series_id,\n book_name: x.title,\n author: '',\n abstract: x.rec_text || '',\n thumb_url: x.horiz_cover || x.cover,\n category: '短剧',\n creation_status: '1',\n score: x.score,\n word_number: String(x.episode_cnt || '')\n });\n } else {\n arr.push(x);\n }\n });\n});\narr;\n</js>",
|
||||
"name": "$.book_name",
|
||||
"author": "$.author",
|
||||
"kind": "{{$.creation_status=='0'?'完结':'连载'}},{{$.category}},{{$.score}}分",
|
||||
"wordCount": "$.word_number##^0+$",
|
||||
"intro": "$.abstract",
|
||||
"coverUrl": "$.thumb_url",
|
||||
"bookUrl": "<js>\nvar t = /tab_type=11/.test(baseUrl) ? 'd' : /tab_type=2/.test(baseUrl) ? 't' : /tab_type=8/.test(baseUrl) ? 'm' : 'n';\n`/detail?book_id=${result.book_id}&fqtab=${t}`;\n</js>",
|
||||
"checkKeyWord": "斗罗大陆"
|
||||
},
|
||||
"ruleExplore": {
|
||||
"bookList": "$.data.book_info[*]",
|
||||
"name": "$.book_name",
|
||||
"author": "$.author",
|
||||
"kind": "{{$.category}},{{$.score}}分",
|
||||
"wordCount": "$.word_number##^0+$",
|
||||
"intro": "$.abstract",
|
||||
"coverUrl": "$.thumb_url",
|
||||
"bookUrl": "<js>\nvar m = String(baseUrl).match(/fqtab=([ntmd])/);\n`/detail?book_id=${result.book_id}&fqtab=${m ? m[1] : 'n'}`;\n</js>"
|
||||
},
|
||||
"ruleBookInfo": {
|
||||
"init": "$.data",
|
||||
"name": "$.book_name",
|
||||
"author": "$.author",
|
||||
"kind": "{{$.creation_status=='0'?'完结':'连载'}},{{$.category}}",
|
||||
"wordCount": "$.word_number##^0+$",
|
||||
"lastChapter": "$.last_chapter_title",
|
||||
"coverUrl": "$.thumb_url",
|
||||
"intro": "<js>\nconst { book_id, last_chapter_title, last_chapter_update_time, word_number, score, abstract, read_count, category } = result;\nlet m0 = String(baseUrl).match(/fqtab=([ntmd])/);\nconst tab = { n: '小说', t: '听书', m: '漫画', d: '短剧' }[(m0 ? m0[1] : 'n')];\nlet moreSettings = getVariable('更多设置');\nconst lightDivider = \"❇️───────❇️───────❇️\";\nconst heavyDivider = \"‎\\n‎\";\nconst isValid = (v) => String(v).length > 1;\nlet ctitle = book.durChapterTitle || '未开始';\nconst two = (n) => ('0' + n).slice(-2);\nconst fmtTime = (t) => {\n let n = parseInt(t);\n if (!n || n <= 0) return '';\n let d = new Date(n * 1000);\n return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())}`;\n};\nconst formatAbstract = (text) => String(text).split(\"\\n\").map(line => ` ${line}`).join(\"\\n\");\nconst buildBasicInfo = (items) => {\n let info = \"\";\n for (let [value, prefix, icon] of items) {\n if (isValid(value)) info += ` ${icon} ${prefix} ${value}\\n`;\n }\n return info;\n};\nlet info = ` 🏷 数据来源:番茄小说(fanqie-go)\\n 🔄 当前模式:${tab}\\n 📖 阅读至:${ctitle}\\n`;\nconst fullBasicInfo = buildBasicInfo([\n [category, \"书籍分类:\", \"🌈\"],\n [last_chapter_title, \"最新章节:\", \"📚\"],\n [fmtTime(last_chapter_update_time), \"更新时间:\", \"⏳\"],\n [word_number, \"书籍字数:\", \"📝\"],\n [score, \"书籍评分:\", \"⭐\"],\n [read_count, \"今阅读人数:\", \"📃\"]\n]);\nif (fullBasicInfo) info += `${lightDivider}\\n${fullBasicInfo}`;\nif (isValid(abstract)) info += `${heavyDivider}\\n 📖 书籍简介:\\n${formatAbstract(abstract)}\\n`;\ninfo += `${lightDivider}\\n${heavyDivider}\\n 数据更新于 ${new Date().toLocaleString()}\\n`;\nconst abstractMode = moreSettings && moreSettings['完整简介'] || 'true';\nif (abstractMode == \"false\") {\n const simplifiedBasicInfo = buildBasicInfo([\n [last_chapter_title, \"最新章节:\", \"📚\"],\n [fmtTime(last_chapter_update_time), \"更新时间:\", \"⏳\"],\n [word_number, \"书籍字数:\", \"📝\"],\n [score, \"书籍评分:\", \"⭐\"]\n ]);\n info = `\\n‎${isValid(abstract) ? `📖 书籍简介:\\n${formatAbstract(abstract)}\\n${heavyDivider}` : ''}🏷 数据来源:番茄小说\\n${simplifiedBasicInfo}`;\n} else {\n info = info.split(\"\\n\").map(line => line.replace(/^ {4}/, \"\")).join(\"\\n\");\n}\ninfo;\n</js>",
|
||||
"tocUrl": "<js>\nvar m = String(baseUrl).match(/fqtab=([ntmd])/);\n`/catalog?book_id=${result.book_id}&fqtab=${m ? m[1] : 'n'}`;\n</js>",
|
||||
"canReName": "1"
|
||||
},
|
||||
"ruleToc": {
|
||||
"chapterList": "<js>\n// 类型随书切换(照光遇 typeMap:安卓用 default,苹果端用其类型体系)\nconst typeMap = {\n \"小说\": { \"苹果\": 0, \"default\": 8 },\n \"听书\": { \"苹果\": 1, \"default\": 32 },\n \"漫画\": { \"苹果\": 2, \"default\": 64 },\n \"短剧\": { \"苹果\": 3, \"default\": 8 }\n};\nconst device_type = checkEnv();\nvar tabName = { n: '小说', t: '听书', m: '漫画', d: '短剧' }[fqTab(baseUrl, 'n')];\nvar currentType = typeMap[tabName] || typeMap[\"小说\"];\nif (device_type == '苹果') {\n book.type = currentType[device_type];\n} else {\n book.type = currentType.default;\n}\ntry {\n book.imageStyle = checkEnv() == '改版' ? 'FULL' : 'TEXT';\n} catch (e) {}\nresult;\n</js>$.data.item_data_list[*]",
|
||||
"chapterName": "$.title",
|
||||
"chapterUrl": "<js>\nvar t = fqTab(baseUrl, 'n');\nvar id = result.item_id;\nvar u = {\n n: `/content?item_id=${id}&text_mode=html&review=keep&image_mode=keep&fqtab=n`,\n t: `/audio?item_ids=${id}&fqtab=t`,\n m: `/manga?item_ids=${id}&output=proxy&fqtab=m`,\n d: `/video?item_ids=${id}&fqtab=d`\n}[t];\nu;\n</js>"
|
||||
},
|
||||
"ruleContent": {
|
||||
"content": "<js>\nvar t = fqTab(baseUrl, 'n');\nlet moreSettings = getVariable('更多设置');\nlet dpSettings = getVariable('段评设置');\nlet islyc = checkEnv();\n\nif (t == 't') {\n // 听书:直接返回音频地址\n JSON.parse(result).data[0].main_url;\n} else if (t == 'm') {\n // 漫画:拼装图片\n var d = JSON.parse(result);\n var org = String(baseUrl).match(/^https?:\\/\\/[^\\/]+/)[0];\n var imgs = (d.data || {}).images || [];\n var out = [];\n for (var i = 0; i < imgs.length; i++) {\n out.push('<img src=\"' + org + imgs[i].data + '\">');\n }\n out.join('\\n');\n} else if (t == 'd') {\n // 短剧:选最高清晰度,当前章节自动唤起播放\n var d = JSON.parse(result).data || {};\n var vl = d.video_list || {};\n var list = [];\n for (var k in vl) { list.push(vl[k]); }\n list.sort(function (a, b) { return (b.vheight || 0) - (a.vheight || 0); });\n var org = String(baseUrl).match(/^https?:\\/\\/[^\\/]+/)[0];\n var url = list.length ? String(list[0].main_url) : '';\n if (url && url.indexOf('http') != 0) { url = org + url; }\n if (url && book.durChapterIndex == chapter.index) {\n java.startBrowser(url, chapter.title);\n }\n '▶️ 本集已唤起播放(菜单-刷新可重新打开):\\n' + url;\n} else {\n // 小说:正文 + 段评气泡\n var d = JSON.parse(result);\n var content = String((d.data || {}).content || '');\n let show_img = moreSettings && moreSettings['显示图片'] || 'true';\n if (show_img == 'false') {\n content = removeAllImgTags(content);\n }\n let para = dpSettings && dpSettings['段评开关'] || 'true';\n if (para == 'true' && content.indexOf('<comment') != -1) {\n content = islyc == '苹果' ? paraForiOS(content, '番茄') : paraForAndroid(content, '番茄');\n }\n content;\n}\n</js>",
|
||||
"title": "$.data.title"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -172,6 +172,7 @@ func setupRoutes() {
|
||||
http.HandleFunc("/audio", wrap(handlers.HandleAudio))
|
||||
http.HandleFunc("/audio/proxy/", wrap(handlers.HandleAudioProxy))
|
||||
http.HandleFunc("/video", wrap(handlers.HandleVideo))
|
||||
http.HandleFunc("/video/proxy/", wrap(handlers.HandleVideoProxy))
|
||||
http.HandleFunc("/manga", wrap(handlers.HandleManga))
|
||||
http.HandleFunc("/manga/image/", wrap(handlers.HandleMangaImageProxy))
|
||||
|
||||
|
||||
@@ -51,6 +51,21 @@ fanqie:
|
||||
# 是否启用段评功能(默认true,启用段评)
|
||||
enable_review: true
|
||||
|
||||
# 视频处理配置
|
||||
video:
|
||||
# 输出模式:proxy / url
|
||||
# proxy: 返回本地解密代理URL /video/proxy/{key}(已解密,可直接播放,推荐)
|
||||
# url: 返回原始CDN链接(内容为 CENC 加密,需自行解密)
|
||||
output_mode: "proxy"
|
||||
|
||||
# 默认清晰度:max(最高档)/ 360p/480p/540p/720p / 档位 key(video_1..N)
|
||||
# 留空返回全部清晰度;/video 接口的 quality 参数优先于此配置
|
||||
quality: "max"
|
||||
|
||||
# 解密后视频的磁盘缓存(同一视频重复播放直接读本地文件,无需重新下载解密)
|
||||
cache_enabled: true
|
||||
cache_path: "./video_cache"
|
||||
|
||||
# 漫画处理配置
|
||||
manga:
|
||||
# 输出模式:proxy / data_uri / url
|
||||
|
||||
@@ -7,10 +7,15 @@
|
||||
# ./deploy.sh v1.2.0 # 编译 + 部署(指定版本)
|
||||
# ./deploy.sh v1.2.0 --init # 首次初始化(写 systemd/nginx 配置)
|
||||
# ./deploy.sh v1.2.0 --no-pull # 跳过 git pull
|
||||
# ./deploy.sh v1.2.0 --no-autostart # 部署后不开机自启
|
||||
# ./deploy.sh v1.2.0 --no-restart # 只部署,不重启服务
|
||||
# ./deploy.sh --stop # 停止服务
|
||||
# ./deploy.sh --start # 启动服务
|
||||
# ./deploy.sh --build-only # 只编译,不部署
|
||||
# ./deploy.sh --rollback # 交互式回滚到指定版本
|
||||
# ./deploy.sh --rollback v1.0.0 # 直接回滚到指定版本
|
||||
# ./deploy.sh --list # 列出所有已部署版本
|
||||
# ./deploy.sh --sync-nginx # 更新线上 nginx 配置(备份+校验+失败回滚)
|
||||
# ./deploy.sh --help # 显示帮助
|
||||
# ============================================================
|
||||
|
||||
@@ -35,9 +40,11 @@ NGINX_CONF="${NGINX_CONF:-/etc/nginx/conf.d/${APP_NAME}.conf}"
|
||||
APP_PORT="${APP_PORT:-40180}" # 程序监听端口
|
||||
DOMAIN="${DOMAIN:-fq.20010117.xyz}" # 域名
|
||||
CERT_EMAIL="${CERT_EMAIL:-admin@${DOMAIN}}" # 证书申请邮箱(过期提醒)
|
||||
CERT_DIR="${CERT_DIR:-/etc/nginx/ssl}" # 证书目录(acme.sh --install-cert 安装位置)
|
||||
BUILD_TARGET="${BUILD_TARGET:-./cmd/fanqie}" # go build 的包路径
|
||||
ENV_FILE="${ENV_FILE:-${SRC_DIR}/.env}" # 应用环境变量(.env.example 为模板)
|
||||
KEEP_VERSIONS="${KEEP_VERSIONS:-5}" # 保留最近几个版本
|
||||
AUTO_START="${AUTO_START:-true}" # 服务是否开机自启(--no-autostart 覆盖)
|
||||
|
||||
# ==================== 颜色与日志 ====================
|
||||
C_GREEN='\033[1;32m'; C_YELLOW='\033[1;33m'; C_RED='\033[1;31m'; C_BLUE='\033[1;34m'; C_RESET='\033[0m'
|
||||
@@ -61,6 +68,11 @@ ROLLBACK=false
|
||||
ROLLBACK_VERSION=""
|
||||
LIST=false
|
||||
FORCE=false
|
||||
SYNC_NGINX=false
|
||||
AUTO_START="${AUTO_START:-true}"
|
||||
NO_RESTART=false
|
||||
STOP=false
|
||||
START=false
|
||||
|
||||
print_help() {
|
||||
cat <<EOF
|
||||
@@ -69,10 +81,15 @@ print_help() {
|
||||
选项:
|
||||
--init 首次初始化,写入 systemd 和 nginx 配置
|
||||
--no-pull 跳过 git pull
|
||||
--no-autostart 服务不设置开机自启(默认自启)
|
||||
--no-restart 只部署不重启服务(自启设置仍会应用)
|
||||
--stop 停止服务后退出
|
||||
--start 启动服务后退出
|
||||
--build-only 只编译,不部署、不重启服务
|
||||
--force, -f 允许覆盖已存在的同名版本(默认报错退出)
|
||||
--rollback [版本] 回滚到指定版本(不带版本号则交互式选择)
|
||||
--list 列出所有已部署的版本
|
||||
--sync-nginx 只更新 nginx 配置(备份旧配置,校验失败自动回滚)
|
||||
--help, -h 显示此帮助
|
||||
|
||||
示例:
|
||||
@@ -93,6 +110,10 @@ while [ $i -lt ${#ARGS[@]} ]; do
|
||||
case "$arg" in
|
||||
--init) INIT=true ;;
|
||||
--no-pull) NO_PULL=true ;;
|
||||
--no-autostart) AUTO_START=false ;;
|
||||
--no-restart) NO_RESTART=true ;;
|
||||
--stop) STOP=true ;;
|
||||
--start) START=true ;;
|
||||
--build-only) BUILD_ONLY=true ;;
|
||||
--rollback)
|
||||
ROLLBACK=true
|
||||
@@ -103,6 +124,7 @@ while [ $i -lt ${#ARGS[@]} ]; do
|
||||
fi
|
||||
;;
|
||||
--list) LIST=true ;;
|
||||
--sync-nginx) SYNC_NGINX=true ;;
|
||||
--force|-f) FORCE=true ;;
|
||||
--help|-h) print_help; exit 0 ;;
|
||||
v*) VERSION="$arg" ;;
|
||||
@@ -167,19 +189,35 @@ cleanup_old_versions() {
|
||||
done
|
||||
}
|
||||
|
||||
# 重启服务 + 验证
|
||||
restart_and_verify() {
|
||||
log "重启 ${APP_NAME} 服务..."
|
||||
# 注意:不要用 "list-unit-files | grep -q"——grep -q 提前退出会让 systemctl 收到
|
||||
# SIGPIPE,在 pipefail 下整条管道判假(unit 多的机器必踩),误报"服务不存在"
|
||||
if systemctl cat "${APP_NAME}" >/dev/null 2>&1; then
|
||||
$SUDO systemctl restart "${APP_NAME}"
|
||||
# 应用开机自启设置(AUTO_START 由 --no-autostart / .deploy.env 决定)
|
||||
apply_autostart() {
|
||||
if [ "$AUTO_START" = true ]; then
|
||||
$SUDO systemctl enable "${APP_NAME}" >/dev/null 2>&1 || true
|
||||
else
|
||||
$SUDO systemctl disable "${APP_NAME}" >/dev/null 2>&1 || true
|
||||
info "开机自启已禁用(--no-autostart)"
|
||||
fi
|
||||
}
|
||||
|
||||
# 重启服务 + 验证
|
||||
restart_and_verify() {
|
||||
# 注意:不要用 "list-unit-files | grep -q"——grep -q 提前退出会让 systemctl 收到
|
||||
# SIGPIPE,在 pipefail 下整条管道判假(unit 多的机器必踩),误报"服务不存在"
|
||||
if ! systemctl cat "${APP_NAME}" >/dev/null 2>&1; then
|
||||
warn "服务 ${APP_NAME}.service 不存在,请先执行 $0 --init"
|
||||
return 0
|
||||
fi
|
||||
|
||||
apply_autostart
|
||||
|
||||
if [ "$NO_RESTART" = true ]; then
|
||||
info "跳过服务重启(--no-restart),需要时执行: sudo systemctl restart ${APP_NAME}"
|
||||
return 0
|
||||
fi
|
||||
|
||||
log "重启 ${APP_NAME} 服务..."
|
||||
$SUDO systemctl restart "${APP_NAME}"
|
||||
|
||||
if command -v nginx >/dev/null 2>&1; then
|
||||
$SUDO systemctl reload nginx 2>/dev/null || $SUDO nginx -s reload 2>/dev/null || true
|
||||
fi
|
||||
@@ -206,12 +244,152 @@ restart_and_verify() {
|
||||
$SUDO journalctl -u "${APP_NAME}" -n 15 --no-pager || true
|
||||
}
|
||||
|
||||
|
||||
# 写入 nginx 配置(--init 与 --sync-nginx 共用的唯一模板来源)
|
||||
# 模板自带完整 443/证书配置(证书存在时启用),不依赖签发工具注入——
|
||||
# 这样 --sync-nginx 覆盖配置时不会丢失 HTTPS 段(注入式配置会被覆盖回 80-only)
|
||||
write_nginx_conf() {
|
||||
# 反代 location(80 无证书时与 443 共用)
|
||||
local proxy_locations
|
||||
proxy_locations=$(cat <<LOC_EOF
|
||||
|
||||
# 视频解密代理:关闭缓冲,分片(Range/206)直通,避免 nginx 对大文件二次落盘
|
||||
location /video/proxy/ {
|
||||
proxy_pass http://127.0.0.1:${APP_PORT};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host \$host;
|
||||
proxy_set_header X-Real-IP \$remote_addr;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:${APP_PORT};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host \$host;
|
||||
proxy_set_header X-Real-IP \$remote_addr;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
proxy_set_header Upgrade \$http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
LOC_EOF
|
||||
)
|
||||
|
||||
local ssl_block=""
|
||||
if [ -f "${CERT_DIR}/${DOMAIN}/fullchain.pem" ]; then
|
||||
log "检测到 ${DOMAIN} 证书,配置启用 443"
|
||||
ssl_block=$(cat <<SSL_EOF
|
||||
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name ${DOMAIN};
|
||||
|
||||
ssl_certificate ${CERT_DIR}/${DOMAIN}/fullchain.pem;
|
||||
ssl_certificate_key ${CERT_DIR}/${DOMAIN}/privkey.pem;
|
||||
ssl_protocols TLSv1.2 TLSv1.3;
|
||||
|
||||
access_log /var/log/nginx/${APP_NAME}.access.log;
|
||||
error_log /var/log/nginx/${APP_NAME}.error.log;
|
||||
${proxy_locations}
|
||||
}
|
||||
SSL_EOF
|
||||
)
|
||||
else
|
||||
warn "未找到 ${CERT_DIR}/${DOMAIN}/ 证书,本次仅写 80 配置(不跳转 HTTPS);证书签发后重跑: $0 --sync-nginx"
|
||||
fi
|
||||
|
||||
# 80 端口:有证书时仅 ACME 验证 + 301 跳转;无证书时直接反代
|
||||
local root_location
|
||||
if [ -n "${ssl_block}" ]; then
|
||||
root_location=' location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}'
|
||||
else
|
||||
root_location="${proxy_locations}"
|
||||
fi
|
||||
|
||||
$SUDO tee "${NGINX_CONF}" >/dev/null <<NGINX_EOF
|
||||
server {
|
||||
listen 80;
|
||||
server_name ${DOMAIN};
|
||||
|
||||
access_log /var/log/nginx/${APP_NAME}.access.log;
|
||||
error_log /var/log/nginx/${APP_NAME}.error.log;
|
||||
|
||||
# ACME http-01 验证(acme.sh webroot 模式依赖)
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/html;
|
||||
}
|
||||
|
||||
${root_location}
|
||||
}${ssl_block}
|
||||
NGINX_EOF
|
||||
}
|
||||
|
||||
# 更新已部署服务器的 nginx 配置:备份 → 重写 → 校验 → 失败回滚
|
||||
sync_nginx_conf() {
|
||||
local backup=""
|
||||
if [ -f "${NGINX_CONF}" ]; then
|
||||
backup="${NGINX_CONF}.bak.$(date +%Y%m%d%H%M%S)"
|
||||
$SUDO cp "${NGINX_CONF}" "${backup}"
|
||||
log "已备份原配置: ${backup}"
|
||||
else
|
||||
warn "nginx 配置不存在,将写入全新配置: ${NGINX_CONF}"
|
||||
fi
|
||||
|
||||
write_nginx_conf
|
||||
log "已写入新配置: ${NGINX_CONF}"
|
||||
|
||||
if $SUDO nginx -t; then
|
||||
$SUDO systemctl reload nginx 2>/dev/null || $SUDO nginx -s reload 2>/dev/null || true
|
||||
log "nginx 配置已更新并重载"
|
||||
else
|
||||
err "nginx -t 校验失败"
|
||||
if [ -n "${backup}" ] && [ -f "${backup}" ]; then
|
||||
$SUDO cp "${backup}" "${NGINX_CONF}"
|
||||
if $SUDO nginx -t >/dev/null 2>&1; then
|
||||
$SUDO systemctl reload nginx 2>/dev/null || $SUDO nginx -s reload 2>/dev/null || true
|
||||
warn "已回滚到备份配置: ${backup}"
|
||||
fi
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
# ==================== --list ====================
|
||||
if [ "$LIST" = true ]; then
|
||||
list_versions
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ==================== --sync-nginx ====================
|
||||
# 只更新 nginx 配置(给已部署服务器同步模板变更用),不动二进制与服务
|
||||
if [ "$SYNC_NGINX" = true ]; then
|
||||
command -v nginx >/dev/null 2>&1 || { err "未找到 nginx"; exit 1; }
|
||||
sync_nginx_conf
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ==================== --stop / --start ====================
|
||||
if [ "$STOP" = true ] || [ "$START" = true ]; then
|
||||
systemctl cat "${APP_NAME}" >/dev/null 2>&1 || { err "服务 ${APP_NAME}.service 不存在,请先执行 $0 --init"; exit 1; }
|
||||
if [ "$STOP" = true ]; then
|
||||
$SUDO systemctl stop "${APP_NAME}"
|
||||
log "✅ 已停止 ${APP_NAME}(开机自启设置不变)"
|
||||
else
|
||||
$SUDO systemctl start "${APP_NAME}"
|
||||
sleep 1
|
||||
$SUDO systemctl status "${APP_NAME}" --no-pager -l | head -n 15 || true
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ==================== --rollback ====================
|
||||
if [ "$ROLLBACK" = true ]; then
|
||||
if [ ! -d "${BIN_DIR}" ]; then
|
||||
@@ -326,55 +504,34 @@ WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
log "初始化 Nginx 配置: ${NGINX_CONF}"
|
||||
$SUDO tee "${NGINX_CONF}" >/dev/null <<EOF
|
||||
server {
|
||||
listen 80;
|
||||
server_name ${DOMAIN};
|
||||
|
||||
access_log /var/log/nginx/${APP_NAME}.access.log;
|
||||
error_log /var/log/nginx/${APP_NAME}.error.log;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:${APP_PORT};
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host \$host;
|
||||
proxy_set_header X-Real-IP \$remote_addr;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto \$scheme;
|
||||
proxy_set_header Upgrade \$http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_read_timeout 300s;
|
||||
proxy_send_timeout 300s;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
write_nginx_conf
|
||||
|
||||
|
||||
# ---- Certbot 续期后自动重载 Nginx(deploy-hook 只在续期成功时执行)----
|
||||
HOOK_FILE="/etc/letsencrypt/renewal-hooks/deploy/reload-nginx.sh"
|
||||
if [ ! -f "${HOOK_FILE}" ]; then
|
||||
log "创建 Certbot 续期重载 Hook: ${HOOK_FILE}"
|
||||
$SUDO mkdir -p /etc/letsencrypt/renewal-hooks/deploy/
|
||||
$SUDO tee "${HOOK_FILE}" >/dev/null <<'HOOK'
|
||||
#!/bin/bash
|
||||
if /usr/sbin/nginx -t 2>/dev/null; then
|
||||
systemctl reload nginx
|
||||
fi
|
||||
HOOK
|
||||
$SUDO chmod +x "${HOOK_FILE}"
|
||||
fi
|
||||
|
||||
# ---- 首次初始化自动申请 HTTPS 证书(一次性;续期由 certbot.timer 自动处理)----
|
||||
if [ ! -d "/etc/letsencrypt/live/${DOMAIN}" ]; then
|
||||
if command -v certbot >/dev/null 2>&1; then
|
||||
log "未检测到证书,尝试自动申请: ${DOMAIN}"
|
||||
$SUDO certbot --nginx -d "${DOMAIN}" --non-interactive --agree-tos -m "${CERT_EMAIL}" --redirect \
|
||||
|| warn "证书申请失败,请检查域名解析与 80 端口;可稍后手动执行 certbot --nginx -d ${DOMAIN}"
|
||||
else
|
||||
warn "未安装 certbot,跳过证书申请。可手动执行: dnf install certbot python3-certbot-nginx"
|
||||
fi
|
||||
else
|
||||
# ---- 首次初始化自动申请 HTTPS 证书(一次性;续期由 acme.sh cron 自动处理)----
|
||||
if [ -f "${CERT_DIR}/${DOMAIN}/fullchain.pem" ]; then
|
||||
log "证书已存在,跳过申请"
|
||||
else
|
||||
# 定位 acme.sh:PATH → 当前用户目录 → root 目录(sudo 后 HOME 可能被重置)
|
||||
ACME_SH="$(command -v acme.sh 2>/dev/null || true)"
|
||||
for c in "${HOME}/.acme.sh/acme.sh" "/root/.acme.sh/acme.sh"; do
|
||||
if [ -z "$ACME_SH" ] && [ -x "$c" ]; then ACME_SH="$c"; fi
|
||||
done
|
||||
if [ -z "$ACME_SH" ]; then
|
||||
err "未找到 acme.sh,请先安装: curl https://get.acme.sh | sh -s email=${CERT_EMAIL}"
|
||||
exit 1
|
||||
fi
|
||||
log "未检测到证书,使用 acme.sh 申请: ${DOMAIN}"
|
||||
$SUDO mkdir -p /var/www/html "${CERT_DIR}/${DOMAIN}"
|
||||
if $SUDO "$ACME_SH" --issue -d "${DOMAIN}" -w /var/www/html --server letsencrypt --keylength ec-256 -m "${CERT_EMAIL}" \
|
||||
&& $SUDO "$ACME_SH" --install-cert -d "${DOMAIN}" --ecc \
|
||||
--fullchain-file "${CERT_DIR}/${DOMAIN}/fullchain.pem" \
|
||||
--key-file "${CERT_DIR}/${DOMAIN}/privkey.pem" \
|
||||
--reloadcmd "systemctl reload nginx"; then
|
||||
log "证书申请成功,写入 443 配置..."
|
||||
write_nginx_conf
|
||||
else
|
||||
warn "证书申请失败,请检查域名解析与 80 端口;成功后重跑: $0 --sync-nginx"
|
||||
fi
|
||||
fi
|
||||
|
||||
if command -v getenforce >/dev/null 2>&1 && [ "$(getenforce)" != "Disabled" ]; then
|
||||
|
||||
@@ -41,6 +41,7 @@ type FanqieConfig struct {
|
||||
Signature string `mapstructure:"signature"` // 签名方法: sign2 / sign4
|
||||
Content ContentConfig `mapstructure:"content"`
|
||||
Manga MangaConfig `mapstructure:"manga"`
|
||||
Video VideoConfig `mapstructure:"video"`
|
||||
}
|
||||
|
||||
// ContentConfig 内容处理配置
|
||||
@@ -60,6 +61,14 @@ type MangaConfig struct {
|
||||
OutputMode string `mapstructure:"output_mode"` // 输出模式: data_uri / base64 / url
|
||||
}
|
||||
|
||||
// VideoConfig 视频处理配置
|
||||
type VideoConfig struct {
|
||||
OutputMode string `mapstructure:"output_mode"` // 输出模式: url(原始CDN链接,内容加密)/ proxy(本地解密代理,可直接播放)
|
||||
Quality string `mapstructure:"quality"` // 默认清晰度: max(最高档)/ 360p/480p/... 或档位 key(video_1..N),留空返回全部
|
||||
CacheEnabled bool `mapstructure:"cache_enabled"` // 解密后视频的磁盘缓存
|
||||
CachePath string `mapstructure:"cache_path"` // 缓存目录
|
||||
}
|
||||
|
||||
// CacheConfig 缓存配置
|
||||
type CacheConfig struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
@@ -197,6 +206,12 @@ func setDefaults() {
|
||||
// 漫画处理配置
|
||||
viper.SetDefault("fanqie.manga.output_mode", "url")
|
||||
|
||||
// 视频处理配置
|
||||
viper.SetDefault("fanqie.video.output_mode", "proxy")
|
||||
viper.SetDefault("fanqie.video.quality", "max")
|
||||
viper.SetDefault("fanqie.video.cache_enabled", true)
|
||||
viper.SetDefault("fanqie.video.cache_path", "./video_cache")
|
||||
|
||||
// 缓存配置
|
||||
viper.SetDefault("cache.enabled", true)
|
||||
viper.SetDefault("cache.backend", "sqlite")
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// video 段配置读取:显式值生效、缺省回落 viper 默认值
|
||||
func TestVideoConfig(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "config.yaml")
|
||||
os.WriteFile(path, []byte(`
|
||||
fanqie:
|
||||
video:
|
||||
output_mode: "proxy"
|
||||
quality: "720p"
|
||||
`), 0644)
|
||||
|
||||
v := viper.New()
|
||||
v.SetConfigFile(path)
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var c Config
|
||||
if err := v.Unmarshal(&c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.Fanqie.Video.OutputMode != "proxy" || c.Fanqie.Video.Quality != "720p" {
|
||||
t.Fatalf("显式配置未生效: %+v", c.Fanqie.Video)
|
||||
}
|
||||
|
||||
// 缺省回落
|
||||
v2 := viper.New()
|
||||
v2.SetDefault("fanqie.video.output_mode", "url")
|
||||
v2.SetDefault("fanqie.video.quality", "")
|
||||
var c2 Config
|
||||
if err := v2.Unmarshal(&c2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c2.Fanqie.Video.OutputMode != "url" || c2.Fanqie.Video.Quality != "" {
|
||||
t.Fatalf("默认值不符: %+v", c2.Fanqie.Video)
|
||||
}
|
||||
}
|
||||
@@ -52,54 +52,61 @@ func GenerateAudioProxyURL(originalURL, deviceID string, headers map[string]stri
|
||||
return fmt.Sprintf("/audio/proxy/%s", key)
|
||||
}
|
||||
|
||||
// HandleAudioProxy 处理音频代理请求(流式返回,调用方负责 Close)
|
||||
func HandleAudioProxy(key string) (io.ReadCloser, string, error) {
|
||||
var originalURL, deviceID string
|
||||
var headers map[string]string
|
||||
// loadMediaProxyEntry 读取媒体代理映射(audio/video 共用;Redis 优先,回退 SQL)
|
||||
type mediaProxyEntry struct {
|
||||
OriginalURL string
|
||||
DeviceID string
|
||||
Headers map[string]string
|
||||
}
|
||||
|
||||
func loadMediaProxyEntry(key string) (*mediaProxyEntry, error) {
|
||||
if redisCache != nil {
|
||||
entry, err := loadAudioProxyEntry(key)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
return nil, err
|
||||
}
|
||||
originalURL, deviceID, headers = entry.OriginalURL, entry.DeviceID, entry.Headers
|
||||
} else {
|
||||
if cacheDB == nil {
|
||||
return nil, "", fmt.Errorf("数据库未初始化")
|
||||
}
|
||||
|
||||
// 从数据库获取音频信息
|
||||
var headersJSON string
|
||||
var createdAt int64
|
||||
|
||||
err := cacheDB.QueryRow(q(`
|
||||
SELECT original_url, device_id, headers, created_at
|
||||
FROM audio_cache WHERE key = ?
|
||||
`), key).Scan(&originalURL, &deviceID, &headersJSON, &createdAt)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, "", fmt.Errorf("音频信息不存在,请先调用 /audio 接口")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("查询音频缓存失败: %w", err)
|
||||
}
|
||||
|
||||
// 检查缓存是否过期(2小时,匹配CDN链接有效期)
|
||||
if time.Now().Unix()-createdAt > 7200 { // 2小时 = 7200秒
|
||||
// 清理过期缓存
|
||||
cacheDB.Exec(q("DELETE FROM audio_cache WHERE key = ?"), key)
|
||||
return nil, "", fmt.Errorf("音频信息已过期,请重新调用 /audio 接口")
|
||||
}
|
||||
|
||||
// 解析headers
|
||||
json.Unmarshal([]byte(headersJSON), &headers)
|
||||
return &mediaProxyEntry{OriginalURL: entry.OriginalURL, DeviceID: entry.DeviceID, Headers: entry.Headers}, nil
|
||||
}
|
||||
if cacheDB == nil {
|
||||
return nil, fmt.Errorf("数据库未初始化")
|
||||
}
|
||||
|
||||
var originalURL, deviceID, headersJSON string
|
||||
var createdAt int64
|
||||
err := cacheDB.QueryRow(q(`
|
||||
SELECT original_url, device_id, headers, created_at
|
||||
FROM audio_cache WHERE key = ?
|
||||
`), key).Scan(&originalURL, &deviceID, &headersJSON, &createdAt)
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, fmt.Errorf("媒体信息不存在,请先调用 /audio 或 /video 接口")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("查询媒体缓存失败: %w", err)
|
||||
}
|
||||
// 过期清理(2小时,匹配CDN链接有效期)
|
||||
if time.Now().Unix()-createdAt > 7200 {
|
||||
cacheDB.Exec(q("DELETE FROM audio_cache WHERE key = ?"), key)
|
||||
return nil, fmt.Errorf("媒体信息已过期,请重新调用接口")
|
||||
}
|
||||
|
||||
var headers map[string]string
|
||||
json.Unmarshal([]byte(headersJSON), &headers)
|
||||
if headers == nil {
|
||||
headers = make(map[string]string)
|
||||
}
|
||||
return &mediaProxyEntry{OriginalURL: originalURL, DeviceID: deviceID, Headers: headers}, nil
|
||||
}
|
||||
|
||||
// HandleAudioProxy 处理音频代理请求(流式返回,调用方负责 Close)
|
||||
func HandleAudioProxy(key string) (io.ReadCloser, string, error) {
|
||||
entry, err := loadMediaProxyEntry(key)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
|
||||
// 下载音频内容(流式),使用关联的设备信息
|
||||
body, contentType, err := downloadMediaWithRetry(originalURL, deviceID, headers, 3)
|
||||
body, contentType, err := downloadMediaWithRetry(entry.OriginalURL, entry.DeviceID, entry.Headers, 3)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("下载音频失败: %w", err)
|
||||
}
|
||||
|
||||
@@ -483,6 +483,9 @@ func CleanupExpiredCache() error {
|
||||
cacheLogger.Info(fmt.Sprintf("已清理 %d 条过期缓存(创建时间早于 %d 秒前)", rowsAffected, cfg.Cache.CleanupSeconds))
|
||||
}
|
||||
|
||||
// 顺带清理磁盘视频缓存(7 天未访问的解密文件)
|
||||
CleanupVideoCache()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ func loadAudioProxyEntry(key string) (*audioProxyEntry, error) {
|
||||
|
||||
val, err := redisCache.Get(ctx, redisAudioKeyPrefix+key).Result()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("音频信息不存在或已过期,请重新调用 /audio 接口")
|
||||
return nil, fmt.Errorf("媒体信息不存在或已过期,请重新调用 /audio 或 /video 接口")
|
||||
}
|
||||
|
||||
var entry audioProxyEntry
|
||||
|
||||
+226
-17
@@ -1,17 +1,27 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fanqie/internal/common"
|
||||
"fanqie/internal/config"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var videoLogger = common.NewLogger("video", "INFO", "")
|
||||
|
||||
// HandleVideo 处理获取视频(支持批量和单个接口)
|
||||
func HandleVideo(itemIDs interface{}) (string, error) {
|
||||
// HandleVideo 处理获取视频(支持批量和单个接口)。
|
||||
// output: url(默认,返回原始CDN链接,内容为 CENC 加密)/ proxy(返回本地解密代理链接,可直接播放)
|
||||
// quality: 清晰度过滤,支持 max(最高档,默认)、definition(360p/480p/...)或档位 key(video_1..N),空为全部;
|
||||
// 未传时回退 config fanqie.video.quality,output 为空时回退 fanqie.video.output_mode
|
||||
func HandleVideo(itemIDs, output, quality interface{}) (string, error) {
|
||||
if itemIDs == nil || itemIDs == "" {
|
||||
return BuildSuccessResponse([]interface{}{}), nil
|
||||
}
|
||||
@@ -44,6 +54,26 @@ func HandleVideo(itemIDs interface{}) (string, error) {
|
||||
requestBody := fmt.Sprintf(`{"biz_param":{"device_level":3,"need_all_video_definition":true,"need_mp4_align":false,"use_os_player":false,"video_platform":1024},"video_id":"%s"}`,
|
||||
itemIDStr)
|
||||
|
||||
outputMode := ParseStringParam(output, "")
|
||||
qualityFilter := ParseStringParam(quality, "")
|
||||
if cfg := config.GetAppConfig(); cfg != nil {
|
||||
if outputMode == "" {
|
||||
outputMode = cfg.Fanqie.Video.OutputMode
|
||||
}
|
||||
if qualityFilter == "" {
|
||||
qualityFilter = cfg.Fanqie.Video.Quality
|
||||
}
|
||||
}
|
||||
if outputMode == "" {
|
||||
outputMode = "url"
|
||||
}
|
||||
deviceID := ""
|
||||
if outputMode == "proxy" {
|
||||
if dev := GetCurrentDevice(); dev != nil {
|
||||
deviceID = dev.DeviceHeader
|
||||
}
|
||||
}
|
||||
|
||||
// 使用 GorgonRequest 添加签名和设备信息
|
||||
resp, err := GorgonRequest(url, map[string]interface{}{
|
||||
"method": "POST",
|
||||
@@ -86,7 +116,14 @@ func HandleVideo(itemIDs interface{}) (string, error) {
|
||||
|
||||
if data != nil {
|
||||
if videoModelStr, ok := data["video_model"].(string); ok && isSingle {
|
||||
decodedModel := decodeVideoModelAsJSON(videoModelStr)
|
||||
decodedModel := decodeVideoModelAsJSON(videoModelStr, outputMode, deviceID, qualityFilter)
|
||||
|
||||
// 清晰度过滤无匹配时报错(调用方能立即发现参数写错)
|
||||
if qualityFilter != "" {
|
||||
if vl, ok := decodedModel.(map[string]interface{})["video_list"].(map[string]interface{}); ok && len(vl) == 0 {
|
||||
return BuildErrorResponse(fmt.Sprintf("无匹配清晰度: %s(可用档位见 video_list)", qualityFilter)), nil
|
||||
}
|
||||
}
|
||||
|
||||
// 单个接口直接返回 video_model
|
||||
response := map[string]interface{}{
|
||||
@@ -103,7 +140,7 @@ func HandleVideo(itemIDs interface{}) (string, error) {
|
||||
for itemID, itemData := range data {
|
||||
if itemMap, ok := itemData.(map[string]interface{}); ok {
|
||||
if videoModelStr, ok := itemMap["video_model"].(string); ok {
|
||||
decodedModel := decodeVideoModelAsJSON(videoModelStr)
|
||||
decodedModel := decodeVideoModelAsJSON(videoModelStr, outputMode, deviceID, qualityFilter)
|
||||
result[itemID] = map[string]interface{}{
|
||||
"video_model": decodedModel,
|
||||
}
|
||||
@@ -134,8 +171,10 @@ func HandleVideo(itemIDs interface{}) (string, error) {
|
||||
return BuildErrorResponse(errMsg), nil
|
||||
}
|
||||
|
||||
// decodeVideoModelAsJSON 解析并解码 video_model,返回关键字段的 JSON 对象
|
||||
func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
// decodeVideoModelAsJSON 解析并解码 video_model,返回关键字段的 JSON 对象。
|
||||
// outputMode=proxy 时把 CDN 链接替换为本地解密代理链接(/video/proxy/{key})
|
||||
// qualityFilter 非空时只保留匹配的清晰度(definition 或档位 key,大小写不敏感)
|
||||
func decodeVideoModelAsJSON(videoModelStr, outputMode, deviceID, qualityFilter string) interface{} {
|
||||
// 解析 video_model JSON 字符串
|
||||
var videoModel map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(videoModelStr), &videoModel); err != nil {
|
||||
@@ -151,8 +190,10 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
result := make(map[string]interface{})
|
||||
|
||||
// 提取关键字段
|
||||
if videoID, ok := videoModel["video_id"].(string); ok {
|
||||
result["video_id"] = videoID
|
||||
videoID := ""
|
||||
if v, ok := videoModel["video_id"].(string); ok {
|
||||
result["video_id"] = v
|
||||
videoID = v
|
||||
}
|
||||
if duration, ok := videoModel["video_duration"].(float64); ok {
|
||||
result["video_duration"] = formatDuration(duration)
|
||||
@@ -167,10 +208,37 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
|
||||
// 处理 video_list
|
||||
if videoList, ok := videoModel["video_list"].(map[string]interface{}); ok {
|
||||
// max/best:解析为实际最高档位 key(不同视频可用档位不同,按 vheight/definition 取最大)
|
||||
if strings.EqualFold(qualityFilter, "max") || strings.EqualFold(qualityFilter, "best") {
|
||||
bestKey, bestH := "", 0
|
||||
for q, qd := range videoList {
|
||||
qm, ok := qd.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if h := qualityHeight(qm); h > bestH {
|
||||
bestH, bestKey = h, q
|
||||
}
|
||||
}
|
||||
qualityFilter = bestKey
|
||||
}
|
||||
|
||||
processedVideoList := make(map[string]interface{})
|
||||
|
||||
for quality, qualityData := range videoList {
|
||||
if qualityMap, ok := qualityData.(map[string]interface{}); ok {
|
||||
// 清晰度过滤:匹配档位 key(video_1)或 definition(720p)
|
||||
if qualityFilter != "" {
|
||||
def, _ := qualityMap["definition"].(string)
|
||||
if !strings.EqualFold(quality, qualityFilter) && !strings.EqualFold(def, qualityFilter) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
// spade_a(PlayAuth):解出 CENC 内容密钥的种子,proxy 模式随代理下发
|
||||
spadeA := ""
|
||||
if v, ok := qualityMap["spade_a"].(string); ok {
|
||||
spadeA = v
|
||||
}
|
||||
// 只保留关键字段
|
||||
qualityInfo := make(map[string]interface{})
|
||||
|
||||
@@ -205,18 +273,23 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
}
|
||||
}
|
||||
|
||||
// 解码 main_url
|
||||
if mainURL, ok := qualityMap["main_url"].(string); ok {
|
||||
if decoded, err := base64.StdEncoding.DecodeString(mainURL); err == nil {
|
||||
qualityInfo["main_url"] = string(decoded)
|
||||
// 解码 main_url / backup_url_1(base64 的CDN链接),proxy 模式替换为解密代理。
|
||||
// 代理 key 用 videoID+档位(稳定),同一视频重复调用复用磁盘缓存
|
||||
processURL := func(b64 string) interface{} {
|
||||
decoded, err := base64.StdEncoding.DecodeString(b64)
|
||||
if err != nil {
|
||||
return b64
|
||||
}
|
||||
if outputMode == "proxy" && spadeA != "" && videoID != "" {
|
||||
return GenerateVideoProxyURL(videoID+"_"+quality, string(decoded), deviceID, spadeA)
|
||||
}
|
||||
return string(decoded)
|
||||
}
|
||||
if mainURL, ok := qualityMap["main_url"].(string); ok {
|
||||
qualityInfo["main_url"] = processURL(mainURL)
|
||||
}
|
||||
|
||||
// 解码 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)
|
||||
}
|
||||
qualityInfo["backup_url_1"] = processURL(backupURL)
|
||||
}
|
||||
|
||||
processedVideoList[quality] = qualityInfo
|
||||
@@ -229,6 +302,22 @@ func decodeVideoModelAsJSON(videoModelStr string) interface{} {
|
||||
return result
|
||||
}
|
||||
|
||||
// qualityHeight 取清晰度的比较高度:优先 vheight,缺失时从 definition(如 "720p")解析
|
||||
func qualityHeight(qm map[string]interface{}) int {
|
||||
if h, ok := qm["vheight"].(float64); ok && h > 0 {
|
||||
return int(h)
|
||||
}
|
||||
def, _ := qm["definition"].(string)
|
||||
n := 0
|
||||
for _, c := range def {
|
||||
if c < '0' || c > '9' {
|
||||
break
|
||||
}
|
||||
n = n*10 + int(c-'0')
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// formatDuration 将秒数转换为可读的时间格式
|
||||
func formatDuration(seconds float64) string {
|
||||
totalSeconds := int(math.Round(seconds))
|
||||
@@ -278,3 +367,123 @@ func formatBitrate(bitrate float64) string {
|
||||
mbps := kbps / unit
|
||||
return fmt.Sprintf("%.2f Mbps", mbps)
|
||||
}
|
||||
|
||||
// GenerateVideoProxyURL 生成视频解密代理URL。
|
||||
// cacheKey 需稳定(videoID+档位):映射表覆盖式更新,磁盘缓存按 key 复用
|
||||
func GenerateVideoProxyURL(cacheKey, originalURL, deviceID, spadeA string) string {
|
||||
headers := map[string]string{"x-spade-a": spadeA}
|
||||
if redisCache != nil {
|
||||
saveAudioProxyEntry(cacheKey, &audioProxyEntry{
|
||||
OriginalURL: originalURL,
|
||||
DeviceID: deviceID,
|
||||
Headers: headers,
|
||||
})
|
||||
return "/video/proxy/" + cacheKey
|
||||
}
|
||||
headersJSON, _ := json.Marshal(headers)
|
||||
if cacheDB != nil {
|
||||
cacheDB.Exec(q(`
|
||||
INSERT INTO audio_cache (key, original_url, device_id, headers, created_at, updated_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(key) DO UPDATE SET original_url = excluded.original_url,
|
||||
device_id = excluded.device_id, headers = excluded.headers, updated_at = excluded.updated_at
|
||||
`), cacheKey, originalURL, deviceID, string(headersJSON), time.Now().Unix(), time.Now().Unix())
|
||||
}
|
||||
return "/video/proxy/" + cacheKey
|
||||
}
|
||||
|
||||
// videoCachePath 解密后视频的磁盘缓存路径;缓存未启用返回空串
|
||||
func videoCachePath(key string) string {
|
||||
cfg := config.GetAppConfig()
|
||||
if cfg == nil || !cfg.Fanqie.Video.CacheEnabled || cfg.Fanqie.Video.CachePath == "" {
|
||||
return ""
|
||||
}
|
||||
return filepath.Join(cfg.Fanqie.Video.CachePath, key+".mp4")
|
||||
}
|
||||
|
||||
// HandleVideoProxy 处理视频代理请求:磁盘缓存命中直接返回;否则下载 CENC 加密 MP4 →
|
||||
// SpadeA 解 key → 解密 → 写入缓存。返回 ReadSeeker 供 http.ServeContent(支持 Range/seek)。
|
||||
func HandleVideoProxy(key string) (io.ReadSeeker, string, error) {
|
||||
// 磁盘缓存命中:直接返回文件(映射记录即使过期也不影响已缓存的视频)
|
||||
if p := videoCachePath(key); p != "" {
|
||||
if f, err := os.Open(p); err == nil {
|
||||
return f, "video/mp4", nil
|
||||
}
|
||||
}
|
||||
|
||||
entry, err := loadMediaProxyEntry(key)
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
spadeA := entry.Headers["x-spade-a"]
|
||||
if spadeA == "" {
|
||||
return nil, "", fmt.Errorf("视频信息缺少 spade_a,请重新调用 /video 接口")
|
||||
}
|
||||
|
||||
body, _, err := downloadMediaWithRetry(entry.OriginalURL, entry.DeviceID, entry.Headers, 3)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("下载视频失败: %w", err)
|
||||
}
|
||||
defer body.Close()
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("读取视频失败: %w", err)
|
||||
}
|
||||
|
||||
contentKey, err := DecodeSpadeKey(spadeA)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("解密视频失败: %w", err)
|
||||
}
|
||||
if err := DecryptCENCMP4(data, contentKey); err != nil {
|
||||
return nil, "", fmt.Errorf("解密视频失败: %w", err)
|
||||
}
|
||||
|
||||
// 写入磁盘缓存(临时文件 + rename 原子替换;失败不影响本次返回)
|
||||
if p := videoCachePath(key); p != "" {
|
||||
if err := os.MkdirAll(filepath.Dir(p), 0755); err == nil {
|
||||
if tmp, err := os.CreateTemp(filepath.Dir(p), ".tmp-*"); err == nil {
|
||||
if _, werr := tmp.Write(data); werr == nil {
|
||||
tmp.Close()
|
||||
if err := os.Rename(tmp.Name(), p); err != nil {
|
||||
os.Remove(tmp.Name())
|
||||
}
|
||||
} else {
|
||||
tmp.Close()
|
||||
os.Remove(tmp.Name())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return bytes.NewReader(data), "video/mp4", nil
|
||||
}
|
||||
|
||||
// CleanupVideoCache 清理磁盘视频缓存中 mtime 过早的文件,挂接在缓存定期清理任务中
|
||||
func CleanupVideoCache() {
|
||||
cfg := config.GetAppConfig()
|
||||
if cfg == nil || !cfg.Fanqie.Video.CacheEnabled {
|
||||
return
|
||||
}
|
||||
dir := cfg.Fanqie.Video.CachePath
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
return // 目录不存在等:无缓存可清
|
||||
}
|
||||
const maxAge = 7 * 24 * time.Hour // ponytail: 固定 7 天,需要更长保留时改配置语义
|
||||
cutoff := time.Now().Add(-maxAge)
|
||||
removed := 0
|
||||
for _, e := range entries {
|
||||
info, err := e.Info()
|
||||
if err != nil || info.IsDir() {
|
||||
continue
|
||||
}
|
||||
if info.ModTime().Before(cutoff) {
|
||||
if os.Remove(filepath.Join(dir, e.Name())) == nil {
|
||||
removed++
|
||||
}
|
||||
}
|
||||
}
|
||||
if removed > 0 {
|
||||
videoLogger.Info(fmt.Sprintf("已清理 %d 个过期视频缓存文件", removed))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// ============ SpadeA(黑桃A)PlayAuth 解码 ============
|
||||
//
|
||||
// 番茄短剧/汽水音乐同源的本地 DRM:video_model 每个清晰度的 spade_a
|
||||
// (PlayAuth)经混淆变换直接还原 16 字节 AES-128 内容密钥(32 位 hex 字符串)。
|
||||
// 算法逆向自 SodaMusic v3.5.1(qishui-decrypt-tool),与番茄短剧样本实测一致。
|
||||
|
||||
func bitCount32(v uint32) int {
|
||||
c := v
|
||||
c -= (c >> 1) & 0x55555555
|
||||
c = (c & 0x33333333) + ((c >> 2) & 0x33333333)
|
||||
return int(((c + (c>>4)) & 0x0f0f0f0f) * 0x01010101 >> 24)
|
||||
}
|
||||
|
||||
func decodeBase36Byte(v byte) int {
|
||||
switch {
|
||||
case v >= '0' && v <= '9':
|
||||
return int(v - '0')
|
||||
case v >= 'a' && v <= 'z':
|
||||
return int(v-'a') + 10
|
||||
}
|
||||
return 0xff
|
||||
}
|
||||
|
||||
// decodeSpadeInner 逐字节去混淆:与前一字节异或后减去索引 popcount 与常数
|
||||
func decodeSpadeInner(data []byte) []byte {
|
||||
result := make([]byte, len(data))
|
||||
buff := append([]byte{0xfa, 0x55}, data...)
|
||||
for i := 0; i < len(data); i++ {
|
||||
raw := int(data[i]^buff[i]) - bitCount32(uint32(i)) - 21
|
||||
if raw >= 0 {
|
||||
result[i] = byte(raw)
|
||||
} else {
|
||||
result[i] = byte(((raw % 255) + 255) % 255)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// DecodeSpadeKey 从 spade_a(PlayAuth base64)解出 16 字节 AES 内容密钥
|
||||
func DecodeSpadeKey(playAuthB64 string) ([]byte, error) {
|
||||
raw, err := base64.StdEncoding.DecodeString(playAuthB64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("spade_a base64 解码失败: %w", err)
|
||||
}
|
||||
if len(raw) < 4 {
|
||||
return nil, fmt.Errorf("spade_a 长度不足: %d", len(raw))
|
||||
}
|
||||
padding := int(raw[0]^raw[1]^raw[2]) - 48
|
||||
if padding < 0 || padding >= len(raw)-3 {
|
||||
return nil, fmt.Errorf("spade_a padding 非法: %d", padding)
|
||||
}
|
||||
body := raw[1 : len(raw)-padding]
|
||||
tmp := decodeSpadeInner(body)
|
||||
keyLen := decodeBase36Byte(tmp[0])
|
||||
if keyLen == 0xff {
|
||||
return nil, fmt.Errorf("spade_a key 长度字符非法: %q", tmp[0])
|
||||
}
|
||||
end := len(body) - keyLen
|
||||
if end < 1 || end > len(tmp) {
|
||||
return nil, fmt.Errorf("spade_a key 范围非法: end=%d len=%d", end, len(tmp))
|
||||
}
|
||||
keyHex := string(tmp[1:end])
|
||||
if len(keyHex) != 32 {
|
||||
return nil, fmt.Errorf("spade_a key 长度异常: %d", len(keyHex))
|
||||
}
|
||||
key := make([]byte, 16)
|
||||
for i := 0; i < 16; i++ {
|
||||
if _, err := fmt.Sscanf(keyHex[i*2:i*2+2], "%02x", &key[i]); err != nil {
|
||||
return nil, fmt.Errorf("spade_a key hex 非法: %s", keyHex)
|
||||
}
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
|
||||
// ============ CENC (cenc-aes-ctr) MP4 解密 ============
|
||||
//
|
||||
// 容器为标准 CENC MP4:moov 明文;加密 sample entry(encv/enca)+ senc box
|
||||
// (version 0,每个 sample 8 字节 IV,整样本 AES-128-CTR,无 subsample)。
|
||||
// 解密后把 entry 类型改回原始 codec(sinf/frma 指示),得到可播放文件。
|
||||
|
||||
type mp4Box struct {
|
||||
typ string
|
||||
contentStar int
|
||||
end int
|
||||
}
|
||||
|
||||
// walkBoxes 迭代 [start,end) 内的顶层 box,fn 返回 false 时停止迭代
|
||||
func walkBoxes(data []byte, start, end int, fn func(mp4Box) bool) error {
|
||||
p := start
|
||||
for p+8 <= end {
|
||||
size := int(binary.BigEndian.Uint32(data[p : p+4]))
|
||||
typ := string(data[p+4 : p+8])
|
||||
if size == 1 { // largesize
|
||||
if p+16 > end {
|
||||
return fmt.Errorf("box %s largesize 越界", typ)
|
||||
}
|
||||
size = int(binary.BigEndian.Uint64(data[p+8 : p+16]))
|
||||
// ponytail: >2GB 文件不支持,截断风险可接受
|
||||
if size > len(data) {
|
||||
return fmt.Errorf("box %s 过大", typ)
|
||||
}
|
||||
}
|
||||
if size < 8 || p+size > end {
|
||||
return fmt.Errorf("box %s 尺寸非法 size=%d at %d", typ, size, p)
|
||||
}
|
||||
if !fn(mp4Box{typ: typ, contentStar: p + 8, end: p + size}) {
|
||||
return nil
|
||||
}
|
||||
p += size
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DecryptCENCMP4 原地解密 CENC 加密的 MP4 字节并修复 stsd entry 类型。
|
||||
// 仅支持 senc version 0 + 无 subsample 标志(番茄实测形态),其他形态返回错误。
|
||||
func DecryptCENCMP4(data []byte, key []byte) error {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("内容密钥非法: %w", err)
|
||||
}
|
||||
|
||||
decryptStream := func(ct []byte, iv8 []byte) error {
|
||||
if len(iv8) != 8 {
|
||||
return fmt.Errorf("senc IV 长度异常: %d", len(iv8))
|
||||
}
|
||||
iv := make([]byte, 16)
|
||||
copy(iv, iv8) // 8 字节 IV 置于高位,低 8 字节为块计数器(CENC 标准)
|
||||
cipher.NewCTR(block, iv).XORKeyStream(ct, ct)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 找 moov 并遍历其下所有 trak,逐 trak 解密
|
||||
var trakErr error
|
||||
foundMoov := false
|
||||
if err := walkBoxes(data, 0, len(data), func(b mp4Box) bool {
|
||||
if b.typ != "moov" {
|
||||
return true
|
||||
}
|
||||
foundMoov = true
|
||||
_ = walkBoxes(data, b.contentStar, b.end, func(trak mp4Box) bool {
|
||||
if trak.typ != "trak" {
|
||||
return true
|
||||
}
|
||||
if err := decryptTrak(data, trak, decryptStream); err != nil {
|
||||
trakErr = err
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
return false
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if !foundMoov {
|
||||
return fmt.Errorf("moov box 未找到")
|
||||
}
|
||||
return trakErr
|
||||
}
|
||||
|
||||
// decryptTrak 处理单个 trak:解析 sample 表 + senc,逐样本解密,修补 stsd
|
||||
func decryptTrak(data []byte, trak mp4Box, decryptStream func([]byte, []byte) error) error {
|
||||
// 定位 mdia→minf→stbl
|
||||
stbl, err := findBox(data, trak, "mdia", "minf", "stbl")
|
||||
if err != nil || stbl == nil {
|
||||
return err // 无 stbl 的 trak 跳过
|
||||
}
|
||||
|
||||
var (
|
||||
sizes []int
|
||||
chunkOffsets []int
|
||||
stscEntries [][2]int // {first_chunk, samples_per_chunk}
|
||||
ivs [][]byte
|
||||
stsd *mp4Box
|
||||
haveSizes bool
|
||||
haveOffsets bool
|
||||
haveStsc bool
|
||||
parseErr error
|
||||
)
|
||||
|
||||
if err := walkBoxes(data, stbl.contentStar, stbl.end, func(b mp4Box) bool {
|
||||
switch b.typ {
|
||||
case "stsd":
|
||||
stsd = &b
|
||||
case "stsz":
|
||||
constSize := int(binary.BigEndian.Uint32(data[b.contentStar+4 : b.contentStar+8]))
|
||||
count := int(binary.BigEndian.Uint32(data[b.contentStar+8 : b.contentStar+12]))
|
||||
if constSize != 0 {
|
||||
for i := 0; i < count; i++ {
|
||||
sizes = append(sizes, constSize)
|
||||
}
|
||||
} else {
|
||||
sizes = make([]int, count)
|
||||
for i := 0; i < count; i++ {
|
||||
sizes[i] = int(binary.BigEndian.Uint32(data[b.contentStar+12+i*4 : b.contentStar+16+i*4]))
|
||||
}
|
||||
}
|
||||
haveSizes = true
|
||||
case "stco":
|
||||
count := int(binary.BigEndian.Uint32(data[b.contentStar+4 : b.contentStar+8]))
|
||||
for i := 0; i < count; i++ {
|
||||
chunkOffsets = append(chunkOffsets, int(binary.BigEndian.Uint32(data[b.contentStar+8+i*4:b.contentStar+12+i*4])))
|
||||
}
|
||||
haveOffsets = true
|
||||
case "co64":
|
||||
count := int(binary.BigEndian.Uint32(data[b.contentStar+4 : b.contentStar+8]))
|
||||
for i := 0; i < count; i++ {
|
||||
v := binary.BigEndian.Uint64(data[b.contentStar+8+i*8 : b.contentStar+16+i*8])
|
||||
if v > uint64(len(data)) {
|
||||
parseErr = fmt.Errorf("co64 偏移越界")
|
||||
return false
|
||||
}
|
||||
chunkOffsets = append(chunkOffsets, int(v))
|
||||
}
|
||||
haveOffsets = true
|
||||
case "stsc":
|
||||
count := int(binary.BigEndian.Uint32(data[b.contentStar+4 : b.contentStar+8]))
|
||||
for i := 0; i < count; i++ {
|
||||
first := int(binary.BigEndian.Uint32(data[b.contentStar+8+i*12 : b.contentStar+12+i*12]))
|
||||
spc := int(binary.BigEndian.Uint32(data[b.contentStar+12+i*12 : b.contentStar+16+i*12]))
|
||||
stscEntries = append(stscEntries, [2]int{first, spc})
|
||||
}
|
||||
haveStsc = true
|
||||
case "senc":
|
||||
verFlags := binary.BigEndian.Uint32(data[b.contentStar : b.contentStar+4])
|
||||
if verFlags>>24 != 0 {
|
||||
parseErr = fmt.Errorf("senc version %d 不支持", verFlags>>24)
|
||||
return false
|
||||
}
|
||||
if verFlags&0b10 != 0 {
|
||||
parseErr = fmt.Errorf("senc subsample 加密模式不支持")
|
||||
return false
|
||||
}
|
||||
count := int(binary.BigEndian.Uint32(data[b.contentStar+4 : b.contentStar+8]))
|
||||
p := b.contentStar + 8
|
||||
if p+8*count > b.end {
|
||||
parseErr = fmt.Errorf("senc IV 表越界")
|
||||
return false
|
||||
}
|
||||
for i := 0; i < count; i++ {
|
||||
ivs = append(ivs, data[p+8*i:p+8*i+8])
|
||||
}
|
||||
}
|
||||
return true
|
||||
}); err != nil {
|
||||
return fmt.Errorf("stbl 解析失败: %w", err)
|
||||
}
|
||||
if parseErr != nil {
|
||||
return parseErr
|
||||
}
|
||||
|
||||
if len(ivs) == 0 {
|
||||
return nil // 本 trak 未加密
|
||||
}
|
||||
if !haveSizes || !haveOffsets || !haveStsc {
|
||||
return fmt.Errorf("sample 表不完整(stsz=%v stco=%v stsc=%v)", haveSizes, haveOffsets, haveStsc)
|
||||
}
|
||||
|
||||
// stsc+stco+stsz 重建每样本绝对偏移(标准 sample table 遍历)
|
||||
sampleIdx := 0
|
||||
for ci, off := range chunkOffsets {
|
||||
spc := stscEntries[len(stscEntries)-1][1]
|
||||
for _, e := range stscEntries {
|
||||
if e[0] <= ci+1 {
|
||||
spc = e[1]
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
pos := off
|
||||
for s := 0; s < spc && sampleIdx < len(sizes); s++ {
|
||||
size := sizes[sampleIdx]
|
||||
if sampleIdx >= len(ivs) {
|
||||
break
|
||||
}
|
||||
if pos+size > len(data) {
|
||||
return fmt.Errorf("sample %d 越界 pos=%d size=%d", sampleIdx, pos, size)
|
||||
}
|
||||
if err := decryptStream(data[pos:pos+size], ivs[sampleIdx]); err != nil {
|
||||
return err
|
||||
}
|
||||
pos += size
|
||||
sampleIdx++
|
||||
}
|
||||
}
|
||||
|
||||
if stsd != nil {
|
||||
patchStsdEntry(data, *stsd)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// findBox 沿 path 逐层查找唯一子 box;任意一层缺失返回 (nil, nil)
|
||||
func findBox(data []byte, parent mp4Box, path ...string) (*mp4Box, error) {
|
||||
cur := parent
|
||||
for _, name := range path {
|
||||
var next *mp4Box
|
||||
if err := walkBoxes(data, cur.contentStar, cur.end, func(b mp4Box) bool {
|
||||
if b.typ == name {
|
||||
next = &b
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if next == nil {
|
||||
return nil, nil
|
||||
}
|
||||
cur = *next
|
||||
}
|
||||
return &cur, nil
|
||||
}
|
||||
|
||||
// patchStsdEntry 把加密 sample entry(encv/enca)的类型改回 sinf/frma 指示的原始 codec。
|
||||
// 番茄实测单 entry;entry 头部长度因音/视频而异,直接在 entry 字节里定位 "sinf"。
|
||||
func patchStsdEntry(data []byte, stsd mp4Box) {
|
||||
entryCount := int(binary.BigEndian.Uint32(data[stsd.contentStar+4 : stsd.contentStar+8]))
|
||||
if entryCount != 1 {
|
||||
return // ponytail: 多 entry 形态按需扩展
|
||||
}
|
||||
entryStart := stsd.contentStar + 8
|
||||
entryEnd := stsd.end
|
||||
|
||||
// 在 entry 内定位 "sinf"(box 类型魔数),再验证其 box 头合法性
|
||||
sinfOff := bytes.Index(data[entryStart:entryEnd], []byte("sinf"))
|
||||
for sinfOff >= 0 {
|
||||
boxStart := entryStart + sinfOff - 4 // size 字段起点
|
||||
if boxStart >= entryStart+8 {
|
||||
size := int(binary.BigEndian.Uint32(data[boxStart : boxStart+4]))
|
||||
if size >= 12 && boxStart+size <= entryEnd {
|
||||
sinfContent, sinfEnd := boxStart+8, boxStart+size
|
||||
frmaOff := bytes.Index(data[sinfContent:sinfEnd], []byte("frma"))
|
||||
if frmaOff >= 0 {
|
||||
frmaContent := sinfContent + frmaOff + 4
|
||||
if frmaContent+4 <= sinfEnd {
|
||||
// entry 类型字段在 box 头的 type 位置(entryStart+4)
|
||||
copy(data[entryStart+4:entryStart+8], data[frmaContent:frmaContent+4])
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
next := bytes.Index(data[entryStart+sinfOff+1:entryEnd], []byte("sinf"))
|
||||
if next < 0 {
|
||||
return
|
||||
}
|
||||
sinfOff = sinfOff + 1 + next
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package fqapi
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/binary"
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// 番茄短剧真实样本(video_model video_1..4 共用同一 spade_a)
|
||||
const testSpadeA = "kbwfwFiKI8RuvCnHV4ss9lK6HMFmvS/2f7wv7H+mAfRRvxmXlw=="
|
||||
|
||||
func TestDecodeSpadeKey(t *testing.T) {
|
||||
key, err := DecodeSpadeKey(testSpadeA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "4f04d75b0df5cee67dbe13738872e965"
|
||||
if got := hex.EncodeToString(key); got != want {
|
||||
t.Fatalf("key mismatch: got %s want %s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// 端到端:下载真实 360p 视频 → DecryptCENCMP4 → 输出文件(ffprobe 验证)
|
||||
func TestDecryptRealVideo(t *testing.T) {
|
||||
mainURLB64 := os.Getenv("FQ_VIDEO_URL")
|
||||
spadeA := strings.TrimSpace(os.Getenv("FQ_VIDEO_SPADE"))
|
||||
if mainURLB64 == "" || spadeA == "" {
|
||||
t.Skip("need FQ_VIDEO_URL (main_url base64) and FQ_VIDEO_SPADE")
|
||||
}
|
||||
url, err := base64.StdEncoding.DecodeString(mainURLB64)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _, err := downloadMedia(string(bytes.TrimSpace(url)), "", map[string]string{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer body.Close()
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("downloaded %d bytes", len(data))
|
||||
|
||||
key, err := DecodeSpadeKey(spadeA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("key=%x", key)
|
||||
if err := DecryptCENCMP4(data, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile("/tmp/video_decrypted.mp4", data, 0644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Log("written /tmp/video_decrypted.mp4")
|
||||
}
|
||||
|
||||
// ---- 合成 CENC MP4 单元测试:加密 → 解密 → 比对明文 ----
|
||||
|
||||
func box(typ string, payload ...[]byte) []byte {
|
||||
var body []byte
|
||||
for _, p := range payload {
|
||||
body = append(body, p...)
|
||||
}
|
||||
b := make([]byte, 8+len(body))
|
||||
binary.BigEndian.PutUint32(b[:4], uint32(len(b)))
|
||||
copy(b[4:8], typ)
|
||||
copy(b[8:], body)
|
||||
return b
|
||||
}
|
||||
|
||||
func u32(v uint32) []byte { b := make([]byte, 4); binary.BigEndian.PutUint32(b, v); return b }
|
||||
|
||||
func TestDecryptCENCMP4Synthetic(t *testing.T) {
|
||||
key := []byte("0123456789abcdef")
|
||||
plain1 := []byte("HELLO_CENC_SAMPLE_1_PADPADP")
|
||||
plain2 := []byte("SECOND_SAMPLE")
|
||||
plain3 := []byte("THIRD")
|
||||
|
||||
enc := func(pt []byte, iv8 []byte) []byte {
|
||||
iv := make([]byte, 16)
|
||||
copy(iv, iv8)
|
||||
block, _ := aes.NewCipher(key)
|
||||
ct := make([]byte, len(pt))
|
||||
cipher.NewCTR(block, iv).XORKeyStream(ct, pt)
|
||||
return ct
|
||||
}
|
||||
iv1 := []byte{1, 2, 3, 4, 5, 6, 7, 8}
|
||||
iv2 := []byte{8, 7, 6, 5, 4, 3, 2, 1}
|
||||
iv3 := []byte{0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x11, 0x22}
|
||||
ct1, ct2, ct3 := enc(plain1, iv1), enc(plain2, iv2), enc(plain3, iv3)
|
||||
|
||||
// buildFile(off1, off2):chunk 绝对偏移写入 stco;偏移依赖 moov 长度,先占位测长再重建
|
||||
buildFile := func(off1, off2 uint32) []byte {
|
||||
entry := box("enca", make([]byte, 8), box("sinf", box("frma", []byte("mp4a"))))
|
||||
stsd := box("stsd", u32(0), u32(1), entry)
|
||||
stsz := box("stsz", u32(0), u32(0), u32(3), u32(uint32(len(plain1))), u32(uint32(len(plain2))), u32(uint32(len(plain3))))
|
||||
stsc := box("stsc", u32(0), u32(2),
|
||||
u32(1), u32(2), u32(1), // entry1: chunk1 起,每 chunk 2 样本
|
||||
u32(2), u32(1), u32(1)) // entry2: chunk2 起,每 chunk 1 样本
|
||||
stco := box("stco", u32(0), u32(2), u32(off1), u32(off2))
|
||||
sencBody := append(append(append(append(u32(0), u32(3)...), iv1...), iv2...), iv3...)
|
||||
senc := box("senc", sencBody)
|
||||
moov := box("moov", box("trak", box("mdia", box("minf", box("stbl", stsd, stsz, stsc, stco, senc)))))
|
||||
ftyp := box("ftyp", []byte("isom"))
|
||||
return append(append(ftyp, moov...), box("mdat", ct1, ct2, ct3)...)
|
||||
}
|
||||
|
||||
// 占位构造测 moov 总长,得到真实 chunk 偏移后重建
|
||||
probe := buildFile(0, 0)
|
||||
chunk1Off := uint32(len(probe) - len(ct1) - len(ct2) - len(ct3))
|
||||
chunk2Off := chunk1Off + uint32(len(ct1)+len(ct2))
|
||||
data := buildFile(chunk1Off, chunk2Off)
|
||||
|
||||
if err := DecryptCENCMP4(data, key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := data[chunk1Off : chunk1Off+uint32(len(plain1))]; string(got) != string(plain1) {
|
||||
t.Errorf("sample1 解密不符: %q", got)
|
||||
}
|
||||
s2 := chunk1Off + uint32(len(plain1))
|
||||
if got := data[s2 : s2+uint32(len(plain2))]; string(got) != string(plain2) {
|
||||
t.Errorf("sample2 解密不符: %q", got)
|
||||
}
|
||||
if got := data[chunk2Off : chunk2Off+uint32(len(plain3))]; string(got) != string(plain3) {
|
||||
t.Errorf("sample3 解密不符: %q", got)
|
||||
}
|
||||
// stsd entry 类型应被 patch 为 frma 指示的 mp4a(原 enca 四字已不存在)
|
||||
if bytes.Index(data, []byte("enca")) >= 0 || bytes.Index(data, []byte("mp4a")) < 0 {
|
||||
t.Error("stsd entry 类型未修复为 mp4a")
|
||||
}
|
||||
}
|
||||
|
||||
// 清晰度过滤:按 definition 与档位 key 均可命中;无匹配返回空列表由上层报错
|
||||
func TestDecodeVideoModelQualityFilter(t *testing.T) {
|
||||
vm := `{"video_id":"v123","video_duration":1.5,"video_list":{
|
||||
"video_1":{"definition":"360p","vtype":"mp4","main_url":"` + base64.StdEncoding.EncodeToString([]byte("https://a/360")) + `"},
|
||||
"video_4":{"definition":"720p","vtype":"mp4","main_url":"` + base64.StdEncoding.EncodeToString([]byte("https://a/720")) + `"}}}`
|
||||
got := decodeVideoModelAsJSON(vm, "url", "", "720p").(map[string]interface{})
|
||||
vl := got["video_list"].(map[string]interface{})
|
||||
if len(vl) != 1 || vl["video_4"] == nil {
|
||||
t.Fatalf("definition 过滤失败: %v", vl)
|
||||
}
|
||||
got = decodeVideoModelAsJSON(vm, "url", "", "VIDEO_1").(map[string]interface{})
|
||||
vl = got["video_list"].(map[string]interface{})
|
||||
if len(vl) != 1 || vl["video_1"] == nil {
|
||||
t.Fatalf("档位key过滤失败: %v", vl)
|
||||
}
|
||||
if u := vl["video_1"].(map[string]interface{})["main_url"].(string); u != "https://a/360" {
|
||||
t.Fatalf("main_url 未解码: %s", u)
|
||||
}
|
||||
got = decodeVideoModelAsJSON(vm, "url", "", "1080p").(map[string]interface{})
|
||||
if len(got["video_list"].(map[string]interface{})) != 0 {
|
||||
t.Fatal("无匹配应返回空列表")
|
||||
}
|
||||
// max 取最高档(vheight 缺失时按 definition 数字比较)
|
||||
got = decodeVideoModelAsJSON(vm, "url", "", "max").(map[string]interface{})
|
||||
vl = got["video_list"].(map[string]interface{})
|
||||
if len(vl) != 1 || vl["video_4"] == nil {
|
||||
t.Fatalf("max 应只保留最高档: %v", vl)
|
||||
}
|
||||
// vheight 存在时优先按 vheight
|
||||
vm2 := `{"video_list":{
|
||||
"video_1":{"definition":"360p","vwidth":360,"vheight":640},
|
||||
"video_2":{"definition":"540p","vwidth":540,"vheight":960}}}`
|
||||
got = decodeVideoModelAsJSON(vm2, "url", "", "max").(map[string]interface{})
|
||||
if len(got["video_list"].(map[string]interface{})) != 1 || got["video_list"].(map[string]interface{})["video_2"] == nil {
|
||||
t.Fatal("max 应按 vheight 取 video_2")
|
||||
}
|
||||
}
|
||||
@@ -124,23 +124,17 @@ func addReviewToContent(jsonResult, itemID string, r *http.Request) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 获取基础 URL
|
||||
// 获取基础 URL(反代场景识别 X-Forwarded-Proto,避免生成 http:// 被 301)
|
||||
cfg := config.GetConfig()
|
||||
baseURL := ""
|
||||
if cfg != nil {
|
||||
if r.Host != "" {
|
||||
baseURL = externalBaseURL(r)
|
||||
} else if cfg != nil {
|
||||
host := cfg.Server.Host
|
||||
if host == "0.0.0.0" {
|
||||
host = "localhost"
|
||||
}
|
||||
port := cfg.Server.Port
|
||||
scheme := "http"
|
||||
|
||||
// 检查是否来自外部请求
|
||||
if r.Host != "" {
|
||||
baseURL = scheme + "://" + r.Host
|
||||
} else {
|
||||
baseURL = scheme + "://" + host + ":" + port
|
||||
}
|
||||
baseURL = "http://" + host + ":" + cfg.Server.Port
|
||||
}
|
||||
|
||||
// 生成带段评标记的内容
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// HandleAudio 音频处理
|
||||
@@ -75,7 +76,9 @@ func HandleVideo(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
result, err := fqapi.HandleVideo(params["item_ids"])
|
||||
output := r.URL.Query().Get("output")
|
||||
quality := r.URL.Query().Get("quality")
|
||||
result, err := fqapi.HandleVideo(params["item_ids"], output, quality)
|
||||
if err != nil {
|
||||
respondError(w, "获取视频失败: "+err.Error(), false)
|
||||
return
|
||||
@@ -84,6 +87,30 @@ func HandleVideo(w http.ResponseWriter, r *http.Request) {
|
||||
fmt.Fprint(w, result)
|
||||
}
|
||||
|
||||
// HandleVideoProxy 视频解密代理处理(磁盘缓存优先;http.ServeContent 支持 Range/seek/HEAD,
|
||||
// 播放器拖动进度条时按需分片返回)
|
||||
func HandleVideoProxy(w http.ResponseWriter, r *http.Request) {
|
||||
incrementStat("total", "video")
|
||||
|
||||
path := r.URL.Path
|
||||
key := strings.TrimPrefix(path, "/video/proxy/")
|
||||
if key == "" || key == path {
|
||||
http.Error(w, "缺少视频key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
content, contentType, err := fqapi.HandleVideoProxy(key)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if closer, ok := content.(io.Closer); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
http.ServeContent(w, r, key+".mp4", time.Time{}, content)
|
||||
}
|
||||
|
||||
// HandleManga 漫画处理
|
||||
func HandleManga(w http.ResponseWriter, r *http.Request) {
|
||||
incrementStat("total", "manga")
|
||||
|
||||
@@ -12,6 +12,16 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// externalBaseURL 取外部可访问的基础 URL(nginx 反代下识别 X-Forwarded-Proto,
|
||||
// 避免生成 http:// 链接被 301,弹窗 WebView 内 fetch 对 301 处理不稳)
|
||||
func externalBaseURL(r *http.Request) string {
|
||||
scheme := "http"
|
||||
if p := r.Header.Get("X-Forwarded-Proto"); p != "" {
|
||||
scheme = p
|
||||
}
|
||||
return scheme + "://" + r.Host
|
||||
}
|
||||
|
||||
// validateParams 验证必需参数
|
||||
func validateParams(r *http.Request, required ...string) (map[string]string, error) {
|
||||
params := make(map[string]string)
|
||||
@@ -207,7 +217,7 @@ func HandleReviewHTML(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
|
||||
html := generateReviewHTML(data, params["item_id"], bookID, para, page, pageSize, sort)
|
||||
html := generateReviewHTML(r, data, params["item_id"], bookID, para, page, pageSize, sort)
|
||||
fmt.Fprint(w, html)
|
||||
}
|
||||
|
||||
@@ -318,6 +328,7 @@ var reviewTmpl = template.Must(template.New("review").Parse(reviewHTML))
|
||||
// reviewPageData 评论页模板数据
|
||||
type reviewPageData struct {
|
||||
ItemID, BookID string
|
||||
BaseURL string
|
||||
ParaPlus1, Para, Sort int
|
||||
Total, NextOffset int
|
||||
PageSize, CommentCount int
|
||||
@@ -327,7 +338,7 @@ type reviewPageData struct {
|
||||
}
|
||||
|
||||
// generateReviewHTML 生成评论 HTML 页面
|
||||
func generateReviewHTML(data map[string]interface{}, itemID, bookID string, para, page, pageSize, sort int) string {
|
||||
func generateReviewHTML(r *http.Request, data map[string]interface{}, itemID, bookID string, para, page, pageSize, sort int) string {
|
||||
total := 0
|
||||
hasMore := false
|
||||
nextOffset := 0
|
||||
@@ -383,6 +394,7 @@ func generateReviewHTML(data map[string]interface{}, itemID, bookID string, para
|
||||
var b strings.Builder
|
||||
if err := reviewTmpl.Execute(&b, reviewPageData{
|
||||
ItemID: itemID, BookID: bookID,
|
||||
BaseURL: externalBaseURL(r),
|
||||
ParaPlus1: para + 1, Para: para, Sort: sort,
|
||||
Total: total, NextOffset: nextOffset,
|
||||
PageSize: pageSize, CommentCount: len(pageComments),
|
||||
|
||||
@@ -49,25 +49,50 @@
|
||||
box-sizing: border-box;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||
}
|
||||
html, body { height: 100%; }
|
||||
body {
|
||||
background-color: var(--bg-primary);
|
||||
color: var(--text-primary);
|
||||
padding: 15px;
|
||||
max-width: 600px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
transition: background-color 0.3s ease, color 0.3s ease;
|
||||
}
|
||||
.header {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 20px;
|
||||
padding: 10px 15px;
|
||||
padding: 10px 15px 12px;
|
||||
background: var(--bg-secondary);
|
||||
border-radius: 12px;
|
||||
border-radius: 20px 20px 0 0;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
box-shadow: 0 2px 8px var(--shadow);
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
transition: background-color 0.3s ease;
|
||||
}
|
||||
/* BottomSheet 顶部拖拽把手 */
|
||||
.header::before {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
width: 36px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--border-color);
|
||||
}
|
||||
#comment-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
padding: 15px;
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
.header h1 {
|
||||
font-size: 18px;
|
||||
color: var(--text-primary);
|
||||
@@ -333,8 +358,8 @@
|
||||
<i class="fas fa-book-open" style="color: var(--text-tertiary); font-size: 16px; margin: 0 10px;"></i>
|
||||
</span>
|
||||
<div class="sort-tabs">
|
||||
<div class="sort-tab{{if eq .Sort 1}} active{{end}}" onclick="switchSort(1)">最热</div>
|
||||
<div class="sort-tab{{if eq .Sort 3}} active{{end}}" onclick="switchSort(3)">最新</div>
|
||||
<div class="sort-tab{{if eq .Sort 1}} active{{end}}" onclick="switchSort(1, this)">最热</div>
|
||||
<div class="sort-tab{{if eq .Sort 3}} active{{end}}" onclick="switchSort(3, this)">最新</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="comment-list">
|
||||
@@ -370,6 +395,8 @@
|
||||
const bookID = '{{.BookID}}';
|
||||
const para = {{.Para}};
|
||||
let currentSort = {{.Sort}};
|
||||
// 服务端注入的绝对地址:弹窗 WebView(loadDataWithBaseURL) 中相对路径解析不可靠
|
||||
const API_BASE = '{{.BaseURL}}';
|
||||
|
||||
const commentList = document.getElementById('comment-list');
|
||||
const imageViewer = document.getElementById('imageViewer');
|
||||
@@ -380,7 +407,7 @@
|
||||
// 已加载回复的评论
|
||||
const loadedReplies = new Set();
|
||||
|
||||
// URL 构建
|
||||
// URL 构建(绝对地址,兼容弹窗 WebView)
|
||||
function buildReviewURL(params) {
|
||||
const baseParams = {
|
||||
item_id: itemID,
|
||||
@@ -388,7 +415,7 @@
|
||||
para: para
|
||||
};
|
||||
const query = new URLSearchParams({...baseParams, ...params});
|
||||
return '/review?' + query.toString();
|
||||
return API_BASE + '/review?' + query.toString();
|
||||
}
|
||||
|
||||
// 时间格式化
|
||||
@@ -429,11 +456,11 @@
|
||||
};
|
||||
}
|
||||
|
||||
// 滚动信息获取
|
||||
// 滚动信息获取(评论区为独立滚动容器)
|
||||
function getScrollInfo() {
|
||||
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
|
||||
const scrollHeight = document.documentElement.scrollHeight;
|
||||
const clientHeight = document.documentElement.clientHeight;
|
||||
const scrollTop = commentList.scrollTop;
|
||||
const scrollHeight = commentList.scrollHeight;
|
||||
const clientHeight = commentList.clientHeight;
|
||||
return {
|
||||
scrollTop,
|
||||
scrollHeight,
|
||||
@@ -443,11 +470,11 @@
|
||||
}
|
||||
|
||||
// 切换排序
|
||||
async function switchSort(newSort) {
|
||||
async function switchSort(newSort, tab) {
|
||||
if (currentSort === newSort) return;
|
||||
|
||||
document.querySelectorAll('.sort-tab').forEach(tab => tab.classList.remove('active'));
|
||||
event.target.closest('.sort-tab').classList.add('active');
|
||||
|
||||
document.querySelectorAll('.sort-tab').forEach(t => t.classList.remove('active'));
|
||||
if (tab) tab.classList.add('active');
|
||||
|
||||
commentList.innerHTML = LOADING_HTML;
|
||||
|
||||
@@ -479,7 +506,7 @@
|
||||
}
|
||||
|
||||
loadedReplies.clear();
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
commentList.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
} else {
|
||||
commentList.innerHTML = '<div class="empty">加载失败,请重试</div>';
|
||||
commentIndex = 0;
|
||||
@@ -751,25 +778,25 @@
|
||||
|
||||
// 回到顶部
|
||||
function scrollToTop() {
|
||||
window.scrollTo({
|
||||
commentList.scrollTo({
|
||||
top: 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
}
|
||||
|
||||
// 滚动监听
|
||||
|
||||
// 滚动监听(挂在评论容器上,顶栏固定不参与滚动)
|
||||
const handleScroll = debounce(() => {
|
||||
const scroll = getScrollInfo();
|
||||
|
||||
|
||||
// 显示/隐藏回到顶部按钮
|
||||
backToTopBtn.classList.toggle('show', scroll.scrollTop > 300);
|
||||
|
||||
|
||||
// 距离底部 200px 时触发加载
|
||||
if (scroll.distanceFromBottom <= 200) {
|
||||
loadMoreComments();
|
||||
}
|
||||
}, 100);
|
||||
|
||||
window.addEventListener('scroll', handleScroll, { passive: true });
|
||||
|
||||
commentList.addEventListener('scroll', handleScroll, { passive: true });
|
||||
</script>
|
||||
</body>
|
||||
Reference in new issue
Block a user