--[[-- Kmoe(mox.moe)HTTP 客户端。 书单 / 搜索走公开 JSON `data_list.php`,不带账号 Cookie;详情、卷列表、书架、收藏、下载带登录 Cookie。 需要登录的页面在未登录时 302 到 login.php;没做手机验证的账号取下载地址会 302 到 regphone.php。 请求一律不跟随跳转,跳转目标就是错误类型。 取下载地址要求 UA 与登录时逐字一致,否则 403(普通页面不查)。所以会话的 UA 跟 Cookie 一起保存: 密码登录用这里的固定电脑版 UA;浏览器授权和粘贴 Cookie 用那个浏览器自己的 UA。 @module moonsource_kmoe.client --]] local Mapper = require("moonsource_kmoe.mapper") local Request = require("http.request") local Text = require("utils.text") local _ = require("l10n").get("moonsource_kmoe") local SOURCE_ID = "kmoe" local BASE = "https://mox.moe" local UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" ---@class KmoeClient ---@field jar CookieJar|nil 登录会话;未登录为 nil ---@field ua string 这份会话登录时的 UA local Client = {} Client.__index = Client Client.BASE = BASE Client.ua = UA ---@param cookie string|nil 已保存的登录 Cookie ---@param ua string|nil 登录时的 UA;nil 为密码登录用的默认 UA ---@return KmoeClient function Client.new(cookie, ua) return setmetatable({ jar = require("http.cookie_jar").session(SOURCE_ID, cookie), ua = ua }, Client) end ---@return boolean function Client:loggedIn() return self.jar ~= nil end --- 需要登录却没登录(或登录已失效)时的错误。 ---@return string function Client:loginError() if not self.jar then return _("请先登录 Kmoe 账号") end return require("source.auth").expire(SOURCE_ID, _("Kmoe 登录已失效。打开「设置 → 书库 → 账号 → Kmoe」,重新登录。")) end --- 站内请求。body 非 nil 时 POST 表单。成功 cb(body, nil, res)。 ---@param path string 站内路径(/ 开头) ---@param opts { form: table|nil, auth: boolean|nil, jar: CookieJar|nil } ---@param cb fun(body: string|nil, err: string|nil, res: table|nil) ---@return { cancel: fun() } function Client:request(path, opts, cb) local jar = opts.jar or (opts.auth and self.jar or nil) local headers = { ["User-Agent"] = self.ua, ["Referer"] = BASE .. "/" } local function done(body, err, res) if body then cb(body, nil, res); return end local code = res and res.code or 0 local location = code >= 300 and code < 400 and Request.header(res, "Location") or "" if location:find("regphone", 1, true) then cb(nil, _("Kmoe 要求先验证手机号才能下载:在 Kmoe 网站「設置 → 帳號信息 → 手機驗證」完成验证,再回月读重新登录。"), res) elseif location:find("login", 1, true) then cb(nil, self:loginError(), res) elseif location ~= "" then cb(nil, _("Kmoe 返回了意外的跳转"), res) else cb(nil, err or _("网络请求失败"), res) end end local http = { headers = headers, jar = jar, timeout = require("http.timeout").net(1) } if opts.form then headers["Content-Type"] = "application/x-www-form-urlencoded" return Request.post(BASE .. path, Text.formEncode(opts.form), http, done) end return Request.get(BASE .. path, http, done) end ---@class KmoeListQuery ---@field s string 关键词,或 `CAT*<分类>` ---@field ["end"] string|nil 完結 / 連載 ---@field lang string|nil chn / jpn / eng ---@field by string|nil 排序 --- 书单一页(每页 21 部)。 ---@param query KmoeListQuery ---@param page integer ---@param cb fun(books: Book[]|nil, err: string|nil, more: boolean|nil) ---@return { cancel: fun() } function Client:listAsync(query, page, cb) local q = { k = "", s = query.s or "", ["end"] = query["end"] or "", lang = query.lang or "", blen = "", regn = "", by = query.by or "", color = "0", hd = "0", p = tostring(page), } return self:request("/data_list.php?" .. Text.formEncode(q), {}, function(body, err) if not body then cb(nil, err); return end cb(Mapper.list(body)) end) end --- 手机版详情页。登录时带 Cookie,页面里的 uin 用来判断登录是否还有效。 ---@param key string ---@param cb fun(detail: KmoeDetail|nil, err: string|nil) ---@return { cancel: fun() } function Client:detailAsync(key, cb) return self:request("/m/c/" .. key .. ".htm", { auth = true }, function(body, err) if not body then cb(nil, err); return end local detail = Mapper.detail(key, body) if not detail then cb(nil, _("Kmoe 漫画详情解析失败")); return end cb(detail) end) end --- 卷列表。匿名请求服务器回空列表,所以先看详情页是否按登录态渲染。 ---@param detail KmoeDetail ---@param cb fun(chapters: BookChapter[]|nil, err: string|nil) ---@return { cancel: fun() } function Client:volumesAsync(detail, cb) if not detail.logged_in then return require("source.base").defer(cb, nil, self:loginError()) end if not detail.hash then return require("source.base").defer(cb, nil, _("Kmoe 漫画详情解析失败")) end return self:request("/data_book.php?h=" .. detail.hash, { auth = true }, function(body, err) if not body then cb(nil, err); return end cb(Mapper.chapters(body, detail.bookid)) end) end --- 取一卷的文件地址。 ---@param origin string 目录里存的 getdownurl 路径 ---@param cb fun(url: string|nil, err: string|nil) ---@return { cancel: fun() } function Client:downUrlAsync(origin, cb) if not self.jar then return require("source.base").defer(cb, nil, self:loginError()) end return self:request(origin, { auth = true }, function(body, err, res) if res and res.code == 403 then cb(nil, _("Kmoe 拒绝下载:登录时的浏览器和现在不一致。改用邮箱密码重新登录;浏览器授权要用新版扩展,粘贴 Cookie 要同时填浏览器 UA。")) return end if not body then cb(nil, err); return end local url, parse_err = Mapper.downUrl(body) cb(url and Text.absoluteUrl(BASE .. "/", url) or nil, parse_err) end) end --- 书架快照:「訂閱收藏」页里打了收藏的书。没有封面的新书顺序补拉详情页拿封面和简介,补拉失败只少封面。 ---@param cb fun(books: Book[]|nil, err: string|nil, meta: { incomplete: boolean }|nil) ---@return { cancel: fun() } function Client:shelfSyncAsync(cb) local handle = {} if not self.jar then return require("source.base").defer(cb, nil, self:loginError()) end handle.inner = self:request("/myfollow.php", { auth = true }, function(body, err) if handle.cancelled then return end if not body then cb(nil, err); return end local rows, parse_err, paged = Mapper.shelf(body) if not rows then cb(nil, parse_err); return end local BookDB = require("book.books_db") local books, pos = {}, 0 for i, row in ipairs(rows) do books[i] = row.book end local function step() if handle.cancelled then return end pos = pos + 1 local book = books[pos] if not book then cb(books, nil, { incomplete = paged }); return end local known = BookDB.get(SOURCE_ID, book.stable_id) if known and known.cover then return step() end handle.inner = self:detailAsync(book.stable_id, function(detail, detail_err) if detail then book.cover, book.intro, book.category = detail.book.cover, detail.book.intro, detail.book.category else require("utils.log").warn("kmoe shelf cover backfill failed", book.stable_id, detail_err) end step() end) end step() end) function handle.cancel() handle.cancelled = true if handle.inner then handle.inner.cancel() end end return handle end --- 收藏 / 取消收藏。接口要数字书号,先读详情页;成功回包里有 `c101`。 ---@param key string ---@param act string "1" 收藏 / "0" 取消 ---@param cb fun(ok: boolean|nil, err: string|nil) ---@return { cancel: fun() } function Client:followAsync(key, act, cb) local handle = {} handle.inner = self:detailAsync(key, function(detail, err) if handle.cancelled then return end if not detail then cb(nil, err); return end if not detail.logged_in then cb(nil, self:loginError()); return end handle.inner = self:request("/book_follow.php", { auth = true, form = { follow_bookid = detail.bookid, follow_type = "0", follow_act = act }, }, function(body, follow_err) if handle.cancelled then return end if not body then cb(nil, follow_err); return end if not body:find('"c101"', 1, true) then cb(nil, _("Kmoe 没有确认收藏操作")); return end cb(true) end) end) function handle.cancel() handle.cancelled = true if handle.inner then handle.inner.cancel() end end return handle end function Client:addToShelfAsync(key, cb) return self:followAsync(key, "1", cb) end function Client:removeFromShelfAsync(key, cb) return self:followAsync(key, "0", cb) end --- 校验一份 Cookie:带它打开「我的」页,拿个人主页链接 `/u//` 里的数字账号。 ---@param cookie string ---@param cb fun(ok: boolean, err: string|nil, account: { id: string }|nil) ---@return { cancel: fun() } function Client.accountAsync(cookie, cb) local client = setmetatable({ jar = require("http.cookie_jar").new():seed(cookie) }, Client) return client:request("/my.php", { auth = true }, function(body, err, res) local uin = body and body:match("/u/(%d+)/") if uin then cb(true, nil, { id = uin }); return end local code = res and res.code or 0 if body or (code >= 300 and code < 400) then cb(false, _("Kmoe 登录无效,请重新登录")); return end cb(false, err) end) end --- 账号密码登录,成功回登录 Cookie 串(还要经 accountAsync 校验)。密码不落盘。 ---@param email string ---@param password string ---@param cb fun(cookie: string|nil, err: string|nil) ---@return { cancel: fun() } function Client.loginAsync(email, password, cb) local client = setmetatable({}, Client) return client:request("/login_act.php", { form = { email = email, passwd = password } }, function(body, err, res) if not body then cb(nil, err); return end local ok, wire = pcall(require("json").decode, body) if not ok or type(wire) ~= "table" then cb(nil, _("Kmoe 登录响应无效")); return end if wire.msgid ~= "m100" then cb(nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("登录失败")) return end local cookie = require("source.cookie_login").parse("", Request.headerAll(res, "Set-Cookie")) if cookie == "" then cb(nil, _("Kmoe 登录成功但没有返回 Cookie")); return end cb(cookie) end) end return Client