initial commit

This commit is contained in:
naiy committed 2026-07-28 19:39:45 +08:00
commit 5626fb6558
25 files changed
+3948

No files matched your search

+63
View File
@@ -0,0 +1,63 @@
import apiFetch from '../utils/request'
import type { Book } from '../types'
import { getCatalog } from './catalog'
import moment from 'moment'
export function mappingCreationStatus(status: string): string {
switch (status) {
case '0':
return '完结'
case '1':
return '连载'
case '4':
return '断更'
default:
return '未知'
}
}
export async function getBookInfoRaw(bookId: string): Promise<any> {
const response = await apiFetch(`https://api5-sinfonlinec.jxbhmy.com/reading/bookapi/multi-detail/v?book_id=${bookId}&aid=13`)
const j: any = await response.json()
if (
typeof j === 'object' &&
j !== null &&
'data' in j &&
Array.isArray(j.data) &&
j.data.length > 0
) return j.data[0]
return null
}
export async function getBookInfo(bookId: string): Promise<Book> {
const bookInfo = await getBookInfoRaw(bookId)
if (!bookInfo) {
throw new Error('Book not found')
}
return {
book_id: bookInfo.book_id,
title: bookInfo.book_name || bookInfo.original_book_name,
author: bookInfo.author,
cover_url: bookInfo.thumb_url,
summary: bookInfo.abstract,
// volume_list: bookInfo.volume_list,
update_time: moment(bookInfo.last_chapter_first_pass_time).format('YYYY-MM-DD HH:mm:ss'),
status: mappingCreationStatus(bookInfo.creation_status),
// chapter_count: bookInfo.chapter_count,
} as Book
}
export async function getBookInfoAndCatalog(book: Book | string): Promise<Book> {
if (typeof book !== 'string') {
book = book.book_id
}
const bookInfo = await getBookInfo(book)
if (!bookInfo) {
throw new Error('Book not found')
}
const catalog = await getCatalog(bookInfo.book_id)
console.log('Catalog:', catalog)
bookInfo.volume_list = catalog.volume_list
bookInfo.chapter_list = catalog.chapter_list
return bookInfo
}
+53
View File
@@ -0,0 +1,53 @@
import apiFetch from '../utils/request'
import type { Book, CatalogResult, ChapterItem, VolumeItem } from '../types'
import moment from 'moment'
export async function getCatalogRaw(bookId: string): Promise<any> {
const response = await apiFetch(`https://fanqienovel.com/api/reader/directory/detail?bookId=${bookId}`)
const j: any = response.json()
if (j.code !== 0 || j.data.chapterListWithVolume.length === 0) {
throw new Error('Empty catalog')
}
return [j.data.chapterListWithVolume, j.data.allItemIds]
}
export async function getCatalog(bookId: string): Promise<CatalogResult> {
const r = await getCatalogRaw(bookId) as Array<unknown>
const catalogRaw: any = r[0] // chapter list with volume
const allItemIds = r[1] as string[] // all item ids
const vmap: Record<string, VolumeItem> = {} // title -> VolumeItem
const chapters: Array<ChapterItem> = []
// const str = ''
catalogRaw[0].map((item: any): void => {
// console.debug(item)
const chapterItem = {
item_id: item.itemId,
title: item.title,
// YYYY-MM-DD HH:mm:ss
update_time: moment(item.updateTime).format('YYYY-MM-DD HH:mm:ss') as string,
char_count: item.charCount,
volume_title: item.volume_name,
} as ChapterItem
chapters.push(chapterItem)
if (!vmap[item.volume_name]) {
vmap[item.volume_name] = {
title: item.volume_name,
book_id: bookId,
chapter_list: [],
} as VolumeItem
}
(vmap[item.volume_name] as VolumeItem).chapter_list.push(chapterItem)
})
return {
book_id: bookId,
volume_list: Object.values(vmap),
chapter_list: chapters,
all_item_ids: allItemIds,
} as CatalogResult
}
export async function enrichBookCatalog(book: Book): Promise<void> {
const catalog = await getCatalog(book.book_id)
book.volume_list = catalog.volume_list
book.chapter_list = catalog.chapter_list
}
+82
View File
@@ -0,0 +1,82 @@
import config, { type KeyInfo } from '../config'
import { get, post } from '.'
import { encryptKeyinfoBody, decryptKeyinfoResponse, decryptChapter, b64decode, b64encode } from '../utils/crypto'
import { read, write } from '../localStorage'
async function refreshKeyinfo(): Promise<void> {
const b = await encryptKeyinfoBody(config.currentConfig)
const res = await post('/reader/crypt/registerkey/v1', false, {}, b)
console.log(res)
const j = res.json()
console.log('response: ', j)
const ek = j?.data?.key
if (!ek) {
throw new Error('Failed to get key info')
}
const key = await decryptKeyinfoResponse(ek)
const keyinfo: KeyInfo = {
key,
keyver: j?.data?.keyver as number,
}
console.log('Refreshed key info:', keyinfo)
config.currentConfig.key_info = keyinfo
write('keyinfo', {
key: b64encode(key),
keyver: j?.data?.keyver as number,
}) // cache key info
}
async function ensureKeyinfo(expectedKeyVersion?: number): Promise<void> {
const keyinfo = config.currentConfig.key_info
const cachedKeyInfo = read('keyinfo')
console.log('cached key info: ', cachedKeyInfo)
if (cachedKeyInfo) {
const cki = {
key: b64decode(cachedKeyInfo.key),
keyver: cachedKeyInfo.keyver,
} as KeyInfo
/*
console.log({
expectedKeyVersion,
cki,
assert: cki.keyver === expectedKeyVersion, // assert key version
})
*/
if (typeof expectedKeyVersion === 'undefined' || cki.keyver === expectedKeyVersion) {
config.currentConfig.key_info = cki
return
}
}
if (!keyinfo) {
// get from zero
return await refreshKeyinfo()
}
if (keyinfo?.keyver !== expectedKeyVersion) {
// refresh from server
return await refreshKeyinfo()
}
}
export async function getChapter(itemId: string, _retry?: number): Promise<any> {
if (typeof _retry === 'undefined') _retry = 0
if (_retry > 5) {
throw new Error(`Failed to get chapter: ${itemId}`)
}
if (!config.currentConfig.key_info) {
await ensureKeyinfo()
}
const res = await get(`/reader/full/v1`, false, { item_id: itemId })
const j = res.json()?.data
if (!j) {
console.warn('Failed to get chapter: ', itemId, ', response: ', j)
return await getChapter(itemId, _retry + 1)
// throw new Error('Failed to get chapter')
}
if (j?.content === 'Invalid' || j?.key_version !== config.currentConfig.key_info?.keyver) { // keyreg expired
console.warn('Key reg expired, regster again and retrying...')
await ensureKeyinfo(parseInt(j?.key_version))
return await getChapter(itemId, _retry + 1)
}
j.content = await decryptChapter(j?.content, config.currentConfig)
return j
}
+68
View File
@@ -0,0 +1,68 @@
import apiFetch from '../utils/request'
import { getCookie } from '../localStorage'
import config from '../config'
export const baseUrl = 'https://api5-sinfonlinec.jxbhmy.com/redcandle/search';
export const baseQuery = {
aid: '1967',
app_name: 'novelapp'
}
export async function get(path: string, cookie?: boolean, query?: any, headers?: any, optionsOverride?: any): Promise<any> {
let url = baseUrl + path;
const sessid = getCookie('sessionid')
let ck = sessid ? `sessionid=${sessid}` : ''
const h = {
Cookie: cookie ? ck : '',
...headers
}
const deviceQuery = {
device_id: config.currentConfig.device_id,
iid: config.currentConfig.install_id,
}
const finalQuery = {
...baseQuery,
...deviceQuery,
...query
}
url += '?' + new URLSearchParams(finalQuery).toString();
const options = {
method: 'GET',
headers: h,
...optionsOverride
}
console.log('---start--- GET ', url, options)
const res = await apiFetch(url, options)
console.log('---complete--- GET ', url, res)
return res
}
export async function post(path: string, cookie?: boolean, query?: any, body?: any, headers?: any, optionsOverride?: any): Promise<any> {
let url = baseUrl + path;
const sessid = getCookie('sessionid')
let ck = sessid ? `sessionid=${sessid}` : ''
const h = {
Cookie: cookie ? ck : '',
...headers
}
const deviceQuery = {
device_id: config.currentConfig.device_id,
iid: config.currentConfig.install_id,
}
const finalQuery = {
...baseQuery,
...deviceQuery,
...query
}
url += '?' + new URLSearchParams(finalQuery).toString();
const options = {
method: 'POST',
headers: h,
body: body,
...optionsOverride
}
console.log('---start--- POST ', url, options)
const res = await apiFetch(url, options)
console.log('---complete--- POST ', url, res)
return res
}
+40
View File
@@ -0,0 +1,40 @@
import { fetch } from '../config'
export interface UserInfo {
id: string
username: string
avatar: string
desc: string
age: number
}
export let userInfo: UserInfo | null = null
export async function getUserInfo() {
if (userInfo) return userInfo
const response = await fetch('https://fanqienovel.com/api/user/info/v2')
const j = await response.json()
userInfo = j?.data
return userInfo
}
export async function checkLogin() {
// sessionid is HttpOnly. So we use fetch directly to access user api.
const response = await fetch('https://fanqienovel.com/api/user/info/v2')
const j = await response.json()
userInfo = {
id: j?.data?.id,
username: j?.data?.name,
avatar: j?.data?.avatar,
desc: j?.data?.desc,
age: j?.data?.age,
} as UserInfo
return j?.data?.id > 1
}
export default async function init(): Promise<void> {
await checkLogin()
if (userInfo) {
console.log('Hello, ', userInfo.username)
}
}
+163
View File
@@ -0,0 +1,163 @@
/*
* 番茄小说APP内置CSS
* 版权归属为番茄小说APP官方
* 修改以兼容网页环境
*/
html{
display:block;
}
body{
display:block;
}
p{
font-size:1em;
text-align:justify;
display:block;
text-indent:2em;
margin:0.6em 0em 0.6em 0em;
}
div{
display:block;
}
h1{
display:block;
font-size:1.42em;
font-weight:bold;
margin:22px 0em 3em 0em;
text-align:left;
line-space:0.5em;
}
h2{
display:block;
font-size:1.2em;
font-weight:bold;
margin:1em 0em 0.6em 0em;
text-align:left;
}
h3{
display:block;
font-size:1em;
font-weight:bold;
margin:0em 0em 1em 0em;
text-align:left;
}
sup{
font-size:smaller;
}
.picture{
text-indent:0em;
text-align:center;
margin:0em 0em 0em 0em;
line-space:0em;
}
.pictureDesc{
font-size:0.73em;
text-indent:0em;
margin:0.4em 0em 1em 0em;
theme-color:color1#0.7;
line-space:0.3em;
text-align:left;
}
.pictureTitle{
font-size:0.73em;
text-indent:0em;
margin:1em 0em 0.3em 0em;
theme-color:color1#0.7;
text-align:left;
line-space:0em;
}
.collectTitle{
margin:80px 68px 0em 0px;
font-size:1.42em;
text-indent:0em;
text-align:left;
}
.collectAuthor{
margin:16px 0em 0em 0em;
font-size:1em;
text-indent:0em;
text-align:left;
}
.collectPicture{
margin:24px 0em 0em 0em;
text-indent:0em;
text-align:right;
}
.collectDetail{
margin:3em 44px 0em 10px;
text-indent:0em;
}
.quoteDefault{
font-size:1em;
margin:1.5em 0em 1.5em 2em;
font-family:'FZShengShiKaiShuS-M-GB';
line-space:0.5em;
}
.quoteStyle1{
text-indent:0em;
text-align:left;
}
.alignRight{
text-align:right;
}
.quoteDefaultAlignRight{
font-size:1em;
margin:0.6em 0em 1.5em 32px;
font-family:'FZShengShiKaiShuS-M-GB';
text-align:right;
line-space:0.5em;
}
.chapterTitle1{
display:block;
font-size:1.42em;
font-weight:bold;
margin:22px 0em 3em 0em;
text-align:left;
line-space:0.5em;
}
.chapterTitle2{
display:block;
font-size:1.2em;
font-weight:bold;
margin:1em 0em 0.6em 0em;
text-align:left;
}
.chapterTitle3{
display:block;
font-size:1em;
font-weight:bold;
margin:0em 0em 1em 0em;
text-align:left;
}
.bdFootnote{
width:0.69em;
height:0.84em;
margin-top:-0.23em;
vertical-align:top;
}
.bdPicturebg{
break-before:always;
}
+45
View File
@@ -0,0 +1,45 @@
<svg width="64" height="64" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<path
d="M23.3115 1H6.68853C3.54684 1 1 3.54684 1 6.68853V23.3115C1 26.4532 3.54684 29 6.68853 29H23.3115C26.4532 29 29 26.4532 29 23.3115V6.68853C29 3.54684 26.4532 1 23.3115 1Z"
fill="white"></path>
<path
d="M23.3115 0.75H6.68853C3.40877 0.75 0.75 3.40877 0.75 6.68853V23.3115C0.75 26.5912 3.40877 29.25 6.68853 29.25H23.3115C26.5912 29.25 29.25 26.5912 29.25 23.3115V6.68853C29.25 3.40877 26.5912 0.75 23.3115 0.75Z"
stroke="black" stroke-opacity="0.08" stroke-width="0.5"></path>
<mask id="mask0_470_48364" maskUnits="userSpaceOnUse" x="1" y="1" width="28" height="28">
<path
d="M23.3115 1H6.68853C3.54684 1 1 3.54684 1 6.68853V23.3115C1 26.4532 3.54684 29 6.68853 29H23.3115C26.4532 29 29 26.4532 29 23.3115V6.68853C29 3.54684 26.4532 1 23.3115 1Z"
fill="white"></path>
</mask>
<g mask="url(#mask0_470_48364)">
<path
d="M23.3115 1H6.68853C3.54684 1 1 3.54684 1 6.68853V23.3115C1 26.4532 3.54684 29 6.68853 29H23.3115C26.4532 29 29 26.4532 29 23.3115V6.68853C29 3.54684 26.4532 1 23.3115 1Z"
fill="white"></path>
<path
d="M15.0008 48.6642C25.4017 48.6642 33.8334 40.2326 33.8334 29.8316C33.8334 19.4307 25.4017 10.999 15.0008 10.999C4.59985 10.999 -3.83179 19.4307 -3.83179 29.8316C-3.83179 40.2326 4.59985 48.6642 15.0008 48.6642Z"
fill="url(#paint0_radial_470_48364)"></path>
<path d="M23.2688 1V7.21294L20.6663 5.71437L18.0674 7.21294V1H23.2688Z" fill="#FF5F00"></path>
<path
d="M15.1343 18.881C15.1343 18.881 16.1014 17.5513 16.1014 16.4065C16.1014 15.2617 15.6676 14.7373 15.1343 14.7373C14.601 14.7373 14.1673 15.2635 14.1673 16.4065C14.1673 17.5496 15.1343 18.881 15.1343 18.881Z"
fill="white"></path>
<path
d="M7.62724 22.6585C8.77205 22.6585 10.1017 23.6256 10.1017 23.6256C10.1017 23.6256 8.77027 24.5926 7.62724 24.5926C6.4842 24.5926 5.95801 24.1589 5.95801 23.6256C5.95801 23.0923 6.48242 22.6585 7.62724 22.6585Z"
fill="white"></path>
<path
d="M22.6396 24.5926C21.4948 24.5926 20.1651 23.6256 20.1651 23.6256C20.1651 23.6256 21.4966 22.6585 22.6396 22.6585C23.7826 22.6585 24.3088 23.0923 24.3088 23.6256C24.3088 24.1589 23.7844 24.5926 22.6396 24.5926Z"
fill="white"></path>
<path
d="M10.4555 18.3139C11.2643 19.1227 11.5221 20.7475 11.5221 20.7475C11.5221 20.7475 9.89732 20.4897 9.08848 19.6809C8.27964 18.8721 8.21387 18.1948 8.59251 17.8161C8.97115 17.4375 9.64666 17.5033 10.4573 18.3121L10.4555 18.3139Z"
fill="white"></path>
<path
d="M18.7465 20.7476C18.7465 20.7476 19.0043 19.1228 19.8131 18.314L19.8113 18.3122C20.622 17.5033 21.2993 17.4393 21.6761 17.8162C22.0548 18.1949 21.989 18.8721 21.1802 19.681C20.3713 20.4898 18.7465 20.7476 18.7465 20.7476Z"
fill="white"></path>
</g>
<defs>
<radialGradient id="paint0_radial_470_48364" cx="0" cy="0" r="1"
gradientUnits="userSpaceOnUse"
gradientTransform="translate(15.0008 29.8316) scale(18.8326)">
<stop stop-color="#CC0500"></stop>
<stop offset="1" stop-color="#FF5F00"></stop>
</radialGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 3.3 KiB

+25
View File
@@ -0,0 +1,25 @@
/* 移除章节锁定图标 */
.muyeicon-lock {
display: none;
}
/* 移除APP推广图标 */
.muye-to-fanqie {
display: none!important;
}
.reader-toolbar-item-download {
display: none!important;
}
.download-btn {
display: none!important;
}
.download-icon {
display: none!important;
}
/* 移除默认阅读器div,让脚本接管。.muye-reader-content且不带fqa标签的div */
.muye-reader-content:not(.fqa) {
display: none!important;
}
.no-content {
display: none!important;
}
+49
View File
@@ -0,0 +1,49 @@
export type HookEvent = 'load' | 'click' | 'onUrlChange' | 'onHashChange' | 'keyup' | 'keydown'
export interface KeyInfo {
key?: ArrayBuffer;
keyver?: number;
}
export interface DeviceConfig {
install_id: string; // iid
device_id: string;
device_type?: string;
key_info?: KeyInfo;
}
export interface HookConfig {
id: string;
event: HookEvent;
filter: (
path: string,
query: URLSearchParams,
hash: string
) => boolean;
handler: Function;
}
/*
export interface EncryptionContext {
iv: ArrayBuffer;
encrypted?: ArrayBuffer;
plaintext?: ArrayBuffer;
}
*/
// b64decode("rCXGfd2POMGzeiNIgo4iLg==") = 172, 37, 198, 125, 221, 143, 56, 193, 179, 122, 35, 72, 130, 142, 34, 46
export const shared_key: ArrayBuffer = new Uint8Array([172, 37, 198, 125, 221, 143, 56, 193, 179, 122, 35, 72, 130, 142, 34, 46]).buffer;
// 字节的上报SDK会覆写fetch,所以这里先留一份
export const fetch = unsafeWindow.fetch;
export const XMLHttpRequest = unsafeWindow.XMLHttpRequest;
// 示例匿名设备。之后允许用户自己输入
export const defaultConfig: DeviceConfig = {
install_id: "2187355326270644",
device_id: "2187355326004404",
device_type: "P30",
};
export default {
currentConfig: defaultConfig,
}
+11
View File
@@ -0,0 +1,11 @@
import scriptcss from './assets/script.css?raw';
import { sleep } from './utils';
export default async function inject() {
while (!document.body) {
console.log('Waiting for body...');
await sleep(500);
}
GM_addStyle(scriptcss);
console.log('CSS injected successfully!');
}
+127
View File
@@ -0,0 +1,127 @@
const enTag = '.font-DNMrHsV173Pd4pgy' // 这个目前从存在解密算法到现在没改过。暂且认为它在加解密算法不变时长时不变。
const code_ed = 58715
const code_st = 58344
const mapping = [
"D", "在", "主", "特", "家", "军", "然", "表", "场", "4", "要", "只", "v", "和", "?", "6", "别", "还", "g",
"现", "儿", "岁", "?", "?", "此", "象", "月", "3", "出", "战", "工", "相", "o", "男", "直", "失", "世", "F",
"都", "平", "文", "什", "V", "O", "将", "真", "T", "那", "当", "?", "会", "立", "些", "u", "是", "十", "张",
"学", "气", "大", "爱", "两", "命", "全", "后", "东", "性", "通", "被", "1", "它", "乐", "接", "而", "感",
"车", "山", "公", "了", "常", "以", "何", "可", "话", "先", "p", "i", "叫", "轻", "M", "士", "w", "着", "变",
"尔", "快", "l", "个", "说", "少", "色", "里", "安", "花", "远", "7", "难", "师", "放", "t", "报", "认",
"面", "道", "S", "?", "克", "地", "度", "I", "好", "机", "U", "民", "写", "把", "万", "同", "水", "新", "没",
"书", "电", "吃", "像", "斯", "5", "为", "y", "白", "几", "日", "教", "看", "但", "第", "加", "候", "作",
"上", "拉", "住", "有", "法", "r", "事", "应", "位", "利", "你", "声", "身", "国", "问", "马", "女", "他",
"Y", "比", "父", "x", "A", "H", "N", "s", "X", "边", "美", "对", "所", "金", "活", "回", "意", "到", "z",
"从", "j", "知", "又", "内", "因", "点", "Q", "三", "定", "8", "R", "b", "正", "或", "夫", "向", "德", "听",
"更", "?", "得", "告", "并", "本", "q", "过", "记", "L", "让", "打", "f", "人", "就", "者", "去", "原", "满",
"体", "做", "经", "K", "走", "如", "孩", "c", "G", "给", "使", "物", "?", "最", "笑", "部", "?", "员", "等",
"受", "k", "行", "一", "条", "果", "动", "光", "门", "头", "见", "往", "自", "解", "成", "处", "天", "能",
"于", "名", "其", "发", "总", "母", "的", "死", "手", "入", "路", "进", "心", "来", "h", "时", "力", "多",
"开", "已", "许", "d", "至", "由", "很", "界", "n", "小", "与", "Z", "想", "代", "么", "分", "生", "口",
"再", "妈", "望", "次", "西", "风", "种", "带", "J", "?", "实", "情", "才", "这", "?", "E", "我", "神", "格",
"长", "觉", "间", "年", "眼", "无", "不", "亲", "关", "结", "0", "友", "信", "下", "却", "重", "己", "老",
"2", "音", "字", "m", "呢", "明", "之", "前", "高", "P", "B", "目", "太", "e", "9", "起", "稜", "她", "也",
"W", "用", "方", "子", "英", "每", "理", "便", "四", "数", "期", "中", "C", "外", "样", "a", "海", "们",
"任",
]
/**
* 解密文本
* @param text 解密前的文本
* @returns 解密后的文本
*/
export function decryptText(text: string): string {
let result = "";
let changed = false;
for (const char of text) {
const codePoint = char.codePointAt(0);
if (typeof codePoint !== "number") {
return text;
}
if (codePoint < code_st || codePoint > code_ed) {
result += char;
continue;
}
const mapped = mapping[codePoint - code_st];
if (mapped && mapped !== "?") {
result += mapped;
changed = true;
} else {
result += char;
}
}
return changed ? result : text;
}
/**
* 解密一个 DOM 元素内的所有文本节点
* @param element 要解密的 DOM 元素
*/
export function decryptElement(element: Element) {
const walker = document.createTreeWalker(
element,
NodeFilter.SHOW_TEXT,
);
let textNode;
while ((textNode = walker.nextNode())) {
const oldText = textNode.nodeValue;
if (!oldText) {
continue;
}
const newText = decryptText(oldText);
if (newText !== oldText) {
textNode.nodeValue = newText;
}
}
}
function decryptPage(root: Document | Element): void {
// 元素自身可能就是加密节点,其后代同样需要扫描:
// MutationObserver 收到的新增节点通常是容器,加密节点在其内部。
if (root instanceof Element && root.matches(enTag)) {
decryptElement(root);
}
root.querySelectorAll(enTag).forEach(decryptElement);
}
export default function initFontDecrypt() {
const observer = new MutationObserver((mutations) => {
for (const mutation of mutations) {
if (mutation.type === "characterData") {
const encryptedElement =
mutation.target.parentElement?.closest(
enTag,
);
if (encryptedElement) {
decryptElement(encryptedElement);
}
continue;
}
for (const node of mutation.addedNodes) {
if (node.nodeType === Node.ELEMENT_NODE) {
decryptPage(node as Element);
continue;
}
if (node.nodeType === Node.TEXT_NODE) {
const encryptedElement =
node.parentElement?.closest(
enTag,
);
if (encryptedElement) {
decryptElement(encryptedElement);
}
}
}
}
});
// 直接观察 document:run-at 为 document-start 时 body 尚不存在,
// 而 subtree 会覆盖 body 的创建及其后所有后代变动,无需轮询等待。
observer.observe(document, {
subtree: true,
childList: true,
characterData: true,
});
// observer 挂载前解析出的节点不会产生 mutation,需补扫一次。
decryptPage(document);
}
+31
View File
@@ -0,0 +1,31 @@
import type { HookConfig, HookEvent } from "../config";
import readerHook from "./readerHook";
const hooks = [
...readerHook,
] as HookConfig[];
async function eventListener(event: HookEvent, previous?: string) {
console.log(`eventListener, event: ${event}, previous: ${previous}`);
const path = window.location.pathname;
const hash = window.location.hash;
const params = new URLSearchParams(window.location.search);
for (const hook of hooks) {
if (hook.event === event && hook.filter(path, params, hash)) {
await hook.handler();
}
}
return Promise.resolve();
}
export async function onUrlChange(previous: string) {
return eventListener('onUrlChange', previous);
}
export async function onHashChange(previous: string) {
return eventListener('onHashChange', previous);
}
export async function onLoad() {
return eventListener('load');
}
+192
View File
@@ -0,0 +1,192 @@
import { type HookConfig } from '../config'
import { getChapter } from '../api/content'
import { getBookInfoAndCatalog } from '../api/book'
// import defaultcss from '../assets/default.css?raw';
import { cloneElement } from '../utils';
import { type Book } from '../types'
import moment from 'moment'
let currentBook: Book | null = null
async function insertContent() {
const itemId = window.location.pathname.split('/').pop()?.substring(0, 19) || ''
if (!itemId) {
console.warn('No item_id found in URL')
return
}
const chapter = await getChapter(itemId)
if (!chapter) {
console.warn('No chapter found for item_id:', itemId)
return
}
console.log('Chapter:', chapter)
const pageState: any = (unsafeWindow as typeof unsafeWindow & {
__INITIAL_STATE__?: { reader?: { chapterData?: { title?: string } } }
}).__INITIAL_STATE__
const chapterTitle = chapter.novel_data?.title || pageState?.reader?.chapterData?.title
if (typeof chapter.content === 'string') {
// TODO: 支持部分书籍的CSS内容
const dp = new DOMParser()
const doc = dp.parseFromString(chapter.content, 'text/html')
const body = doc.body
const article = body.querySelector('article')
const toProcess = article || body
for (let i = 0; i < toProcess.childNodes.length; i++) {
if (i < 1 && (toProcess.childNodes[i] as HTMLElement)?.innerHTML.includes(chapterTitle)) {
// remove duplicate title
toProcess.removeChild(toProcess.childNodes[i] as HTMLElement)
}
}
const readerContainer = document.querySelector("div.muye-reader-content")
let scriptContainer: HTMLDivElement | null = null
if (readerContainer) {
scriptContainer = cloneElement(readerContainer) as HTMLDivElement
scriptContainer.classList.add('fqa')
scriptContainer.classList.remove('noselect') // allow text selection
// readerContainer应该已经被注入的内容CSS隐藏掉了
scriptContainer.innerHTML = ''
scriptContainer.appendChild(toProcess)
readerContainer.insertAdjacentElement('beforebegin', scriptContainer)
}
}
const muyeReaderTitle = document.querySelector("h1.muye-reader-title")
const muyeReaderSubtitle = document.querySelector("div.muye-reader-subtitle")
if (muyeReaderTitle) {
muyeReaderTitle.textContent = chapterTitle
}
// <div class="muye-reader-subtitle">
// <span class="desc-item">
// <span class="title">本章字数:</span>
// 1916字
// </span>
// <span class="desc-item">
// <span class="title">更新时间:</span>
// 2025-05-24
// </span>
// </div>
/*
if (muyeReaderSubtitle) {
muyeReaderSubtitle.innerHTML = ''
const wordCntSpan = document.createElement('span')
wordCntSpan.className = 'desc-item'
wordCntSpan.innerHTML = `<span class="title">本章字数:</span> ${chapter.char_count}字`
muyeReaderSubtitle.appendChild(wordCntSpan)
const updateTimeSpan = document.createElement('span')
updateTimeSpan.className = 'desc-item'
updateTimeSpan.innerHTML = `<span class="title">更新时间:</span> ${chapter.update_time}`
muyeReaderSubtitle.appendChild(updateTimeSpan)
}
*/
if (muyeReaderSubtitle && pageState?.reader?.chapterData?.itemId === itemId) {
// 写入更精确的更新时间
let updateTimeSpan = muyeReaderSubtitle.querySelectorAll('span.desc-item')[1]
if (updateTimeSpan) {
let uttspan = updateTimeSpan.firstChild as HTMLSpanElement
// seconds
updateTimeSpan.innerHTML =
uttspan.innerHTML +
moment(pageState?.reader?.chapterData?.firstPassTime * 1000).format('YYYY-MM-DD HH:mm:ss')
}
}
/*
for (let i = 0; i < 10; i++) {
if (readerContainer) {
readerContainer.innerHTML = ''
readerContainer.appendChild(toProcess)
}
// TODO: 改优雅点
// 防止和页面已有脚本相互作用导致正文没覆盖上
await sleep(100)
}
*/
console.log('Current book:', currentBook)
if (!currentBook || currentBook == null || currentBook.book_id !== chapter.novel_data?.book_id) {
currentBook = await getBookInfoAndCatalog(chapter.novel_data?.book_id)
console.log('Current book:', currentBook)
}
if (currentBook && currentBook.chapter_list) {
const currentChapterItem = currentBook.chapter_list.find(c => c.item_id === itemId)
if (currentChapterItem) {
console.log('Current chapter:', currentChapterItem)
if (document.getElementById('fqa-current-chapter-volume')) {
const c = document.getElementById('fqa-current-chapter-volume')
if (c) {
c.textContent = currentChapterItem.volume_title
}
} else {
const volSpan = document.createElement('span')
volSpan.className = 'desc-item'
volSpan.id = 'fqa-current-chapter-volume'
volSpan.textContent = currentChapterItem.volume_title
// muyeReaderSubtitle?.firstChild: HTMLSpanElement.insertAdjacentElement('beforebegin', volSpan)
const c = muyeReaderSubtitle?.firstChild as HTMLSpanElement
if (c) {
c.insertAdjacentElement('beforebegin', volSpan)
}
}
}
}
}
// let currentBook: Book | null = null
async function onUrlChange(_previous: string): Promise<void> {
// TODO: 记录并上报阅读历史和记录
await insertContent()
}
async function onHashChange(_previous: string): Promise<void> {
// TODO: 支持从hash里解析并跳转到指定行
}
async function onLoad(): Promise<void> {
/*
if (!document.getElementById('fqa-inject-css-reader')) {
const style = document.createElement('style')
style.id = 'fqa-inject-css-reader'
style.innerHTML = defaultcss
document.head.appendChild(style)
}
*/
const btns = document.querySelector("div.muye-reader-btns") // single div
if (btns) {
// TODO: 直接覆写按钮行为,切章节由脚本完成
// btns.innerHTML = btns.innerHTML // clear default onclick
// 上一章
// byte-btn byte-btn-dashed byte-btn-size-large byte-btn-shape-square muye-button chapter-btn last
// 下一章
// fatherdiv: chapter-btn next btn-next-relative-container
// byte-btn byte-btn-primary byte-btn-size-large byte-btn-shape-square muye-button
/*const prevBtn = btns.querySelector('.chapter-btn.last')
const nextBtn = btns.querySelector('.chapter-btn.next')?.firstChild
if (prevBtn) {
}*/
}
await insertContent()
}
function readerFilter(path: string, _query: URLSearchParams, _hash: string) {
return path.startsWith('/reader') || path.startsWith('reader')
}
export default [
{
id: 'readerHook_load',
event: 'load',
handler: onLoad,
filter: readerFilter
} as HookConfig,
{
id: 'readerHook_urlChange',
event: 'onUrlChange',
handler: onUrlChange,
filter: readerFilter
} as HookConfig,
{
id: 'readerHook_hashChange',
event: 'onHashChange',
handler: onHashChange,
filter: readerFilter
} as HookConfig
] as HookConfig[]
+31
View File
@@ -0,0 +1,31 @@
const localStorage = unsafeWindow.localStorage
export function write(key: string, value: any) {
GM_setValue(key, JSON.stringify(value))
}
export function read(key: string) {
return JSON.parse(GM_getValue(key) || 'null')
}
export function del(key: string) {
GM_deleteValue(key)
}
export function writePage(key: string, value: any) {
localStorage.setItem(key, JSON.stringify(value))
}
export function readPage(key: string) {
const value = localStorage.getItem(key)
return value ? JSON.parse(value) : null
}
export function delPage(key: string) {
localStorage.removeItem(key)
}
export function getCookie(key: string) {
return document.cookie.split(';').find(c => c.trim().startsWith(key + '='))?.split('=')[1] || null
}
+43
View File
@@ -0,0 +1,43 @@
import injectCSS from './cssInject'
import initFontDecrypt from './fontDecrypt'
import { onLoad, onUrlChange, onHashChange } from './hooks'
import { version, name } from '../package.json'
import initUser from './api/user'
let previousUrl = window.location.href
let previousHash = window.location.hash
async function mainInit() {
console.log(`================================================`)
console.log(`== ${name} - ${version} ==`)
console.log(`================================================`)
initFontDecrypt()
await injectCSS()
for (const method of ['pushState', 'replaceState'] as const) {
const original = history[method];
history[method] = function (
this: History,
...args: Parameters<History[typeof method]>
) {
const result = original.apply(this, args);
console.debug(`history.${method} called with args:`, args);
onUrlChange(previousUrl);
previousUrl = window.location.href;
return result;
};
}
window.addEventListener('load', async () => {
await onLoad()
})
window.addEventListener('hashchange', async () => {
await onHashChange(previousHash)
previousHash = window.location.hash
})
window.addEventListener('popstate', async () => {
await onUrlChange(previousUrl)
previousUrl = window.location.href
})
await initUser()
}
mainInit()
+34
View File
@@ -0,0 +1,34 @@
export interface ChapterItem {
item_id: string;
title: string;
update_time: string;
char_count: number;
volume_title: string;
}
export interface VolumeItem {
title: string;
book_id: string;
chapter_list: ChapterItem[];
}
export interface Book {
book_id: string;
title: string;
author: string;
cover_url: string;
summary: string;
volume_list?: VolumeItem[]; // 之后可以补,允许为空
update_time: string;
status: string;
all_item_ids?: string[]; // 同理
// chapter_count: number;
chapter_list?: ChapterItem[]; // 同理
}
export interface CatalogResult {
book_id: string;
volume_list: VolumeItem[];
chapter_list: ChapterItem[];
all_item_ids: string[];
}
+190
View File
@@ -0,0 +1,190 @@
import { defaultConfig, shared_key, type DeviceConfig } from "../config";
// 番茄小说始终运行在安全上下文,所以 unsafeWindow 一定能兜底获取到 Crypto API 对象。
// 如果没有,更大可能是浏览器版本过低,或者被某些扩展破坏了安全上下文。
// 惰性求值:模块顶层不抛错,否则会连带炸掉 CSS 注入、字体解密等不依赖本模块的功能。
function getCrypto(): Crypto {
const c = globalThis.crypto ?? (unsafeWindow.crypto as Crypto | undefined);
if (!c?.subtle) {
throw new Error("Crypto API不可用,请检查浏览器版本是否支持该API");
}
return c;
}
function getSubtle(): SubtleCrypto {
return getCrypto().subtle;
}
export function b64decode(b64: string): ArrayBuffer {
const binaryString = atob(b64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
export function b64encode(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
const chunkSize = 0x8000;
const chunks: string[] = [];
for (let i = 0; i < bytes.length; i += chunkSize) {
chunks.push(
String.fromCharCode(...bytes.subarray(i, i + chunkSize)),
);
}
return btoa(chunks.join(""));
}
export function unhex(hex: string): ArrayBuffer {
if (hex.length % 2 !== 0) {
throw new Error("Invalid hex string");
}
const bytes = new Uint8Array(hex.length / 2);
for (let i = 0; i < hex.length; i += 2) {
const byte = parseInt(hex.slice(i, i + 2), 16);
if (Number.isNaN(byte)) {
throw new Error("Invalid hex string");
}
bytes[i / 2] = byte;
}
return bytes.buffer;
}
export function randomString(length: number): string {
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let result = "";
const array = new Uint8Array(length);
getCrypto().getRandomValues(array);
for (let i = 0; i < length; i++) {
result += chars.charAt(array[i]! % chars.length);
}
return result;
}
// 正文算法: AES/CBC/PKCS5Padding
// 返回 string(xhtml/html) | 章节 JSON 对象 | undefined(解析失败)
export async function decryptChapter(
encrypted: string,
config: DeviceConfig = defaultConfig,
): Promise<string | unknown> {
if (!encrypted) {
throw new Error("Invalid encrypted chapter");
};
const buf = b64decode(encrypted);
const iv = buf.slice(0, 16);
const data = buf.slice(16);
const key = config.key_info?.key;
if (!key) {
throw new Error("Missing decrypt key")
}
const subtle = getSubtle();
const cryptoKey = await subtle.importKey(
"raw",
key,
{ name: "AES-CBC" },
false,
["decrypt"],
);
return subtle.decrypt(
{ name: "AES-CBC", iv },
cryptoKey,
data,
).then((decrypted) => {
const decoder = new TextDecoder();
const plain = decoder.decode(decrypted);
if (plain.trim().startsWith("<")) { // xhtml || html
return plain;
}
try {
return JSON.parse(plain); // mostly JSONObject
} catch (e: any) {
console.warn('Invalid chapter content: ', plain, e);
return undefined;
}
});
}
function reverseHex(value: string): string {
const be = BigInt(value).toString(16).padStart(32, "0");
let result = "";
for (let i = be.length; i > 0; i -= 2) result += be.slice(i - 2, i);
return result;
}
export async function encryptKeyinfoBody(config: DeviceConfig): Promise<string> {
const deviceId = config.device_id;
const iv = new TextEncoder().encode(randomString(16));
// 如果是i32类型(返回8字节)则啥也不用管。但是如果返回16以上(i64+),则需要取前八位,后面是0,删了
// BigInt按i64返回,所以取前八位
const data = new Uint8Array(unhex(reverseHex(deviceId))).slice(0, 8);
console.log(data)
const subtle = getSubtle();
const k = await subtle.importKey(
"raw",
shared_key,
{ name: "AES-CBC" },
false,
["encrypt"],
)
const encrypted = await subtle.encrypt(
{ name: "AES-CBC", iv },
k,
data
);
const final = new Uint8Array(iv.length + encrypted.byteLength);
console.log(final)
final.set(iv, 0);
final.set(new Uint8Array(encrypted), iv.length);
return JSON.stringify({
content: b64encode(final.buffer),
});
}
export async function decryptKeyinfoResponse(encrypted: string): Promise<ArrayBuffer> {
const buf = b64decode(encrypted);
const iv = buf.slice(0, 16);
const data = buf.slice(16);
const subtle = getSubtle();
const k = await subtle.importKey(
"raw",
shared_key,
{ name: "AES-CBC" },
false,
["decrypt"]
);
return subtle.decrypt(
{ name: "AES-CBC", iv },
k,
data
);
}
export async function decryptMangaImage(image: ArrayBuffer, key: string /* hex */): Promise<ArrayBuffer> {
const subtle = getSubtle();
// AESGCM
const cryptoKey = await subtle.importKey(
"raw",
unhex(key),
{ name: "AES-GCM" },
false,
["decrypt"],
);
const iv = image.slice(0, 12);
const data = image.slice(12);
return await subtle.decrypt(
{ name: "AES-GCM", iv },
cryptoKey,
data,
);
}
+7
View File
@@ -0,0 +1,7 @@
export async function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
export function cloneElement<T extends Element>(element: T): T {
return element.cloneNode(true) as T;
}
+147
View File
@@ -0,0 +1,147 @@
type GMRequestMethod = "GET" | "HEAD" | "POST" | "PUT" | "DELETE";
export type ApiResponse = Tampermonkey.Response<unknown> & {
json<T = unknown>(): T;
};
const supportedMethods = new Set<GMRequestMethod>([
"GET",
"HEAD",
"POST",
"PUT",
"DELETE",
]);
export default function apiFetch(
url: string,
options: RequestInit = {},
): Promise<ApiResponse> {
return new Promise((resolve, reject) => {
const { signal } = options;
if (signal?.aborted) {
reject(signal.reason ?? new DOMException("The operation was aborted", "AbortError"));
return;
}
const headers = normalizeHeaders(options.headers);
const data = normalizeBody(options.body);
// 不改写调用方传入的 options 对象。
const method = options.method ?? (data ? "POST" : "GET");
if (!supportedMethods.has(method as GMRequestMethod)) {
reject(new TypeError(`Unsupported request method: ${method}`));
return;
}
// abort/cleanup 必须在 GM_xmlhttpRequest 之前声明:
// 回调若同步触发,闭包引用尚未初始化的绑定会抛 ReferenceError(TDZ)。
let request: Tampermonkey.AbortHandle<void> | undefined;
const abort = () => request?.abort();
function cleanup(): void {
signal?.removeEventListener("abort", abort);
}
request = GM_xmlhttpRequest({
url,
method: method as GMRequestMethod,
headers,
data,
anonymous: options.credentials === "omit",
redirect:
options.redirect === "error"
? "error"
: "follow",
onload(response) {
cleanup();
resolve(Object.assign(response, {
json<T = unknown>(this: Tampermonkey.Response<unknown>): T {
return JSON.parse(this.responseText) as T;
},
}));
},
onerror(response) {
cleanup();
reject(createRequestError("Network request failed", response));
},
ontimeout() {
cleanup();
reject(createRequestError("Network request timed out", {
status: 0,
statusText: "Timeout",
url,
}));
},
onabort() {
cleanup();
reject(
signal?.reason ??
new DOMException("The operation was aborted", "AbortError"),
);
},
});
signal?.addEventListener("abort", abort, { once: true });
});
}
function normalizeHeaders(
headers?: HeadersInit,
): Record<string, string> | undefined {
if (!headers) {
return undefined;
}
return Object.fromEntries(new Headers(headers).entries());
}
function normalizeBody(
body?: BodyInit | null,
): string | Blob | ArrayBuffer | FormData | undefined {
if (body == null) {
return undefined;
}
if (body instanceof URLSearchParams) {
return body.toString();
}
if (
typeof body === "string" ||
body instanceof Blob ||
body instanceof ArrayBuffer ||
body instanceof FormData
) {
return body;
}
if (ArrayBuffer.isView(body)) {
return body.buffer.slice(
body.byteOffset,
body.byteOffset + body.byteLength,
) as ArrayBuffer;
}
throw new TypeError(
"GM_xmlhttpRequest does not support ReadableStream request bodies",
);
}
function createRequestError(
message: string,
response: any,
): TypeError {
const error = new TypeError(message);
Object.defineProperty(error, "response", {
configurable: true,
enumerable: false,
value: response,
});
return error;
}