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") return cfg.cookie or "" end local function makeHeaders(extra) local 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", ["Content-Type"] = "application/json", ["Referer"] = BASE .. "/", } local cookie = getCookie() if cookie and cookie ~= "" then headers.Cookie = cookie end if extra then for k, v in pairs(extra) do headers[k] = v end end return headers end local function twirpAsync(service, method, body, cb) local url = BASE .. "/twirp/" .. service .. "/" .. method .. "?" .. QUERY local state = { cancelled = false } local function finish(data, err) if state.cancelled then return end state.job = nil cb(data, err) end local job = Request.request({ url = url, method = "POST", body = JSON.encode(body or {}), headers = makeHeaders(), 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 local code = tonumber(res.code) if not Request.ok(code) then if code == 401 or code == 403 then local settings = require("utils.settings") 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 return end local ok, data = pcall(JSON.decode, res.body) if not ok or type(data) ~= "table" then finish(nil, _("响应无效")) return end local bad = apiCode(data) if bad then finish(nil, bad) return end finish(data) end) if not state.job then -- Request already completed synchronously (unlikely but possible) return { cancel = function() end } end state.job = job return { cancel = function() state.cancelled = true if state.job then state.job.cancel() end end, } end local function twirpAsyncSimple(service, method, body, cb) return twirpAsync(service, method, body, function(data, err) if err then cb(nil, err) else cb(data) end 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 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) 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 or wire) end) end function Client.comicDetailLiteAsync(comic_id, cb) return Client.comicDetailAsync(comic_id, cb) end function Client.imageIndexAsync(ep_id, cb) 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, age = 0, page = 1, page_size = 30, }, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end 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), }, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end -- ============================================================ -- Bookshelf 服务 -- ============================================================ 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) end) end function Client.listHistoryAsync(page_num, page_size, cb) return twirpAsync("bookshelf.v1.Bookshelf", "ListHistory", { page_num = page_num or 1, page_size = page_size or 20, type = 0, }, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end function Client.addHistoryAsync(comic_id, ep_id, cb) return twirpAsync("bookshelf.v1.Bookshelf", "AddHistory", { comic_id = tonumber(comic_id), ep_id = tonumber(ep_id), type = 1, from = "web", source = "web", }, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end function Client.addFavoriteAsync(comic_id, cb) return twirpAsync("bookshelf.v1.Bookshelf", "AddFavorite", { comic_id = tonumber(comic_id), type = 0, from = "web", source = "web", }, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end function Client.deleteFavoriteAsync(comic_id, cb) return twirpAsync("bookshelf.v1.Bookshelf", "DeleteFavorite", { comic_id = tonumber(comic_id), type = 0, from = "web", source = "web", }, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end -- ============================================================ -- User 服务 -- ============================================================ function Client.getUserInfoAsync(cb) return twirpAsync("user.v1.User", "GetInitInfo", {}, function(wire, err) if not wire then cb(nil, err); return end cb(wire) end) end function Client.checkLoginAsync(cb) return Client.getUserInfoAsync(function(wire, err) if not wire then cb(nil, err); return end if wire.user_info then cb(wire.user_info) else cb(nil, _("获取用户信息失败")) end end) 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 ~= "" end function Client.setCookie(cookie) local cfg = require("utils.settings").getSource("bilimanga") 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(nil) end -- 分页遍历 function Client.paginateAsync(fetchFn, cb) local all_items = {} local page = 1 local function fetchPage() fetchFn(page, function(result, err) if err then cb(nil, err) return end local items = result and result.list or result and result.items or {} if not items or #items == 0 then cb(all_items) return end for i = 1, #items do all_items[#all_items + 1] = items[i] end local has_more = result and result.has_more if not has_more or has_more == false then cb(all_items) return end page = page + 1 fetchPage() end) end fetchPage() end return Client