From 455891353c46b444cd778825c01ca9a00783ab21 Mon Sep 17 00:00:00 2001 From: Garfield Date: Fri, 27 Nov 2026 07:43:39 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20=E8=BF=81=E7=A7=BB=E5=88=B0?= =?UTF-8?q?=E7=8E=B0=E8=A1=8C=20Web=20=E5=8D=8F=E8=AE=AE=EF=BC=9A=E7=AD=BE?= =?UTF-8?q?=E5=90=8D=E8=AF=B7=E6=B1=82=E3=80=81=E6=B5=8F=E8=A7=88=E5=99=A8?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E4=B8=8E=E5=88=86=E7=B1=BB=E4=B9=A6=E5=9F=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GetImageIndex / ImageToken 等接口走 ultra_sign 签名并解 bytesData; 登录改为浏览器授权或完整 Cookie,校验通过才保存。 --- .../moonsource_bilimanga/client.lua | 307 +++++++++++-- .../moonsource_bilimanga/crypto.lua | 404 ++++++++++++++++++ .../moonsource_bilimanga/l10n/en.lua | 17 +- .../moonsource_bilimanga/l10n/zh_TW.lua | 17 +- .../moonsource_bilimanga/mapper.lua | 142 ++++-- .../moonsource_bilimanga/setting.lua | 150 ++++--- tests/bilimanga/account_spec.lua | 74 ++++ tests/bilimanga/store_spec.lua | 44 ++ 8 files changed, 1012 insertions(+), 143 deletions(-) create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/crypto.lua create mode 100644 tests/bilimanga/account_spec.lua create mode 100644 tests/bilimanga/store_spec.lua diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua index 9e0d522..8c76670 100644 --- a/moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua @@ -1,9 +1,14 @@ local Request = require("http.request") local JSON = require("json") +local Crypto = require("moonsource_bilimanga.crypto") local _ = require("moonsource_bilimanga.l10n") local BASE = "https://manga.bilibili.com" local NOV = "27" +local QUERY = "device=pc&platform=web&nov=27&a=810" +local DATA_SN = "1E74C20E5720FBF3BB351965D7A9DFC1" +local session_buvid3, session_buvid4 +local apiCode local function getCookie() local cfg = require("utils.settings").getSource("bilimanga") @@ -30,7 +35,7 @@ local function makeHeaders(extra) end local function twirpAsync(service, method, body, cb) - local url = BASE .. "/twirp/" .. service .. "." .. method .. "?nov=" .. NOV + local url = BASE .. "/twirp/" .. service .. "/" .. method .. "?" .. QUERY local state = { cancelled = false } local function finish(data, err) @@ -57,8 +62,10 @@ local function twirpAsync(service, method, body, cb) if not Request.ok(code) then if code == 401 or code == 403 then local settings = require("utils.settings") - settings.saveSource("bilimanga", { cookie = "" }) - cb(nil, _("登录已过期,请重新输入 Cookie")) + local cfg = settings.getSource("bilimanga") + cfg.cookie, cfg.account_id = nil, nil + settings.saveSource("bilimanga") + finish(nil, require("source.auth").expire("bilimanga", _("登录已过期,请重新登录"))) else finish(nil, _("请求失败")) end @@ -70,6 +77,11 @@ local function twirpAsync(service, method, body, cb) finish(nil, _("响应无效")) return end + local bad = apiCode(data) + if bad then + finish(nil, bad) + return + end finish(data) end) @@ -93,51 +105,214 @@ local function twirpAsyncSimple(service, method, body, cb) end) end +function apiCode(wire) + local code = wire and wire.code + if code == nil or tonumber(code) == 0 then return nil end + if type(wire.msg) == "string" and wire.msg ~= "" then return wire.msg end + return _("请求失败") +end + +local function cookieValue(cookie, key) + if not cookie or cookie == "" then return nil end + return cookie:match(key .. "=([^;]*)") +end + +local function nowMs() + local ok, socket = pcall(require, "socket") + if ok and socket and socket.gettime then + return math.floor(socket.gettime() * 1000) + end + return os.time() * 1000 +end + +local function ensureBuvid(cookie, state, cb) + local from_cookie = cookieValue(cookie, "buvid3") + if from_cookie and from_cookie ~= "" then + session_buvid3 = from_cookie + session_buvid4 = cookieValue(cookie, "buvid4") or session_buvid4 + cb(session_buvid3, session_buvid4) + return + end + if session_buvid3 then + cb(session_buvid3, session_buvid4) + return + end + state.job = Request.request({ + url = "https://api.bilibili.com/x/frontend/finger/spi", + method = "GET", + headers = { + ["User-Agent"] = "Mozilla/5.0", + ["Accept"] = "application/json", + }, + timeout = require("http.timeout").net(1), + }, function(res, err) + if state.cancelled then return end + state.job = nil + if err or not res or not Request.ok(tonumber(res.code)) then + cb(nil, nil, _("请求失败")) + return + end + local ok, wire = pcall(JSON.decode, res.body) + local data = ok and wire and wire.data + if type(data) ~= "table" or type(data.b_3) ~= "string" or data.b_3 == "" then + cb(nil, nil, _("响应无效")) + return + end + session_buvid3 = data.b_3 + session_buvid4 = data.b_4 + cb(session_buvid3, session_buvid4) + end) +end + +local function signedAsync(service, method, body, decrypt_id, cb) + local state = { cancelled = false, job = nil } + local cookie = getCookie() + + local function finish(data, err) + if state.cancelled then return end + state.job = nil + cb(data, err) + end + + local function post(b3, b4) + if state.cancelled then return end + local body_str = JSON.encode(body or {}) + local sign = Crypto.sign(QUERY, body_str, nowMs()) + local headers = makeHeaders() + headers["x-bili-data-sn"] = DATA_SN + if not cookieValue(cookie, "buvid3") then + local extra = "buvid3=" .. b3 + if type(b4) == "string" and b4 ~= "" then + extra = extra .. "; buvid4=" .. b4 + end + if cookie and cookie ~= "" then + headers.Cookie = cookie .. "; " .. extra + else + headers.Cookie = extra + end + end + state.job = Request.request({ + url = BASE .. "/twirp/" .. service .. "/" .. method + .. "?" .. QUERY .. "&ultra_sign=" .. Crypto.urlencode(sign), + method = "POST", + body = body_str, + headers = headers, + timeout = require("http.timeout").net(1), + }, function(res, err) + if state.cancelled then return end + state.job = nil + if err or not res then + finish(nil, err and tostring(err) or _("请求失败")) + return + end + if not Request.ok(tonumber(res.code)) then + finish(nil, _("请求失败")) + return + end + local ok, wire = pcall(JSON.decode, res.body) + if not ok or type(wire) ~= "table" then + finish(nil, _("响应无效")) + return + end + local bad = apiCode(wire) + if bad then + finish(nil, bad) + return + end + if type(wire.bytesData) == "string" and wire.bytesData ~= "" then + if decrypt_id == nil then + finish(nil, _("响应无效")) + return + end + local plain = Crypto.open(wire.bytesData, b3, decrypt_id) + if type(plain) ~= "string" then + finish(nil, _("响应无效")) + return + end + local decoded, obj = pcall(JSON.decode, plain) + if not decoded or type(obj) ~= "table" then + finish(nil, _("响应无效")) + return + end + finish(obj) + return + end + finish(wire.data or wire) + end) + end + + ensureBuvid(cookie, state, function(b3, b4, err) + if err or not b3 then + finish(nil, err or _("请求失败")) + return + end + post(b3, b4) + end) + + return { + cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end, + } +end + -- ============================================================ -- Comic 服务 -- ============================================================ +local Client = {} + function Client.searchAsync(keyword, page, page_size, cb) - return twirpAsync("comic.v1.Comic", "Search", { - keyword = keyword, - page = page or 1, - page_size = page_size or 20, - }, function(wire, err) + return signedAsync("comic.v1.Comic", "Search", { + keyWord = keyword, + pageNum = page or 1, + pageSize = page_size or 20, + }, nil, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end function Client.comicDetailAsync(comic_id, cb) - return twirpAsync("comic.v1.Comic", "ComicDetail", { - comic_id = tonumber(comic_id), - }, function(wire, err) + local id = tonumber(comic_id) + return signedAsync("comic.v1.Comic", "ComicDetail", { + comic_id = id, + }, tostring(id), function(wire, err) if not wire then cb(nil, err); return end - cb(wire.comic) + cb(wire.comic or wire) end) end function Client.comicDetailLiteAsync(comic_id, cb) - return twirpAsync("comic.v1.Comic", "ComicDetailLite", { - comic_id = tonumber(comic_id), - }, function(wire, err) - if not wire then cb(nil, err); return end - cb(wire.comic) - end) + return Client.comicDetailAsync(comic_id, cb) end function Client.imageIndexAsync(ep_id, cb) - return twirpAsync("comic.v1.Comic", "GetImageIndex", { - ep_id = tonumber(ep_id), - mode = 2, - quality = 5, - type = 1, - }, function(wire, err) + local id = tonumber(ep_id) + return signedAsync("comic.v1.Comic", "GetImageIndex", { + ep_id = id, + }, tostring(id), function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end +-- 站点用这个公钥决定要不要把原图包成密文。没有配对私钥,解不了 0x08 那种页。 +local M1 = "BB0d+pwvfKzW0hUAiBNsnSLRFVnZ0S8pxSYtuF9kScmWvdWuxvmXDikDKTG5M/0zeTR7konA9ImBpO1FqccgvwI=" + +function Client.imageTokenAsync(paths, cb) + local parts = {} + for i = 1, #paths do + parts[i] = '"' .. tostring(paths[i]):gsub("\\", "\\\\"):gsub('"', '\\"') .. '"' + end + local urls = "[" .. table.concat(parts, ",") .. "]" + return signedAsync("comic.v1.Comic", "ImageToken", { + urls = urls, + m1 = M1, + }, urls, cb) +end + function Client.homeHotAsync(cb) return twirpAsync("comic.v1.Comic", "HomeHot", { tab = 0, @@ -150,16 +325,26 @@ function Client.homeHotAsync(cb) end) end -function Client.classPageAsync(cb) - return twirpAsync("comic.v1.Comic", "ClassPage", { - page = 1, - page_size = 20, - }, function(wire, err) +function Client.allLabelAsync(cb) + return twirpAsync("comic.v1.Comic", "AllLabel", {}, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end +function Client.classPageAsync(choice, page, cb) + return signedAsync("comic.v1.Comic", "ClassPage", { + style_id = choice.style_id, + area_id = -1, + is_finish = -1, + order = choice.order, + special_tag = 0, + page_num = page, + page_size = 15, + is_free = -1, + }, tostring(choice.style_id), cb) +end + function Client.recommendAsync(comic_id, cb) return twirpAsync("comic.v1.Comic", "Recommend", { comic_id = tonumber(comic_id), @@ -177,8 +362,23 @@ function Client.listFavoriteAsync(page_num, page_size, cb) return twirpAsync("bookshelf.v1.Bookshelf", "ListFavorite", { page_num = page_num or 1, page_size = page_size or 20, + order = 0, + wait_free = 0, + time_limit_free = 0, + type = 0, from = "web", source = "web", + filter = { + reading_progress = -1, + is_finish = -1, + area = -1, + comic_type = -1, + wait_free = -1, + style = -1, + out_label = -1, + out_label_type = 0, + }, + show_update_group = false, }, function(wire, err) if not wire then cb(nil, err); return end cb(wire) @@ -259,6 +459,48 @@ end -- 公共工具 -- ============================================================ +function Client.loginCheckAsync(cookie, cb) + if type(cookie) ~= "string" or cookie == "" then + cb(false, _("没有读到 Cookie")) + return { cancel = function() end } + end + local state = { cancelled = false } + state.job = Request.request({ + url = "https://api.bilibili.com/x/web-interface/nav", + method = "GET", + headers = { + ["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", + ["Accept"] = "application/json", + ["Referer"] = BASE .. "/", + Cookie = cookie, + }, + timeout = require("http.timeout").net(1), + }, function(res, err) + if state.cancelled then return end + state.job = nil + if err or not res or not Request.ok(tonumber(res.code)) then + cb(false, _("请求失败")) + return + end + local ok, wire = pcall(JSON.decode, res.body) + local data = ok and type(wire) == "table" and wire.data + local mid = type(data) == "table" and data.mid + local id = type(mid) == "number" and tostring(math.floor(mid)) or mid + if type(data) == "table" and data.isLogin == true and tonumber(wire.code) == 0 + and type(id) == "string" and id:match("^%d+$") then + cb(true, nil, { id = id }) + return + end + cb(false, _("登录校验失败,请确认已经登录哔哩哔哩")) + end) + return { + cancel = function() + state.cancelled = true + if state.job and state.job.cancel then state.job.cancel() end + end, + } +end + function Client.hasAccount() local cfg = require("utils.settings").getSource("bilimanga") return cfg.cookie ~= nil and cfg.cookie ~= "" @@ -266,12 +508,13 @@ end function Client.setCookie(cookie) local cfg = require("utils.settings").getSource("bilimanga") - cfg.cookie = cookie or "" - require("utils.settings").saveSource("bilimanga", cfg) + cfg.cookie = (type(cookie) == "string" and cookie ~= "") and cookie or nil + cfg.account_id = nil + require("utils.settings").saveSource("bilimanga") end function Client.clearCookie() - Client.setCookie("") + Client.setCookie(nil) end -- 分页遍历 diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/crypto.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/crypto.lua new file mode 100644 index 0000000..e73ba99 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/crypto.lua @@ -0,0 +1,404 @@ +local bit = require("bit") +local band, bor, bxor = bit.band, bit.bor, bit.bxor +local lshift, rshift = bit.lshift, bit.rshift + +local Crypto = {} + +local ALPHA62 = "br5NH9CxpvJzmEt3OqoF7jgWMIZ2UnASfc8K6XaLYylT1eVBGh4sdQkDwRP0ui" +local B64 = { + "UalVqQk8T7+5oJxC6MzIniWDrc3XERGN/wdLyp90mf2tHuvsgeSjZbBF1KAOPhY4", + "zI3XZb8T7+5opF1KJxUaBqQk90mf6MlVCEceSjAOPhY42RGN/wdLytHuvsgniWDr", +} + +local function u8(x) + return band(x, 0xff) +end + +local function xtime(x) + x = u8(x) + local hi = band(x, 0x80) + local y = u8(lshift(x, 1)) + if hi ~= 0 then y = bxor(y, 0x1b) end + return y +end + +local function mul(a, b) + local p = 0 + a, b = u8(a), u8(b) + for _ = 1, 8 do + if band(b, 1) ~= 0 then p = bxor(p, a) end + local hi = band(a, 0x80) + a = u8(lshift(a, 1)) + if hi ~= 0 then a = bxor(a, 0x1b) end + b = rshift(b, 1) + end + return p +end + +local function rotl8(x, n) + x = u8(x) + return u8(bor(lshift(x, n), rshift(x, 8 - n))) +end + +local SBOX, INV = {}, {} +for x = 0, 255 do + local inv = 0 + if x ~= 0 then + for i = 1, 255 do + if mul(x, i) == 1 then inv = i; break end + end + end + local y = bxor(inv, rotl8(inv, 1), rotl8(inv, 2), rotl8(inv, 3), rotl8(inv, 4), 0x63) + SBOX[x] = y + INV[y] = x +end + +local function expand192(key) + local words = {} + for i = 0, 5 do + words[i] = { + key:byte(i * 4 + 1), + key:byte(i * 4 + 2), + key:byte(i * 4 + 3), + key:byte(i * 4 + 4), + } + end + local rcon = 0x01 + for i = 6, 51 do + local prev = words[i - 1] + local t1, t2, t3, t4 = prev[1], prev[2], prev[3], prev[4] + if i % 6 == 0 then + t1, t2, t3, t4 = SBOX[t2], SBOX[t3], SBOX[t4], SBOX[t1] + t1 = bxor(t1, rcon) + rcon = xtime(rcon) + end + local old = words[i - 6] + words[i] = { bxor(old[1], t1), bxor(old[2], t2), bxor(old[3], t3), bxor(old[4], t4) } + end + return words +end + +local function addRound(s, words, round) + for c = 0, 3 do + local w = words[round * 4 + c] + for r = 0, 3 do + local i = c * 4 + r + s[i] = bxor(s[i], w[r + 1]) + end + end +end + +local function mod4(x) + return (x % 4 + 4) % 4 +end + +local function invShift(s) + local t = {} + for i = 0, 15 do t[i] = s[i] end + for r = 1, 3 do + for c = 0, 3 do + s[c * 4 + r] = t[mod4(c - r) * 4 + r] + end + end +end + +local function invMix(s) + for c = 0, 3 do + local o = c * 4 + local a, b, d, e = s[o], s[o + 1], s[o + 2], s[o + 3] + s[o] = bxor(mul(a, 14), mul(b, 11), mul(d, 13), mul(e, 9)) + s[o + 1] = bxor(mul(a, 9), mul(b, 14), mul(d, 11), mul(e, 13)) + s[o + 2] = bxor(mul(a, 13), mul(b, 9), mul(d, 14), mul(e, 11)) + s[o + 3] = bxor(mul(a, 11), mul(b, 13), mul(d, 9), mul(e, 14)) + end +end + +local function decryptBlock(block, words) + local s = {} + for i = 0, 15 do s[i] = block:byte(i + 1) end + addRound(s, words, 12) + for round = 11, 1, -1 do + invShift(s) + for i = 0, 15 do s[i] = INV[s[i]] end + addRound(s, words, round) + invMix(s) + end + invShift(s) + for i = 0, 15 do s[i] = INV[s[i]] end + addRound(s, words, 0) + local out = {} + for i = 0, 15 do out[i + 1] = string.char(s[i]) end + return table.concat(out) +end + +local function b64dec(s) + local map = {} + local alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" + for i = 1, #alpha do map[alpha:sub(i, i)] = i - 1 end + s = s:gsub("%s", ""):gsub("=", "") + local out, buf, n = {}, 0, 0 + for i = 1, #s do + local v = map[s:sub(i, i)] + if v then + buf = buf * 64 + v + n = n + 1 + if n == 4 then + out[#out + 1] = string.char( + math.floor(buf / 65536) % 256, + math.floor(buf / 256) % 256, + buf % 256) + buf, n = 0, 0 + end + end + end + if n == 2 then + buf = buf * 64 * 64 + out[#out + 1] = string.char(math.floor(buf / 65536) % 256) + elseif n == 3 then + buf = buf * 64 + out[#out + 1] = string.char(math.floor(buf / 65536) % 256, math.floor(buf / 256) % 256) + end + return table.concat(out) +end + +function Crypto.open(bytesData, buvid3, id) + local even = {} + for i = 1, #buvid3, 2 do + even[#even + 1] = buvid3:sub(i, i) + end + local head = table.concat(even):sub(1, 18) + local tail = tostring(id) + tail = tail:sub(math.max(1, #tail - 2)) + local key = (head .. "web" .. tail) + if #key < 24 then key = key .. string.rep("=", 24 - #key) end + key = key:sub(1, 24) + local words = expand192(key) + local iv = key:sub(1, 16) + local raw = b64dec(bytesData) + local prev = iv + local plain = {} + for i = 1, #raw, 16 do + local block = raw:sub(i, i + 15) + local dec = decryptBlock(block, words) + local chunk = {} + for b = 1, 16 do + chunk[b] = string.char(bxor(dec:byte(b), prev:byte(b))) + end + plain[#plain + 1] = table.concat(chunk) + prev = block + end + plain = table.concat(plain) + local pad = plain:byte(#plain) + if not pad or pad < 1 or pad > 16 then return nil end + return plain:sub(1, #plain - pad) +end + +local function u32hex(w) + w = band(w, 0xffffffff) + if w < 0 then w = w + 4294967296 end + return string.format("%08x", w) +end + +local function rol(x, n) + return bit.rol(band(x, 0xffffffff), n) +end + +local function u32n(x) + x = band(x, 0xffffffff) + if x < 0 then x = x + 4294967296 end + return x +end + +local function add32(a, b, c) + local s = u32n(a) + u32n(b) + if c then s = s + u32n(c) end + return band(s % 4294967296, 0xffffffff) +end + +local function processBlock(block, a, b, c, d) + for i = 0, 15 do + local o = i * 4 + local w = bor( + block[o], + lshift(block[o + 1], 8), + lshift(block[o + 2], 16), + lshift(block[o + 3], 24)) + a = add32(a, bor(band(b, c), band(bit.bnot(b), d)), w) + b = add32(b, bxor(c, a, d), w) + c = add32(c, bor(band(b, a), band(bit.bnot(b), d)), w) + d = add32(d, bxor(c, a, b), w) + a, b, c, d = rol(a, 5), rol(b, 7), rol(c, 3), rol(d, 11) + end + return a, b, c, d +end + +local function md5v2(data) + local len = #data + local zeros = 64 - ((len + 9) % 64) + local n = len + 1 + zeros + 8 + local buf = {} + for i = 0, n - 1 do buf[i] = 0 end + for i = 1, len do buf[i - 1] = data:byte(i) end + buf[len] = 0x80 + local bits = len * 8 + for i = 0, 7 do + buf[n - 8 + i] = bits % 256 + bits = math.floor(bits / 256) + end + local a, b, c, d = 0xabcdef01, 0x12345678, 0xdeadbeef, 0xfeedcafe + for off = 0, n - 1, 64 do + local block = {} + for i = 0, 63 do block[i] = buf[off + i] end + a, b, c, d = processBlock(block, a, b, c, d) + end + local hex = u32hex(a) .. u32hex(b) .. u32hex(c) .. u32hex(d) + local out = {} + for i = 1, #hex do + local idx = hex:byte(i) % 62 + out[i] = ALPHA62:sub(idx + 1, idx + 1) + end + return table.concat(out) +end + +local function xrc4(data) + local key = { 1, 3, 7 } + local S = {} + for i = 0, 255 do S[i] = i end + local j = 0 + for i = 0, 255 do + j = band(j + S[i] + key[(i % 3) + 1], 255) + S[i], S[j] = S[j], S[i] + S[i] = bxor(S[i], i) + end + local out, ii, jj = {}, 0, 0 + for n = 1, #data do + ii = band(ii + 1, 255) + jj = band(jj + S[ii], 255) + S[ii], S[jj] = S[jj], S[ii] + out[n] = string.char(bxor(data:byte(n), S[band(S[ii] + S[jj] + 1, 255)])) + end + return table.concat(out) +end + +local function b64v2(data, variant) + local table64 = B64[variant + 1] + local out = {} + local n = #data + for i = 0, n - 1, 3 do + local b1 = data:byte(i + 1) or 0 + local b2 = data:byte(i + 2) or 0 + local b3 = data:byte(i + 3) or 0 + local v = b1 * 65536 + b2 * 256 + b3 + for k = 0, 3 do + local shift = 18 - 6 * k + local idx = math.floor(v / (2 ^ shift)) % 64 + out[#out + 1] = table64:sub(idx + 1, idx + 1) + end + end + local rem = n % 3 + if rem ~= 0 then + out[#out + 1] = string.rep("=", 3 - rem) + end + return table.concat(out) +end + +local function hexTs(ts) + local hex = {} + ts = math.floor(ts) + if ts == 0 then return "0" end + while ts > 0 do + local d = ts % 16 + hex[#hex + 1] = string.sub("0123456789abcdef", d + 1, d + 1) + ts = math.floor(ts / 16) + end + for i = 1, math.floor(#hex / 2) do + hex[i], hex[#hex - i + 1] = hex[#hex - i + 1], hex[i] + end + return table.concat(hex) +end + +local function binTs(ts) + ts = math.floor(ts / 128) + if ts == 0 then return "0" end + local bits = {} + while ts > 0 do + bits[#bits + 1] = (ts % 2 == 1) and "1" or "0" + ts = math.floor(ts / 2) + end + for i = 1, math.floor(#bits / 2) do + bits[i], bits[#bits - i + 1] = bits[#bits - i + 1], bits[i] + end + return table.concat(bits) +end + +function Crypto.sign(query, body, ts) + local params = {} + for key, value in query:gmatch("([^&=]+)=([^&]*)") do + if key ~= "ultra_sign" then params[#params + 1] = { key, value } end + end + table.sort(params, function(a, b) return a[1] < b[1] end) + local acc = {} + for i = 1, #params do + acc[#acc + 1] = params[i][1] .. params[i][2] + end + acc = table.concat(acc) + ts = math.floor(ts) + local h1 = md5v2(acc .. hexTs(ts)) + local h2 = md5v2(body .. binTs(ts)) + local h3 = md5v2(b64v2(xrc4(body), ts % 2)) + local t = ts % 4294967296 + local function sh(n) + return math.floor(ts / (2 ^ n)) % 256 + end + local function tb(n) + return math.floor(t / (2 ^ n)) % 256 + end + local buf = { + 1, sh(23), sh(31), sh(15), 7, + h1:byte(14), h1:byte(24), h2:byte(12), h2:byte(8), h3:byte(24), h3:byte(20), + tb(8), tb(24), tb(16), + 7, 0, 5, 0, 4, 1, 5, 0, 2, 0, 1, 0, 6, 2, 0, 0, + } + local x = 0 + for i = 1, 28 do x = bxor(x, buf[i]) end + buf[30] = x + local order = { 23, 8, 18, 22, 17, 29, 16, 13, 5, 4, 15, 28, 11, 7, 12, 20, 25, 26, 27, 21, 24, 19, 9, 3 } + local out = { buf[1], buf[2], 0, 0, 0 } + for i = 1, #order do out[#out + 1] = buf[order[i]] end + local function cat(bytes) + local s = {} + for i = 1, #bytes do s[i] = string.char(bytes[i]) end + return table.concat(s) + end + local head = cat(out) + local ha = md5v2(head .. string.char(h1:byte(8), h2:byte(30))) + local hb = md5v2(head .. string.char(h3:byte(32))) + local sign = { ha:sub(1, 24):byte(1, 24) } + local hb24 = { hb:sub(1, 24):byte(1, 24) } + for i = 1, 24 do sign[24 + i] = hb24[i] end + local hex = hexTs(ts) + local places = { 42, 38, 24, 30, 14, 20, 6, 48, 8, 12, 18 } + for pos = 1, #places do + local ch = hex:byte(pos) + if ch then sign[places[pos]] = ch end + end + local raw = {} + for i = 1, 48 do raw[i] = string.char(sign[i] or 0) end + return table.concat(raw) +end + +function Crypto.urlencode(s) + local out = {} + for i = 1, #s do + local c = s:byte(i) + local ch = string.char(c) + if ch:match("^[%w%-_%.!~%*'%(%)]$") then + out[#out + 1] = ch + else + out[#out + 1] = string.format("%%%02X", c) + end + end + return table.concat(out) +end + +return Crypto diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua index c910849..11385c1 100644 --- a/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua @@ -1,11 +1,16 @@ return { ["哔哩哔哩漫画"] = "Bilibili Manga", ["哔哩哔哩漫画书源"] = "Bilibili Manga Source", - ["请输入 SESSDATA Cookie"] = "Enter SESSDATA Cookie", ["登录"] = "Login", ["已登录"] = "Logged in", - ["清除"] = "Clear", - ["未登录"] = "Not logged in", + ["未登录 · 点此登录"] = "Not logged in · tap to log in", + ["哔哩漫画账号"] = "Bilibili Manga account", + ["哔哩漫画登录 Cookie"] = "Bilibili Manga login cookie", + ["在漫画官网登录后,复制请求标头里的完整 Cookie"] = "Log in on the manga site, then copy the full Cookie request header", + ["确定退出哔哩漫画账号?"] = "Log out of Bilibili Manga?", + ["哔哩账号标识缺失"] = "Bilibili account id is missing", + ["登录校验失败,请确认已经登录哔哩哔哩"] = "Login check failed. Confirm you are logged in to Bilibili", + ["没有读到 Cookie"] = "No cookie was found", ["搜索"] = "Search", ["首页"] = "Home", ["分类"] = "Classify", @@ -16,13 +21,17 @@ return { ["网络不可用,请先连接 Wi-Fi"] = "Network unavailable, please connect to Wi-Fi first", ["请求失败"] = "Request failed", ["响应无效"] = "Invalid response", - ["登录已过期,请重新输入 Cookie"] = "Login expired, please re-enter Cookie", + ["登录已过期,请重新登录"] = "Login expired. Please log in again", ["获取用户信息失败"] = "Failed to get user info", ["加载目录失败"] = "Failed to load table of contents", ["获取漫画详情失败"] = "Failed to get manga details", ["搜索失败"] = "Search failed", ["目录加载中…"] = "Loading table of contents...", ["无搜索结果"] = "No search results", + ["全部"] = "All", + ["排序"] = "Sort", + ["题材"] = "Genre", + ["本章未购买"] = "This chapter has not been purchased", ["连载"] = "Ongoing", ["完结"] = "Completed", } diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua index 8abb7b0..335ce40 100644 --- a/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua @@ -1,11 +1,16 @@ return { ["哔哩哔哩漫画"] = "哔哩哔哩漫画", ["哔哩哔哩漫画书源"] = "哔哩哔哩漫画书源", - ["请输入 SESSDATA Cookie"] = "請輸入 SESSDATA Cookie", ["登录"] = "登入", ["已登录"] = "已登入", - ["清除"] = "清除", - ["未登录"] = "未登入", + ["未登录 · 点此登录"] = "未登入 · 點此登入", + ["哔哩漫画账号"] = "嗶哩漫畫帳號", + ["哔哩漫画登录 Cookie"] = "嗶哩漫畫登入 Cookie", + ["在漫画官网登录后,复制请求标头里的完整 Cookie"] = "在漫畫官網登入後,複製請求標頭裡的完整 Cookie", + ["确定退出哔哩漫画账号?"] = "確定退出嗶哩漫畫帳號?", + ["哔哩账号标识缺失"] = "嗶哩帳號識別碼缺失", + ["登录校验失败,请确认已经登录哔哩哔哩"] = "登入驗證失敗,請確認已經登入嗶哩嗶哩", + ["没有读到 Cookie"] = "沒有讀到 Cookie", ["搜索"] = "搜尋", ["首页"] = "首頁", ["分类"] = "分類", @@ -16,13 +21,17 @@ return { ["网络不可用,请先连接 Wi-Fi"] = "網路不可用,請先連線 Wi-Fi", ["请求失败"] = "請求失敗", ["响应无效"] = "回應無效", - ["登录已过期,请重新输入 Cookie"] = "登入已過期,請重新輸入 Cookie", + ["登录已过期,请重新登录"] = "登入已過期,請重新登入", ["获取用户信息失败"] = "取得使用者資訊失敗", ["加载目录失败"] = "載入目錄失敗", ["获取漫画详情失败"] = "取得漫畫詳情失敗", ["搜索失败"] = "搜尋失敗", ["目录加载中…"] = "目錄載入中…", ["无搜索结果"] = "無搜尋結果", + ["全部"] = "全部", + ["排序"] = "排序", + ["题材"] = "題材", + ["本章未购买"] = "本章未購買", ["连载"] = "連載中", ["完结"] = "已完成", } diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua index c33c706..f885ae8 100644 --- a/moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua @@ -11,41 +11,60 @@ end -- Book 映射 -- ============================================================ -function Mapper.book(info) - if not info then return nil end - local cover = info.vcover or info.horizontal_cover or info.cover or "" - local author = info.author - local author_str = "" - if author then - if type(author) == "string" then - author_str = author - elseif type(author) == "table" then - if author.name then author_str = author.name end +local function authorOf(info) + local author = info.author_name or info.author + if type(author) == "string" and author ~= "" then return author end + if type(author) ~= "table" then return "未知作者" end + if type(author.name) == "string" and author.name ~= "" then return author.name end + local names = {} + for i = 1, #author do + local item = author[i] + if type(item) == "string" and item ~= "" then + names[#names + 1] = item + elseif type(item) == "table" and type(item.name) == "string" and item.name ~= "" then + names[#names + 1] = item.name end end - if author_str == "" then author_str = "未知作者" end + if #names == 0 then return "未知作者" end + return table.concat(names, " / ") +end + +local function plainTitle(info) + local title = info.org_title or info.title or "" + return tostring(title):gsub("<.->", "") +end + +local Mapper = {} + +function Mapper.book(info) + if not info then return nil end + local comic_id = info.comic_id or info.season_id or info.id + if comic_id == nil or comic_id == "" then return nil end + local cover = info.vertical_cover or info.vcover or info.horizontal_cover or info.square_cover or info.cover or "" local styles = info.styles local category = "" - if styles and type(styles) == "table" and #styles > 0 then + if styles and type(styles) == "table" and #styles > 0 and type(styles[1]) == "string" then category = table.concat(styles, " · ") end local status_str = _("连载") - if info.status == 2 then status_str = _("完结") end + if info.is_finish == 1 or info.is_finish == true or info.status == 2 then + status_str = _("完结") + end return { source_id = SOURCE_ID, - stable_id = tostring(info.comic_id), - title = clean(info.title), - authors = author_str, + stable_id = tostring(comic_id), + title = clean(plainTitle(info)), + authors = authorOf(info), cover = cover, - intro = clean(info.desc), + intro = clean(info.desc ~= "" and info.desc or info.evaluate), category = category, meta = { status = status_str, fans = info.fans or "", - total_eps = info.ep_count or info.ord_count or 0, + total_eps = info.ep_count or info.total or info.ord_count or 0, }, } end @@ -67,7 +86,7 @@ function Mapper.chapters(comic) idx = i, uid = tostring(ep.id), title = clean(ep.title or ep.short_title or ("第" .. i .. "话")), - vip = ep.pay_type == 1 or (ep.is_pay == true and true) or false, + vip = ep.is_locked == true, } end return chapters @@ -103,9 +122,81 @@ end -- Search 映射 -- ============================================================ +function Mapper.rows(wire) + if type(wire) ~= "table" then return nil end + if wire[1] ~= nil or next(wire) == nil then return wire end + if type(wire.list) == "table" then return wire.list end + local data = wire.data + if type(data) ~= "table" then return nil end + if type(data.list) == "table" then return data.list end + if data[1] ~= nil or next(data) == nil then return data end + return nil +end + +local function choices(list) + if type(list) ~= "table" then return nil end + local out = {} + for _idx, item in ipairs(list) do + local id = type(item) == "table" and tonumber(item.id) + local name = type(item) == "table" and item.name + if not id or id ~= math.floor(id) or type(name) ~= "string" or name == "" then return nil end + out[#out + 1] = { id = id, name = name } + end + return #out > 0 and out or nil +end + +function Mapper.labels(wire) + local data = type(wire) == "table" and wire.data or nil + if type(data) ~= "table" then return nil end + local styles, orders = choices(data.styles), choices(data.orders) + if not styles or not orders then return nil end + return { styles = styles, orders = orders } +end + +function Mapper.storeChoice(node, labels) + local order, style = tostring(node or ""):match("^(-?%d+):(-?%d+)$") + order, style = tonumber(order), tonumber(style) + local function has(list, id) + for _idx, item in ipairs(list) do + if item.id == id then return true end + end + end + if not has(labels.orders, order) then order = labels.orders[1].id end + if style ~= -1 and not has(labels.styles, style) then style = -1 end + return order, style +end + +function Mapper.storeGroups(labels, order, style) + local Browse = require("source.browse") + local node = order .. ":" .. style + local orders, styles = {}, { { id = order .. ":-1", title = _("全部") } } + for _idx, item in ipairs(labels.orders) do + orders[#orders + 1] = { id = item.id .. ":" .. style, title = item.name } + end + for _idx, item in ipairs(labels.styles) do + styles[#styles + 1] = { id = order .. ":" .. item.id, title = item.name } + end + local sort_group = Browse.group(orders, node) + local style_group = Browse.group(styles, node) + sort_group.title = _("排序") + style_group.title = _("题材") + return { sort_group, style_group } +end + +function Mapper.books(wire) + local rows = Mapper.rows(wire) + if not rows then return nil end + local books = {} + for i = 1, #rows do + local book = Mapper.book(rows[i]) + if book then books[#books + 1] = book end + end + if #rows > 0 and #books == 0 then return nil end + return books +end + function Mapper.searchResults(wire) - if not wire then return {} end - local items = wire.list or {} + local items = Mapper.rows(wire) or {} local books = {} for i = 1, #items do local book = Mapper.book(items[i]) @@ -119,8 +210,7 @@ end -- ============================================================ function Mapper.favoriteItems(wire) - if not wire then return {} end - return wire.list or {} + return Mapper.rows(wire) end -- ============================================================ @@ -128,10 +218,10 @@ end -- ============================================================ function Mapper.historyItem(wire, comic_id) - if not wire then return nil end - local list = wire.list or {} + local list = Mapper.rows(wire) + if not list then return nil end for _, item in ipairs(list) do - if tostring(item.comic_id) == tostring(comic_id) then + if tostring(item.comic_id or item.season_id) == tostring(comic_id) then return item end end diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua index 163f3b7..fc82e3c 100644 --- a/moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua @@ -1,82 +1,78 @@ +--[[-- +哔哩漫画账号:浏览器授权与完整 Cookie。校验通过才保存。 + +漫画站复用哔哩哔哩主站会话。已购和大会员话由详情里的 is_locked 表示, +不在这里另做会员开关。 + +@module moonsource_bilimanga.setting +--]] + +local CookieLogin = require("source.cookie_login") local _ = require("moonsource_bilimanga.l10n") -local ID = "bilimanga" +local SOURCE_ID = "bilimanga" +local Setting = {} -local function entries(desktop) - return { { - group = "network", - order = 100, - id = "login", - icon = "d_overwrite_feature", - title = _("哔哩哔哩漫画"), - page = { - title = _("哔哩哔哩漫画"), - sections = function() - local cfg = require("utils.settings").getSource(ID) - local has_cookie = cfg.cookie and cfg.cookie ~= "" - - local function doLogin() - require("ui/modal").input({ - title = _("请输入 SESSDATA Cookie"), - button = _("登录"), - text = cfg.cookie or "", - hint = "SESSDATA", - hint_is_field = true, - }, function(entry) - if not entry or entry == "" then return end - require("utils.settings").saveSource(ID, { - cookie = entry, - }) - require("ui/uimanager"):popMenu() - local Toast = require("ui/themed").Toast - Toast:new({ - text = _("已登录"), - timeout = 2, - }):show() - desktop:onEvent("book_source_refresh") - end) - end - - local function doClear() - require("utils.settings").saveSource(ID, { - cookie = "", - }) - require("ui/uimanager"):popMenu() - local Toast = require("ui/themed").Toast - Toast:new({ - text = _("已清除 Cookie"), - timeout = 2, - }):show() - desktop:onEvent("book_source_refresh") - end - - local rows = { { - fn = function() - return require("desktop.pages.setting.tree").Row.action({ - text = has_cookie and _("已登录") or _("未登录"), - callback = doLogin, - }) - end, - } } - - if has_cookie then - rows[#rows + 1] = { - fn = function() - return require("desktop.pages.setting.tree").Row.action({ - text = _("清除"), - callback = doClear, - }) - end, - } - end - - return { { - title = "", - rows = rows, - } } - end, - }, - } } +local function loggedIn() + local cfg = require("utils.settings").getSource(SOURCE_ID) + return type(cfg.cookie) == "string" and cfg.cookie ~= "" end -return { entries = entries } +local function commit(cookie, account, cb, current) + if type(account) ~= "table" or type(account.id) ~= "string" or not account.id:match("^%d+$") then + cb(false, _("哔哩账号标识缺失")) + return + end + return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, cb, current) +end + +---@type CookieLoginSpec +local SPEC = { + id = SOURCE_ID, + title = _("哔哩漫画账号"), + cookie_title = _("哔哩漫画登录 Cookie"), + cookie_hint = _("在漫画官网登录后,复制请求标头里的完整 Cookie"), + logout_text = _("确定退出哔哩漫画账号?"), + loggedIn = loggedIn, + checkAsync = function(cookie, cb) + return require("moonsource_bilimanga.client").loginCheckAsync(cookie, cb) + end, + commit = commit, + clear = function(cfg) cfg.cookie, cfg.account_id = nil, nil end, +} + +function Setting.rowStatus() + local on = CookieLogin.authorized(SPEC) + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +function Setting.rowIcon() + return "menu_book" +end + +Setting.browser = { + domain = "manga.bilibili.com", + scope = "cookie", + login = "https://manga.bilibili.com/account-center", + check = "https://manga.bilibili.com/account-center", + icon = "https://i0.hdslb.com/bfs/activity-plat/static/20250320/1e16455b3e0f77ddb2522c3ae2aba5d9/SgyyYc4rbJ.ico", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) + return CookieLogin.save(SPEC, CookieLogin.fromPayload(payload, "bilibili.com"), cb) + end, +} + +function Setting.rows() + local rows = { + CookieLogin.browserRow(), + CookieLogin.pasteRow(SPEC), + } + if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end + return rows +end + +function Setting.login() + CookieLogin.prompt(SPEC) +end + +return Setting diff --git a/tests/bilimanga/account_spec.lua b/tests/bilimanga/account_spec.lua new file mode 100644 index 0000000..728d531 --- /dev/null +++ b/tests/bilimanga/account_spec.lua @@ -0,0 +1,74 @@ +--[[-- +哔哩漫画账号校验,以及已解锁话不被本机标成未购买。 + +@module tests.moonsource_bilimanga.account_spec +--]] + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +local Json = require("support.json_stub") + +local Mapper = require("moonsource_bilimanga.mapper") +local chapters = Mapper.chapters({ ep_list = { + { id = 1, title = "已解锁", is_locked = false, pay_type = 1, is_pay = true }, + { id = 2, title = "未解锁", is_locked = true, pay_type = 0 }, +} }) +Assert.eq(chapters[1].vip, false) +Assert.eq(chapters[2].vip, true) + +local fetched = false +package.loaded["moonsource_bilimanga.client"] = { + imageIndexAsync = function() fetched = true end, +} +local Chapter = require("moonsource_bilimanga.chapter") +local reason +Chapter.materializeAsync( + { source_id = "bilimanga", stable_id = "1" }, + { uid = "9", vip = true }, + nil, + function(_path, err) reason = err end) +Stubs.flush() +Assert.eq(reason, "本章未购买") +Assert.is_false(fetched) + +package.loaded["moonsource_bilimanga.client"] = nil +package.loaded["moonsource_bilimanga.chapter"] = nil +package.loaded["json"] = { encode = Json.encode, decode = Json.decode } + +local sent +local reply +package.loaded["http.request"] = { + ok = function(code) return code and code >= 200 and code < 300 end, + request = function(opts, cb) + sent = opts + local job = { cancel = function() reply = nil end } + if reply then cb(reply.body, reply.err) end + return job + end, +} +local Client = require("moonsource_bilimanga.client") + +local function check(body) + reply = { body = { code = 200, body = body } } + local ok, err, account + Client.loginCheckAsync("SESSDATA=fixture", function(a, b, c) + ok, err, account = a, b, c + end) + return ok, err, account +end + +local ok, err = check(Json.encode({ code = -101, data = { isLogin = false } })) +Assert.eq(ok, false) +Assert.eq(err, "登录校验失败,请确认已经登录哔哩哔哩") +Assert.eq(sent.headers.Cookie, "SESSDATA=fixture") +Assert.eq(sent.url, "https://api.bilibili.com/x/web-interface/nav") + +ok, err, account = check(Json.encode({ code = 0, data = { isLogin = true, mid = 42 } })) +Assert.eq(ok, true) +Assert.is_nil(err) +Assert.eq(account.id, "42") + +local empty_ok, empty_err +Client.loginCheckAsync("", function(a, b) empty_ok, empty_err = a, b end) +Assert.eq(empty_ok, false) +Assert.eq(empty_err, "没有读到 Cookie") diff --git a/tests/bilimanga/store_spec.lua b/tests/bilimanga/store_spec.lua new file mode 100644 index 0000000..7f86b7c --- /dev/null +++ b/tests/bilimanga/store_spec.lua @@ -0,0 +1,44 @@ +--[[-- +书架列表和书城分类的字段形状。 + +@module tests.moonsource_bilimanga.store_spec +--]] + +local Assert = require("support.assert") +local Mapper = require("moonsource_bilimanga.mapper") + +local book = Mapper.book({ season_id = 25717, title = "示例", vertical_cover = "http://cover" }) +Assert.eq(book.stable_id, "25717") +Assert.eq(book.cover, "http://cover") + +local shelf = Mapper.rows({ code = 0, data = { + { comic_id = 1, title = "一" }, + { comic_id = 2, title = "二" }, +} }) +Assert.eq(#shelf, 2) +Assert.is_nil(Mapper.rows({ code = 0, msg = "坏了" })) + +local labels = Mapper.labels({ data = { + styles = { { id = 999, name = "热血" } }, + orders = { { id = 0, name = "人气推荐" }, { id = 1, name = "更新时间" } }, +} }) +local order, style = Mapper.storeChoice(nil, labels) +Assert.eq(order, 0) +Assert.eq(style, -1) +order, style = Mapper.storeChoice("1:999", labels) +Assert.eq(order, 1) +Assert.eq(style, 999) +order, style = Mapper.storeChoice("9:8", labels) +Assert.eq(order, 0) +Assert.eq(style, -1) + +local groups = Mapper.storeGroups(labels, 0, 999) +Assert.eq(#groups, 2) +Assert.eq(groups[1].chips[2].id, "1:999") +Assert.eq(groups[2].chips[1].id, "0:-1") +Assert.eq(groups[2].chips[2].id, "0:999") + +local books = Mapper.books({ { season_id = 29040, title = "分类" } }) +Assert.eq(#books, 1) +Assert.eq(books[1].stable_id, "29040") +Assert.is_nil(Mapper.books({ { title = "没有身份" } }))