✨ 初始提交:月读第三方书源插件集合

每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。

Co-authored-by: Copilot <[email protected]>
This commit is contained in:
GarfieldandCopilot committed 2026-11-16 12:08:03 +08:00
commit b41273ef9b
35 files changed
+4665

No files matched your search

@@ -0,0 +1,15 @@
--[[--
书源元信息。
@module moonsource_kuaikan._meta
--]]
local _ = require("l10n").get("moonsource_kuaikan")
return {
id = "ext.kuaikan",
name = _("快看漫画"),
type = "chapter",
description = _("快看漫画在线阅读"),
abilities = { _("微信扫码登录"), _("密码登录"), _("短信登录"), _("书架同步"), _("阅读进度同步"), _("搜索与发现"), _("话题页评论(首话)"), _("章节评论"), _("缓存章节") },
}
@@ -0,0 +1,162 @@
--[[--
快看漫画章节图片下载与 CBZ 打包。
@module moonsource_kuaikan.chapter
--]]
local Cbz = require("source.cbz")
local Client = require("moonsource_kuaikan.client")
local Image = require("utils.image")
local Paths = require("utils.paths")
local _ = require("l10n").get("moonsource_kuaikan")
local Chapter = {}
---@param identity BookIdentity
---@param chapter BookChapter
---@return string
function Chapter.archivePath(identity, chapter)
return Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/" .. chapter.uid .. ".cbz"
end
---@param identity BookIdentity
---@param chapter BookChapter
---@return string|nil
function Chapter.existing(identity, chapter)
local path = Chapter.archivePath(identity, chapter)
return Cbz.ready(path) and path or nil
end
---@param identity BookIdentity
---@param chapter BookChapter
---@param on_progress fun(done: integer, total: integer)|nil
---@param cb fun(path: string|nil, err: string|nil)
---@return { cancel: fun() }
function Chapter.materializeAsync(identity, chapter, on_progress, cb)
Paths.ensureBookWork(identity.stable_id, identity.source_id)
local archive_path = Chapter.archivePath(identity, chapter)
---@type { cancelled: boolean, active: CancelHandle|nil, writer: ArchiverWriter|nil }
local state = { cancelled = false, active = nil, writer = nil }
if Cbz.ready(archive_path) then
require("ui/uimanager"):nextTick(require("ui.guard").wrap("kuaikan callback", function()
if not state.cancelled then cb(archive_path) end
end))
return { cancel = function() state.cancelled = true end }
end
local fetched = false
local image_job = Client.imagesAsync(chapter.uid, function(urls, err)
fetched = true
state.active = nil
if state.cancelled then return end
if not urls then cb(nil, err); return end
local image_dir = archive_path:gsub("%.cbz$", "")
Paths.ensureDir(image_dir)
local paths, current = {}, 1
for i, url in ipairs(urls) do
paths[i] = image_dir .. "/" .. string.format("%04d%s", i, Image.suffix(url) or ".jpg")
end
local function nextImage()
if state.cancelled then return end
local url = urls[current]
if not url then
Cbz.build(paths, archive_path, state, cb)
return
end
local path = paths[current]
if Image.ok(path) then
if on_progress then on_progress(current, #urls) end
current = current + 1
require("ui/uimanager"):nextTick(require("ui.guard").wrap("kuaikan image", nextImage))
return
end
local downloaded = false
local handle = require("http.request").download({
url = url,
timeout = require("http.timeout").net(3),
max_bytes = 32 * 1024 * 1024,
}, path, function(ok, download_err)
downloaded = true
state.active = nil
if state.cancelled then return end
if not ok or not Image.ok(path) then
os.remove(path)
cb(nil, download_err and tostring(download_err) or _("章节图片解析失败"))
return
end
if on_progress then on_progress(current, #urls) end
current = current + 1
require("ui/uimanager"):nextTick(require("ui.guard").wrap("kuaikan image", nextImage))
end)
if not downloaded then state.active = handle end
end
nextImage()
end)
if not fetched then state.active = image_job end
return { cancel = function()
if state.cancelled then return end
state.cancelled = true
if state.active then state.active.cancel() end
if state.writer then state.writer:close() end
os.remove(archive_path .. ".part")
end }
end
---@param identity BookIdentity
---@param toc BookChapter[]
---@param from_idx integer
---@param count integer
---@param ops { progress: fun(done: integer, total: integer)|nil, interval_seconds: number|nil }|nil
---@param cb fun(cached: integer, total: integer, failed: integer, err: any)|nil
---@return { cancel: fun() }
function Chapter.prefetchAsync(identity, toc, from_idx, count, ops, cb)
ops = ops or {}
local cancelled, active = false, nil
local cached_count, failed_count, last_error = 0, 0, nil
local chapters = {}
for idx = from_idx + 1, math.min(#toc, from_idx + count) do
chapters[#chapters + 1] = toc[idx]
end
local pos = 1
local interval = ops.interval_seconds or 0
local UIManager = require("ui/uimanager")
local function step()
if cancelled then return end
local chapter = chapters[pos]
local chapter_idx = from_idx + pos
pos = pos + 1
if not chapter then
if cb then cb(cached_count, #chapters, failed_count, last_error) end
return
end
active = Chapter.materializeAsync(identity, chapter, nil, function(path, err)
active = nil
if cancelled then return end
if path and not require("book.chapters_db").upsert({
path = path, source_id = identity.source_id,
stable_id = identity.stable_id, chapter_idx = chapter_idx,
}) then
path, err = nil, _("书籍信息保存失败")
end
if path then cached_count = cached_count + 1
else
failed_count = failed_count + 1
last_error = err or last_error
end
if ops.progress then ops.progress(cached_count + failed_count, #chapters) end
if interval > 0 then
UIManager:scheduleIn(interval, require("ui.guard").wrap("kuaikan step", step))
else
UIManager:nextTick(require("ui.guard").wrap("kuaikan step", step))
end
end)
end
UIManager:nextTick(require("ui.guard").wrap("kuaikan step", step))
return { cancel = function()
cancelled = true
if active then active.cancel() end
end }
end
return Chapter
@@ -0,0 +1,584 @@
--[[--
快看漫画网页接口。
搜索和首页是 JSON。目录在话题页 HTML 里。页图要先拿挑战接口的 `kk_s_t`,
再按页面脚本的算法算出 `answer`。公共请求不携带账号 Cookie。
@module moonsource_kuaikan.client
--]]
local JSON = require("json")
local Mapper = require("moonsource_kuaikan.mapper")
local Page = require("moonsource_kuaikan.page")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kuaikan")
local Client = {}
Client.login_revision = 0
local HOST = "https://www.kuaikanmanhua.com"
Client.LOGIN_URL = HOST .. "/webs/loginh"
Client.ACCOUNT_URL = HOST .. "/v2/pweb/user_info/get"
local ALPHA = "BtMTUlesLXPIFjfcbGYWyqQxROzAHNDCwmiKpdhvkSrEungZoJaV"
local PREFIX = "20200820"
---@return table
local function opts(extra)
local out = { timeout = require("http.timeout").net(1) }
if extra then
for key, value in pairs(extra) do out[key] = value end
end
return out
end
---@param res table|nil
---@return string|nil
local function cookieOf(res)
local lines = {}
if Request.headerAll then
lines = Request.headerAll(res, "set-cookie") or {}
else
local line = Request.header(res, "set-cookie")
if type(line) == "string" then lines = { line } end
end
for _idx, line in ipairs(lines) do
local value = type(line) == "string" and line:match("kk_s_t=([^;]+)") or nil
if value and value ~= "" then return value end
end
return nil
end
--- 页面 `getSign` 的结果。indexes 是 16 个 0..15 的下标,缺省用随机数。
---@param cookie string
---@param indexes integer[]|nil
---@return string
function Client.answer(cookie, indexes)
local rand = {}
for slot = 1, 16 do
local index = indexes and indexes[slot] or math.random(0, 15)
rand[#rand + 1] = tostring(index) .. ALPHA:sub(index + 1, index + 1)
end
local rand_s = table.concat(rand)
local body = PREFIX .. rand_s .. cookie
if #body % 2 ~= 0 then body = body .. "0" end
local mid = #body / 2
local slice = body:sub(mid - 16 + 1, mid + 16)
return Text.base64Encode(table.concat({ PREFIX, rand_s, cookie, slice }, "_"))
end
--- 登录态在 settings.cookie。页图还要拼上挑战接口的 kk_s_t。
---@param headers table|nil
---@return table|nil
local function withCookie(headers, cookie)
if cookie == nil then cookie = require("utils.settings").getSource("ext.kuaikan").cookie end
local saved = type(cookie) == "string" and cookie or ""
if saved == "" then return headers end
headers = headers or {}
if type(headers.Cookie) == "string" and headers.Cookie ~= "" then
local pairs = {}
for pair in saved:gmatch("[^;]+") do
if pair:match("^%s*([^=%s]+)%s*=") ~= "kk_s_t" then
pairs[#pairs + 1] = Text.trim(pair)
end
end
saved = table.concat(pairs, "; ")
if saved ~= "" then headers.Cookie = saved .. "; " .. headers.Cookie end
else
headers.Cookie = saved
end
return headers
end
---@param url string
---@param headers table|nil
---@param cb fun(raw: string|nil, err: string|nil, res: table|nil)
---@return HttpJob
local function get(url, headers, cb, uncached)
headers = headers or {}
-- 默认 UA 会被收藏接口挂住,网页 UA 才能回包。
if not headers["User-Agent"] then headers["User-Agent"] = "Mozilla/5.0" end
headers["User-Agent-PC"] = "PCKuaikan/1.0.0/100000(Mac;10.15.7;Chrome;pckuaikan;1800*2880;564)"
return Request.get(url, opts({ headers = headers, cache_ttl = (uncached or headers.Cookie) and 0 or nil }), cb)
end
--- 登录会话只访问官网和微信开放平台;第三方域绝不附带快看 Cookie。
---@param url string
---@param cookie string|nil
---@param cb fun(raw: string|nil, err: any, res: table|nil)
---@param fields table|nil POST 表单;nil 为 GET
---@return HttpJob
function Client.loginRequestAsync(url, cookie, cb, fields, method)
method = method or (fields and "POST" or "GET")
local official = url:sub(1, #HOST + 1) == HOST .. "/"
if not official and not url:match("^https://open%.weixin%.qq%.com/")
and not url:match("^https://long%.open%.weixin%.qq%.com/") then
return require("source.base").defer(cb, nil, _("登录响应无效"))
end
local headers = {
["User-Agent"] = "Mozilla/5.0",
["User-Agent-PC"] = "PCKuaikan/1.0.0/100000(Mac;10.15.7;Chrome;pckuaikan;1800*2880;564)",
Referer = official and Client.LOGIN_URL or "https://open.weixin.qq.com/",
}
if official and cookie and cookie ~= "" then headers.Cookie = cookie end
local options = opts({ headers = headers, cache_ttl = 0,
timeout = math.min(require("http.timeout").net(1), 30) })
local callback = require("ui.guard").wrap("kuaikan login", cb)
if method == "DELETE" and official then
options.url, options.method, options.body = url, method, ""
return Request.request(options, function(res, err)
callback(not err and res and res.body or nil, err, res)
end)
end
if method ~= "GET" and method ~= "POST" then
return require("source.base").defer(cb, nil, _("响应无效"))
end
if fields then
if not official then return require("source.base").defer(cb, nil, _("登录响应无效")) end
options.content_type = "application/x-www-form-urlencoded"
return Request.post(url, Text.formEncode(fields), options, callback)
end
return Request.get(url, options, callback)
end
--- 账号校验响应;登录失效与临时网络错误分开。
---@param raw string|nil
---@param err any
---@param res table|nil
---@return { user_id: string }|nil
---@return string|nil
---@return boolean|nil
function Client.accountResponse(raw, err, res)
local status = res and tonumber(res.code)
local location = Request.header(res, "Location")
if status == 401 or (status and status >= 300 and status < 400
and type(location) == "string"
and (location == "/webs/loginh" or location:sub(1, #"/webs/loginh?") == "/webs/loginh?"
or location == Client.LOGIN_URL or location:sub(1, #Client.LOGIN_URL + 1) == Client.LOGIN_URL .. "?")) then
return nil, _("快看登录已失效,请重新登录"), true
end
if not raw or raw == "" or err then return nil, err and tostring(err) or _("请求失败") end
local ok, wire = pcall(JSON.decode, raw)
if not ok then return nil, _("登录响应无效") end
local account, reason = Mapper.account(wire)
if reason == "unauthorized" then return nil, _("快看登录已失效,请重新登录"), true end
if not account then return nil, _("登录响应无效") end
return account
end
---@param keyword string
---@param cb fun(books: Book[]|nil, err: string|nil)
---@return HttpJob
function Client.searchAsync(keyword, cb)
local url = HOST .. "/search/web/complex?f=3&q=" .. Text.urlEncode(keyword)
return get(url, nil, function(raw, err)
if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok then cb(nil, _("请求失败")); return end
local books = Mapper.search(wire)
if not books then cb(nil, _("请求失败")); return end
cb(books)
end)
end
---@param cb fun(books: Book[]|nil, err: string|nil)
---@param cookie string|nil 本轮已校验的 Cookie;缺省取当前配置
---@return { cancel: fun() }
function Client.favAsync(cb, cookie)
if cookie == nil then cookie = require("utils.settings").getSource("ext.kuaikan").cookie or "" end
local cancelled, active = false, nil
local offset, collected, seen = 0, {}, {}
local function nextPage()
local pending = true
local job = get(HOST .. "/v2/pweb/fav/topics?since=" .. offset .. "&limit=20",
withCookie({ Referer = HOST .. "/webs/booklist" }, cookie), function(raw, err)
pending, active = false, nil
if cancelled then return end
if not raw or raw == "" or err then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok then cb(nil, _("响应无效")); return end
local books, total = Mapper.fav(wire)
if not books or not total or offset + #books > total or (#books == 0 and offset < total) then
cb(nil, _("响应无效")); return
end
local added = 0
for _index, book in ipairs(books) do
if not seen[book.stable_id] then
seen[book.stable_id] = true
collected[#collected + 1] = book
added = added + 1
end
end
if #books > 0 and added == 0 then cb(nil, _("响应无效")); return end
offset = offset + #books
if offset >= total then cb(collected); return end
nextPage()
end, true)
if pending then active = job end
end
nextPage()
return { cancel = function()
cancelled = true
if active then active.cancel() end
end }
end
--- 有稳定账号身份的登录态默认同步,真实有效性由请求前的账号校验确认。
---@return boolean
function Client.hasAccount()
local cfg = require("utils.settings").getSource("ext.kuaikan")
return type(cfg.cookie) == "string" and cfg.cookie ~= ""
and type(cfg.user_id) == "string" and cfg.user_id ~= ""
end
---@class KuaikanSync
---@field cookie string
---@field previous_cookie string|nil
---@field user_id string|nil
---@field revision integer
---@field writing boolean
---@field cancelled boolean|nil
---@field job CancelHandle|nil
---@field push_error string|nil
local Sync = {}
Sync.__index = Sync
---@param writing boolean|nil
---@return KuaikanSync
function Client.newSync(writing)
local cfg = require("utils.settings").getSource("ext.kuaikan")
return setmetatable({
cookie = cfg.cookie or "", previous_cookie = cfg.cookie, user_id = cfg.user_id,
revision = Client.login_revision, writing = writing == true,
}, Sync)
end
---@return boolean
function Sync:current()
local cfg = require("utils.settings").getSource("ext.kuaikan")
return not self.cancelled and self.revision == Client.login_revision
and cfg.cookie == self.previous_cookie and cfg.user_id == self.user_id
and (not self.writing or self.user_id ~= nil)
end
function Sync:cancel()
self.cancelled = true
if self.job then self.job:cancel(); self.job = nil end
end
---@param path string
---@param cb fun(raw: string|nil, err: any, res: table|nil)
---@param fields table|nil
---@param method string|nil
---@param anonymous boolean|nil
function Sync:request(path, cb, fields, method, anonymous)
if not self:current() then cb(nil, _("登录状态已变化,请重试")); return end
local pending = true
local job = Client.loginRequestAsync(HOST .. path, anonymous and "" or self.cookie, function(raw, err, res)
pending, self.job = false, nil
if self.cancelled then return end
if not self:current() then cb(nil, _("登录状态已变化,请重试")); return end
cb(raw, err, res)
end, fields, method)
if pending then self.job = job end
end
---@param cb fun(account: table|nil, err: string|nil)
function Sync:checkAsync(cb)
if not require("ui/network/manager"):isConnected() then
return require("source.base").defer(cb, nil, _("网络不可用,请先连接 Wi-Fi"))
end
self:request("/v2/pweb/user_info/get", function(raw, err, res)
local account, reason, expired = Client.accountResponse(raw, err, res)
if not account then
if expired then require("source.auth").expire("ext.kuaikan", reason) end
cb(nil, reason)
elseif self.user_id and tostring(self.user_id) ~= account.user_id then
cb(nil, _("登录状态已变化,请重试"))
else
require("source.auth").ok("ext.kuaikan")
cb(account)
end
end)
return self
end
---@param cb fun(books: Book[]|nil, err: string|nil)
---@return KuaikanSync
function Sync:shelfSyncAsync(cb)
if not self:current() then cb(nil, _("登录状态已变化,请重试")); return self end
local pending = true
local job = Client.favAsync(function(books, err)
pending, self.job = false, nil
if self.cancelled then return end
if not self:current() then cb(nil, _("登录状态已变化,请重试")); return end
cb(books, err)
end, self.cookie)
if pending then self.job = job end
return self
end
---@param raw string|nil
---@param err any
---@return table|nil
---@return string|nil
local function syncResponse(raw, err)
if err or not raw or raw == "" then return nil, err and tostring(err) or _("请求失败") end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then return nil, _("响应无效") end
if tonumber(wire.code) ~= 200 then
return nil, type(wire.message) == "string" and wire.message ~= "" and wire.message or _("请求失败")
end
return wire
end
---@param stable_id string
---@param adding boolean
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return KuaikanSync
function Sync:changeShelfAsync(stable_id, adding, cb)
local function finish(ok, err)
if not ok then self.push_error = self.push_error or err or _("请求失败") end
cb(ok, err)
end
if not self.writing then finish(nil, _("登录状态已变化,请重试")); return self end
self:request("/v1/aegis/api/web/challenge?callback=callback_1", function(raw, err, res)
local challenge = not err and raw and cookieOf(res)
if not challenge then finish(nil, err and tostring(err) or _("响应无效")); return end
self.cookie = withCookie({ Cookie = "kk_s_t=" .. challenge }, self.cookie).Cookie
local path = "/web/topic/" .. Text.urlEncode(stable_id) .. "/fav?answer=" .. Text.urlEncode(Client.answer(challenge))
self:request(path, function(body, write_err)
local wire, reason = syncResponse(body, write_err)
if not wire then finish(nil, reason); return end
self:shelfSyncAsync(function(books, read_err)
if not books then finish(nil, read_err); return end
local found = false
for _index, book in ipairs(books) do
if book.stable_id == stable_id then found = true; break end
end
if found ~= adding then finish(nil, _("快看收藏变更尚未确认")); return end
finish(true)
end)
end, adding and {} or nil, adding and "POST" or "DELETE")
end, nil, nil, true)
return self
end
function Sync:addToShelfAsync(stable_id, cb)
return self:changeShelfAsync(stable_id, true, cb)
end
function Sync:removeFromShelfAsync(stable_id, cb)
return self:changeShelfAsync(stable_id, false, cb)
end
--- history.read_count 是已读话数,不是章内图片数。
---@param stable_id string
---@param cb fun(comic_id: string|nil, err: string|nil)
---@return KuaikanSync
function Sync:historyAsync(stable_id, cb)
local offset, seen = 0, {}
local function nextPage()
self:request("/v2/pweb/read/history/list?since=" .. offset .. "&limit=20", function(raw, err)
local wire, reason = syncResponse(raw, err)
if not wire then cb(nil, reason); return end
local data = wire.data
local rows = type(data) == "table" and data.topics
local total = type(data) == "table" and data.total
if type(rows) ~= "table" or type(total) ~= "number" or total < 0 or total % 1 ~= 0
or offset + #rows > total or #rows == 0 and offset < total then
cb(nil, _("响应无效")); return
end
local added = 0
for _index, row in ipairs(rows) do
if type(row) ~= "table" or row.topic_id == nil or row.comic_id == nil then
cb(nil, _("响应无效")); return
end
local key = tostring(row.topic_id)
if not seen[key] then seen[key], added = true, added + 1 end
if key == stable_id then cb(tostring(row.comic_id)); return end
end
if #rows > 0 and added == 0 then cb(nil, _("响应无效")); return end
offset = offset + #rows
if offset >= total then cb(nil); return end
nextPage()
end)
end
nextPage()
return self
end
---@param record table
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return KuaikanSync
function Sync:reportProgressAsync(record, cb)
if not self.writing then cb(nil, _("登录状态已变化,请重试")); return self end
self:request("/v2/pweb/read/history/report", function(raw, err)
local wire, reason = syncResponse(raw, err)
if not wire then cb(nil, reason); return end
self:historyAsync(tostring(record.topic_id), function(comic_id, read_err)
if read_err then cb(nil, read_err)
elseif comic_id ~= tostring(record.comic_id) then cb(nil, _("快看进度变更尚未确认"))
else cb(true) end
end)
end, { view_rate = JSON.encode({ record }) })
return self
end
function Client.homeAsync(cb)
return get(HOST .. "/v2/pweb/home", nil, function(raw, err)
if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok then cb(nil, _("请求失败")); return end
local books = Mapper.home(wire)
if not books then cb(nil, _("请求失败")); return end
cb(books)
end)
end
---@param node string
---@param page integer
---@param cb fun(books: Book[]|nil, err: string|nil, more: boolean|nil, groups: StoreChipGroup[]|nil)
function Client.storeAsync(node, page, cb)
local tag, region, pays, state, sort = Mapper.storeNode(node):match("^(%d+):(%d+):(%d+):(%d+):(%d+)$")
local url = HOST .. "/search/mini/topic/multi_filter?page=" .. page
.. "&size=48&tag_id=" .. tag .. "&label_dimension_origin=" .. region
.. "&pay_status=" .. pays .. "&update_status=" .. state .. "&sort=" .. sort
return get(url, nil, function(raw, err)
if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok then cb(nil, _("响应无效")); return end
local books, groups, more = Mapper.store(wire, node, page)
if not books then cb(nil, _("响应无效")); return end
cb(books, nil, more, groups)
end)
end
---@param stable_id string
---@param cb fun(page: table|nil, err: string|nil)
---@return HttpJob
function Client.topicAsync(stable_id, cb)
local url = HOST .. "/web/topic/" .. Text.urlEncode(stable_id) .. "/"
return get(url, { Referer = HOST .. "/" }, function(raw, err)
if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end
local page = Page.topic(raw)
if not page then cb(nil, _("漫画目录为空")); return end
cb(page)
end)
end
--- 一话的页图。锁定的话返回「本章未购买」。
---@param comic_id string
---@param cb fun(urls: string[]|nil, err: string|nil)
---@return HttpJob
function Client.imagesAsync(comic_id, cb)
local state = { cancelled = false, job = nil }
local cfg = require("utils.settings").getSource("ext.kuaikan")
local saved_cookie, saved_id, logged_in = cfg.cookie or "", cfg.user_id, cfg.logged_in == true
local challenged = false
local challenge = get(HOST .. "/v1/aegis/api/web/challenge?callback=callback_1", nil, function(_body, err, res)
challenged = true
if state.cancelled then return end
state.job = nil
local cookie = cookieOf(res)
if not cookie then cb(nil, err and tostring(err) or _("请求失败")); return end
local answer = Client.answer(cookie)
local url = HOST .. "/v2/pweb/comic/" .. comic_id .. "?source=&answer=" .. Text.urlEncode(answer)
local loaded = false
local image_job = get(url, withCookie({
Cookie = "kk_s_t=" .. cookie,
Referer = HOST .. "/webs/comic-next/" .. comic_id,
width = "564",
}, saved_cookie), function(raw, image_err)
loaded = true
if state.cancelled then return end
state.job = nil
if not raw or raw == "" then cb(nil, image_err and tostring(image_err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok then cb(nil, _("请求失败")); return end
local urls, locked = Mapper.images(wire)
if locked == "locked" then
if not logged_in then cb(nil, _("本章未购买")); return end
local checked = false
local account_job = Client.loginRequestAsync(Client.ACCOUNT_URL, saved_cookie, function(account_raw, account_err, account_res)
checked = true
if state.cancelled then return end
state.job = nil
local account, reason, expired = Client.accountResponse(account_raw, account_err, account_res)
if expired then
local current = require("utils.settings").getSource("ext.kuaikan")
if current.cookie == saved_cookie and current.user_id == saved_id then
require("source.auth").expire("ext.kuaikan", reason)
else
reason = _("登录状态已变化,请重试")
end
end
cb(nil, account and _("本章未购买") or reason)
end)
if not checked then state.job = account_job end
return
end
if not urls then cb(nil, _("章节图片解析失败")); return end
cb(urls)
end)
if not loaded then state.job = image_job end
end, true)
if not challenged then state.job = challenge end
return { cancel = function()
state.cancelled = true
if state.job then state.job.cancel() end
end }
end
---@param comic_id string
---@param offset integer
---@param cb fun(items: table[]|nil, err: string|nil, pages: integer|nil, pagination: {total: integer, max_idx: integer, more: boolean}|nil)
function Client.commentPageAsync(comic_id, offset, cb)
local url = HOST .. "/v2/comments/comic/" .. Text.urlEncode(comic_id)
.. "/order/score?offset=" .. offset .. "&limit=50&total=true"
return get(url, { Referer = HOST .. "/webs/comic-next/" .. Text.urlEncode(comic_id) }, function(raw, err)
if not raw or raw == "" then cb(nil, err and tostring(err) or _("请求失败")); return end
local ok, wire = pcall(JSON.decode, raw)
if not ok then cb(nil, _("响应无效")); return end
local items, total = Mapper.comments(wire)
if not items or not total then cb(nil, _("快看漫画书评加载失败")); return end
local next_idx = offset + #wire.data.comments
cb(items, nil, math.max(1, math.ceil(total / 50)), {
total = total, max_idx = next_idx, more = #wire.data.comments > 0 and next_idx < total,
})
end)
end
--- 话题页评论。目标是话题信息里的 first_comic_id,按热度取第一页 50 条。
---@param stable_id string
---@param cb fun(items: table[]|nil, err: string|nil, pages: integer|nil)
---@return { cancel: fun() }
function Client.commentsAsync(stable_id, cb)
local state = { cancelled = false, job = nil }
local loaded = false
local topic_job = Client.topicAsync(stable_id, function(page, err)
loaded = true
if state.cancelled then return end
state.job = nil
if not page then cb(nil, err or _("快看漫画书评加载失败")); return end
local info = page.info
local comic_id = type(info) == "table" and info.first_comic_id or nil
local id = (type(comic_id) == "number" or type(comic_id) == "string") and tostring(comic_id) or ""
if id == "" or id == "0" then cb(nil, _("快看漫画书评加载失败")); return end
local fetched = false
local comment_job = Client.commentPageAsync(id, 0, function(items, get_err, pages)
fetched = true
if state.cancelled then return end
state.job = nil
cb(items, get_err, pages)
end)
if not fetched then state.job = comment_job end
end)
if not loaded then state.job = topic_job end
return { cancel = function()
state.cancelled = true
if state.job and state.job.cancel then state.job.cancel() end
end }
end
return Client
@@ -0,0 +1,74 @@
return {
["在章末显示本章讨论,不是段落评论"] = "Show this chapter's discussion at the end, not paragraph comments.",
["密码登录"] = "Password sign-in",
["短信登录"] = "SMS sign-in",
["快看密码登录"] = "Kuaikan password sign-in",
["快看短信登录"] = "Kuaikan SMS sign-in",
["快看安全验证"] = "Kuaikan security verification",
["请输入密码"] = "Enter your password.",
["登录前请阅读并同意快看用户协议和隐私协议"] = "Before signing in, read and agree to the Kuaikan terms and privacy policy.",
["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "Scan with a phone on the same Wi-Fi to complete security verification. Enter your phone number, password and SMS code only on the device.",
["请完成下方安全验证"] = "Complete the security verification below.",
["验证已提交,请回到设备查看结果。"] = "Verification submitted. Return to the device to see the result.",
["验证或登录失败,请回到设备查看并重试"] = "Verification or sign-in failed. Return to the device for details and try again.",
["滑块加载失败,请检查网络后刷新网页"] = "Could not load the slider. Check your connection and refresh the page.",
["快看漫画账号"] = "Kuaikan account",
["快看登录 Cookie"] = "Kuaikan login Cookie",
["在快看官网登录后,复制请求标头里的完整 Cookie"] = "Sign in on the official Kuaikan website and copy the complete Cookie request header.",
["快看登录已失效,请重新登录"] = "Your Kuaikan session has expired. Please sign in again.",
["旧快看账号身份无法确认,请先退出旧登录后重试"] = "The previous Kuaikan account could not be identified. Sign out of the old session before retrying.",
["快看收藏变更尚未确认"] = "The Kuaikan favourite change could not be confirmed.",
["快看进度变更尚未确认"] = "The Kuaikan progress change could not be confirmed.",
["快看云端章节不在当前目录中"] = "The cloud chapter is not in the current Kuaikan table of contents.",
["阅读进度同步"] = "Reading progress sync",
["请先退出旧快看账号,再登录其他账号"] = "Sign out of the previous Kuaikan account before signing in to another account.",
["确定退出快看账号?"] = "Sign out of Kuaikan?",
["地区"] = "Region",
["国漫"] = "Chinese comics",
["韩漫"] = "Korean comics",
["日漫"] = "Japanese comics",
["VIP抢先看"] = "VIP early access",
["最火热"] = "Most popular",
["新上架"] = "New arrivals",
["话题页评论(首话)"] = "Topic comments (first episode)",
["国际区号"] = "Country calling code",
["请输入有效的手机号和国际区号"] = "Enter a valid phone number and country calling code.",
["请稍后再获取验证码"] = "Please wait before requesting another code.",
["验证码已发送"] = "Verification code sent",
["正在处理,请稍候"] = "Processing, please wait.",
["请先获取该手机号的验证码,再填写验证码登录"] = "Request a code for this phone number, then enter it to sign in.",
["登录状态已变化,请重试"] = "The login session changed. Please retry.",
["登录响应无效"] = "Invalid sign-in response",
["章节评论"] = "Chapter comments",
["快看漫画"] = "Kuaikan",
["快看漫画在线阅读"] = "Kuaikan comics",
["快看漫画书评加载失败"] = "Could not load Kuaikan reviews",
["获取验证码"] = "Get code",
["用微信扫一扫"] = "Scan with WeChat",
["本章未购买"] = "This chapter has not been purchased",
["价格"] = "Price",
["免费"] = "Free",
["付费"] = "Paid",
["连载中"] = "Ongoing",
["已完结"] = "Completed",
["验证已过期,请重新发起验证"] = "Verification expired. Please start again",
["重新获取二维码"] = "Get a new QR code",
["微信扫码登录"] = "WeChat QR login",
["正在准备漫画…"] = "Preparing comic…",
["正在获取二维码…"] = "Fetching QR code…",
["漫画目录为空"] = "Comic chapter list is empty",
["章节目录保存失败"] = "Failed to save chapter list",
["章节图片解析失败"] = "Failed to parse chapter images",
["已在微信中拒绝登录"] = "Login declined in WeChat",
["手机号"] = "Phone number",
["同意并继续"] = "Agree and continue",
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "Cannot open remote verification. Connect to Wi-Fi and enable Remote management first.",
["验证已取消"] = "Verification cancelled",
["验证凭据无效"] = "Invalid verification proof",
["正在提交验证…"] = "Submitting verification…",
["验证失败,请重新验证"] = "Verification failed. Please try again",
["重试"] = "Retry",
["书架同步"] = "Shelf sync",
["搜索与发现"] = "Search and discover",
["登录后,在远程管理的「浏览器登录」中授权快看漫画;也可回到快看账号页粘贴 Cookie。"] = "After signing in, authorize Kuaikan under Browser login in Remote management, or paste the Cookie on the Kuaikan account page.",
}
@@ -0,0 +1,74 @@
return {
["在章末显示本章讨论,不是段落评论"] = "在章末顯示本章討論,不是段落評論",
["密码登录"] = "密碼登入",
["短信登录"] = "簡訊登入",
["快看密码登录"] = "快看密碼登入",
["快看短信登录"] = "快看簡訊登入",
["快看安全验证"] = "快看安全驗證",
["请输入密码"] = "請輸入密碼",
["登录前请阅读并同意快看用户协议和隐私协议"] = "登入前請閱讀並同意快看使用者協議和隱私協議",
["用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"] = "用同一 Wi-Fi 下的手機掃碼完成安全驗證;手機號碼、密碼和簡訊碼只在裝置填寫。",
["请完成下方安全验证"] = "請完成下方安全驗證",
["验证已提交,请回到设备查看结果。"] = "驗證已提交,請回到裝置查看結果。",
["验证或登录失败,请回到设备查看并重试"] = "驗證或登入失敗,請回到裝置查看並重試",
["滑块加载失败,请检查网络后刷新网页"] = "滑塊載入失敗,請檢查網路後重新整理網頁",
["快看漫画账号"] = "快看漫畫帳號",
["快看登录 Cookie"] = "快看登入 Cookie",
["在快看官网登录后,复制请求标头里的完整 Cookie"] = "在快看官網登入後,複製請求標頭裡的完整 Cookie",
["快看登录已失效,请重新登录"] = "快看登入已失效,請重新登入",
["旧快看账号身份无法确认,请先退出旧登录后重试"] = "舊快看帳號身分無法確認,請先登出舊登入後重試",
["快看收藏变更尚未确认"] = "快看收藏變更尚未確認",
["快看进度变更尚未确认"] = "快看進度變更尚未確認",
["快看云端章节不在当前目录中"] = "快看雲端章節不在目前目錄中",
["阅读进度同步"] = "閱讀進度同步",
["请先退出旧快看账号,再登录其他账号"] = "請先登出舊快看帳號,再登入其他帳號",
["确定退出快看账号?"] = "確定登出快看帳號?",
["地区"] = "地區",
["国漫"] = "國漫",
["韩漫"] = "韓漫",
["日漫"] = "日漫",
["VIP抢先看"] = "VIP搶先看",
["最火热"] = "最熱門",
["新上架"] = "新上架",
["话题页评论(首话)"] = "話題頁評論(首話)",
["国际区号"] = "國際區碼",
["请输入有效的手机号和国际区号"] = "請輸入有效的手機號碼和國際區碼",
["请稍后再获取验证码"] = "請稍後再取得驗證碼",
["验证码已发送"] = "驗證碼已發送",
["正在处理,请稍候"] = "正在處理,請稍候",
["请先获取该手机号的验证码,再填写验证码登录"] = "請先取得該手機號碼的驗證碼,再填寫驗證碼登入",
["登录状态已变化,请重试"] = "登入狀態已改變,請重試",
["登录响应无效"] = "登入回應無效",
["章节评论"] = "章節評論",
["快看漫画"] = "快看漫畫",
["快看漫画在线阅读"] = "快看漫畫線上閱讀",
["快看漫画书评加载失败"] = "快看漫畫書評載入失敗",
["获取验证码"] = "取得驗證碼",
["用微信扫一扫"] = "用微信掃一掃",
["本章未购买"] = "本章未購買",
["价格"] = "價格",
["免费"] = "免費",
["付费"] = "付費",
["连载中"] = "連載中",
["已完结"] = "已完結",
["验证已过期,请重新发起验证"] = "驗證已過期,請重新發起驗證",
["重新获取二维码"] = "重新取得二維碼",
["微信扫码登录"] = "微信掃碼登入",
["正在准备漫画…"] = "正在準備漫畫…",
["正在获取二维码…"] = "正在取得二維碼…",
["漫画目录为空"] = "漫畫目錄為空",
["章节目录保存失败"] = "章節目錄儲存失敗",
["章节图片解析失败"] = "章節圖片解析失敗",
["已在微信中拒绝登录"] = "已在微信中拒絕登入",
["手机号"] = "手機號碼",
["同意并继续"] = "同意並繼續",
["无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"] = "無法打開遠端驗證,請先連接 Wi-Fi 並啟用遠端管理功能",
["验证已取消"] = "驗證已取消",
["验证凭据无效"] = "驗證憑據無效",
["正在提交验证…"] = "正在提交驗證…",
["验证失败,请重新验证"] = "驗證失敗,請重新驗證",
["重试"] = "重試",
["书架同步"] = "書架同步",
["搜索与发现"] = "搜尋與發現",
["登录后,在远程管理的「浏览器登录」中授权快看漫画;也可回到快看账号页粘贴 Cookie。"] = "登入後,在遠端管理的「瀏覽器登入」中授權快看漫畫;也可回到快看帳號頁貼上 Cookie。",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_kuaikan._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,258 @@
--[[--
快看电脑端登录会话。匿名 Cookie、在飞请求和微信 state 归本次操作所有;
账号校验成功才保存。不同账号必须先经退出确认清理旧记录。
@module moonsource_kuaikan.login
--]]
local Client = require("moonsource_kuaikan.client")
local Mapper = require("moonsource_kuaikan.mapper")
local Request = require("http.request")
local CookieLogin = require("source.cookie_login")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kuaikan")
local HOST = "https://www.kuaikanmanhua.com"
---@class KuaikanLogin
---@field cookies table<string, { value: string, path: string }>
---@field job HttpJob|nil
---@field serial integer
---@field revision integer
---@field previous_cookie string|nil
---@field previous_id string|nil
---@field state string|nil
---@field sms_phone string|nil
---@field sms_retry_at integer|nil
local Login = {}
Login.__index = Login
function Login.new()
local cfg = require("utils.settings").getSource("ext.kuaikan")
return setmetatable({
cookies = {}, serial = 0, revision = Client.login_revision,
previous_cookie = cfg.cookie, previous_id = cfg.user_id,
}, Login)
end
function Login:cancel()
self.serial = self.serial + 1
if self.job then self.job.cancel(); self.job = nil end
end
---@param url string
---@return string
function Login:cookie(url)
local path = url:match("^https://www%.kuaikanmanhua%.com([^?]*)")
if not path then return "" end
local parts = {}
for name, item in pairs(self.cookies) do
if path:sub(1, #item.path) == item.path
and (path == item.path or item.path:sub(-1) == "/" or path:sub(#item.path + 1, #item.path + 1) == "/") then
parts[#parts + 1] = name .. "=" .. item.value
end
end
table.sort(parts)
return table.concat(parts, "; ")
end
---@param url string
---@param cb fun(raw: string|nil, err: any, res: table|nil)
---@param cookie string|nil 旧配置校验不合并其响应 Cookie
---@param fields table|nil
function Login:request(url, cb, cookie, fields)
self:cancel()
local serial, pending = self.serial, true
local job = Client.loginRequestAsync(url, cookie or self:cookie(url), function(raw, err, res)
pending = false
if serial ~= self.serial then return end
self.job = nil
if self.revision ~= Client.login_revision then cb(nil, _("登录状态已变化,请重试")); return end
if cookie == nil and url:sub(1, #HOST + 1) == HOST .. "/" then
local default_path = url:match("^https://[^/]+([^?]*)"):match("^(.*)/") or "/"
if default_path == "" then default_path = "/" end
for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do
local name, value = line:match("^%s*([^=;%s]+)=([^;]*)")
local domain = line:lower():match(";%s*domain=([^;]+)")
domain = domain and Text.trim(domain):gsub("^%.", "")
local path = Text.trim(line:match(";%s*[Pp][Aa][Tt][Hh]=([^;]*)") or default_path)
if path:sub(1, 1) ~= "/" then path = default_path end
if name and (not domain or domain == "kuaikanmanhua.com" or domain == "www.kuaikanmanhua.com") then
local max_age = tonumber(line:lower():match(";%s*max%-age=([%-]?%d+)"))
if value == "" or (max_age and max_age <= 0) then self.cookies[name] = nil
elseif CookieLogin.parse(name .. "=" .. value) ~= "" then
self.cookies[name] = { value = value, path = path }
end
end
end
end
cb(raw, err, res)
end, fields)
if pending then self.job = job end
end
---@param path string
---@param fields table
---@param cb fun(ok: boolean|nil, err: string|nil)
function Login:submit(path, fields, cb)
self:request(HOST .. path, function(raw, err)
if not raw or err then cb(nil, err and tostring(err) or _("请求失败")); return end
local decoded, wire = pcall(require("json").decode, raw)
if not decoded or type(wire) ~= "table" or not tonumber(wire.code) then
cb(nil, _("登录响应无效"))
elseif tonumber(wire.code) == 200 then
cb(true)
else
cb(nil, type(wire.message) == "string" and wire.message ~= "" and wire.message or _("登录失败"))
end
end, nil, fields)
end
---@param phone string
---@param captcha { ticket: string, random: string }
---@param cb fun(ok: boolean|nil, err: string|nil)
function Login:sendCodeAsync(phone, captcha, cb)
if self.sms_retry_at and os.time() < self.sms_retry_at then
cb(nil, _("请稍后再获取验证码"))
return
end
self:submit("/v2/passport/pc/v2/get_sms_code", {
phone = phone, ticket = captcha.ticket, random = captcha.random, verify_provider = "tencent",
}, function(ok, err)
if ok then self.sms_phone, self.sms_retry_at = phone, os.time() + 60 end
cb(ok, err)
end)
end
---@param phone string
---@param password string
---@param captcha { ticket: string, random: string }
---@param cb fun(account: table|nil, err: string|nil)
function Login:passwordAsync(phone, password, captcha, cb)
self:submit("/v2/passport/pc/v2/mobile_pwd_login_encrypted", Mapper.passwordFields(phone, password, captcha),
function(ok, err)
if not ok then cb(nil, err); return end
self:confirm(cb)
end)
end
---@param phone string
---@param code string
---@param cb fun(account: table|nil, err: string|nil)
function Login:codeAsync(phone, code, cb)
if phone ~= self.sms_phone or not code:match("^%d+$") then
cb(nil, _("请先获取该手机号的验证码,再填写验证码登录"))
return
end
self:submit("/v2/passport/pc/mobile_code_login", { phone = phone, code = code, remember = 1 },
function(ok, err)
if not ok then cb(nil, err); return end
self:confirm(cb)
end)
end
---@param account { user_id: string }
---@param cb fun(account: table|nil, err: string|nil)
function Login:accept(account, cb)
local settings = require("utils.settings")
local cfg = settings.getSource("ext.kuaikan")
if self.revision ~= Client.login_revision or cfg.cookie ~= self.previous_cookie or cfg.user_id ~= self.previous_id then
cb(nil, _("登录状态已变化,请重试"))
return
end
local cookie = self:cookie(Client.ACCOUNT_URL)
if cookie == "" then cb(nil, _("没有读到 Cookie")); return end
if (self.previous_id and tostring(self.previous_id) ~= account.user_id)
or (not self.previous_id and self.previous_cookie and cookie ~= CookieLogin.parse(self.previous_cookie)) then
local cleared = require("source.logout").clear("ext.kuaikan", function()
cfg.cookie, cfg.user_id, cfg.logged_in = nil, nil, nil
Client.login_revision = Client.login_revision + 1
settings.saveSource("ext.kuaikan")
end)
if not cleared then cb(nil, _("准备本地同步失败")); return end
end
cfg.cookie, cfg.user_id, cfg.logged_in = cookie, account.user_id, true
settings.saveSource("ext.kuaikan")
Client.login_revision = Client.login_revision + 1
self.revision = Client.login_revision
require("source.auth").ok("ext.kuaikan")
cb(account)
end
---@param cb fun(account: table|nil, err: string|nil)
function Login:confirm(cb)
self:request(Client.ACCOUNT_URL, function(raw, err, res)
local account, reason = Client.accountResponse(raw, err, res)
if not account then cb(nil, reason); return end
self:accept(account, cb)
end)
end
---@param cookie string
---@param cb fun(account: table|nil, err: string|nil)
function Login:cookieAsync(cookie, cb)
local parsed = CookieLogin.parse(cookie)
if parsed == "" then cb(nil, _("没有读到 Cookie")); return end
for name, value in parsed:gmatch("([^=;%s]+)=([^;]+)") do
self.cookies[name] = { value = Text.trim(value), path = "/" }
end
self:confirm(cb)
end
---@param cb fun(uuid: string|nil, err: string|nil)
function Login:qrCreateAsync(cb)
self:request(HOST .. "/v1/passport/login/pc/user_wechat_login?redirect_uri=" .. Text.urlEncode(Client.LOGIN_URL),
function(_raw, err, res)
local redirect = Mapper.qrLocation(Request.header(res, "Location"))
if not res or tonumber(res.code) ~= 302 or not redirect then
cb(nil, err and tostring(err) or _("获取二维码失败"))
return
end
self.state = redirect.state
self:request(redirect.url, function(raw, reason)
local uuid = raw and raw:match("/connect/qrcode/([%w_%-]+)")
if not uuid then cb(nil, reason and tostring(reason) or _("获取二维码失败")); return end
cb(uuid)
end)
end)
end
---@param uuid string
---@param last integer|nil
---@param cb fun(status: integer|nil, code: string|nil, err: string|nil)
function Login:qrPollAsync(uuid, last, cb)
self:request("https://long.open.weixin.qq.com/connect/l/qrconnect?"
.. Text.formEncode({ uuid = uuid, last = last or 408, f = "json" }), function(raw, err)
if not raw then cb(nil, nil, err and tostring(err) or _("请求失败")); return end
local status, code = Mapper.qrStatus(raw)
cb(status, code, not status and _("登录响应无效") or nil)
end)
end
---@param code string
---@param cb fun(account: table|nil, err: string|nil)
function Login:exchangeAsync(code, cb)
local function follow(url, remaining)
self:request(url, function(raw, err, res)
local status = res and tonumber(res.code)
if status and status >= 300 and status < 400 then
local location = Request.header(res, "Location")
if type(location) == "string" and location:sub(1, 1) == "/" and location:sub(1, 2) ~= "//" then
location = HOST .. location
end
if remaining == 0 or type(location) ~= "string" or location:sub(1, #HOST + 1) ~= HOST .. "/" then
cb(nil, _("登录响应无效"))
return
end
follow(location, remaining - 1)
return
end
if not raw or err then cb(nil, err and tostring(err) or _("登录失败")); return end
self:confirm(cb)
end)
end
if not self.state or type(code) ~= "string" or code == "" then cb(nil, _("登录响应无效")); return end
follow(Mapper.WECHAT_CALLBACK .. "?" .. Text.formEncode({ code = code, state = self.state }), 5)
end
return Login
@@ -0,0 +1,341 @@
--[[--
快看漫画响应到书籍、目录和页图。
目录不在 JSON 里。话题页把章节嵌进 `window.__NUXT__`,由 page.lua 拆开后再交给这里。
未解锁章节 `locked == true`,不给页图。
@module moonsource_kuaikan.mapper
--]]
local Text = require("utils.text")
local Mapper = {}
Mapper.TOC_VERSION = 1
local SOURCE_ID = "ext.kuaikan"
---@param topic_id string
---@param comic_id string
---@param pos ProgressPosition
---@param fraction number 章内比例
---@param count integer 图片页数
---@param now integer 毫秒时间
---@return table|nil
function Mapper.progressReport(topic_id, comic_id, pos, fraction, count, now)
local topic, comic = tonumber(topic_id), tonumber(comic_id)
if not topic or not comic or topic <= 0 or comic <= 0 or topic % 1 ~= 0 or comic % 1 ~= 0 then return nil end
local read_count = math.max(1, math.min(count, pos.page or math.ceil(fraction * count)))
return {
topic_id = topic, comic_id = comic, total_count = count,
read_count = read_count, max_read_count = read_count,
read_time = now, max_read_count_time = now,
}
end
---@param value any
---@return string
local function clean(value)
if type(value) ~= "string" then return "" end
return Text.trim(value)
end
---@param row table
---@return string
local function author(row)
if type(row.author_name) == "string" then return clean(row.author_name) end
local user = row.user
if type(user) == "table" then return clean(user.nickname) end
return ""
end
---@param row table
---@return string|nil
local function cover(row)
local url = row.vertical_image_url or row.cover_image_url
if type(url) ~= "string" or url == "" then return nil end
return url
end
---@param row table
---@return Book|nil
local function book(row)
if type(row) ~= "table" or row.id == nil or clean(row.title) == "" then return nil end
return {
source_id = SOURCE_ID,
stable_id = tostring(row.id),
title = clean(row.title),
authors = author(row),
cover = cover(row),
intro = clean(row.description),
}
end
---@param rows table|nil
---@return Book[]
local function books(rows)
local out = {}
if type(rows) ~= "table" then return out end
for _idx, row in ipairs(rows) do
local item = book(row)
if item then out[#out + 1] = item end
end
return out
end
---@param node string|nil
---@return string
function Mapper.storeNode(node)
if type(node) ~= "string" or not node:match("^%d+:%d+:%d+:%d+:%d+$") then return "0:1:0:0:1" end
-- 各筛选维度的枚举与官网 /tag/ 链接一致。
local parts = {}
for value in node:gmatch("%d+") do parts[#parts + 1] = value end
if tonumber(parts[2]) < 1 or tonumber(parts[2]) > 4
or tonumber(parts[3]) > 3 or tonumber(parts[4]) > 2
or tonumber(parts[5]) < 1 or tonumber(parts[5]) > 3 then return "0:1:0:0:1" end
return node
end
---@param wire table|nil
---@param node string
---@param page integer
---@return Book[]|nil, StoreChipGroup[]|nil, boolean|nil
function Mapper.store(wire, node, page)
if type(wire) ~= "table" or tonumber(wire.code) ~= 200 or type(wire.hits) ~= "table" then return nil end
local rows, tags, total = wire.hits.topicMessageList, wire.hits.topicCategories, tonumber(wire.total)
if type(rows) ~= "table" or type(tags) ~= "table" or not total or total < 0 then return nil end
local _ = require("l10n").get("moonsource_kuaikan")
local parts = {}
for value in Mapper.storeNode(node):gmatch("%d+") do parts[#parts + 1] = value end
local categories = {}
for _idx, tag in ipairs(tags) do
local id = type(tag) == "table" and (tag.tag_id or tag.tagId)
if id == nil or not tostring(id):match("^%d+$") or clean(tag.title) == "" then return nil end
categories[#categories + 1] = { tostring(id), tag.title }
end
local dimensions = {
{ _("分类"), categories },
{ _("地区"), { { "1", _("全部") }, { "2", _("国漫") }, { "3", _("韩漫") }, { "4", _("日漫") } } },
{ _("价格"), { { "0", _("全部") }, { "1", _("免费") }, { "2", _("付费") }, { "3", _("VIP抢先看") } } },
{ _("状态"), { { "0", _("全部") }, { "1", _("连载中") }, { "2", _("已完结") } } },
{ _("排序"), { { "1", _("推荐") }, { "2", _("最火热") }, { "3", _("新上架") } } },
}
local groups = {}
for index, dimension in ipairs(dimensions) do
local chips = {}
local saved = parts[index]
for _idx, choice in ipairs(dimension[2]) do
parts[index] = choice[1]
chips[#chips + 1] = { id = table.concat(parts, ":"), title = choice[2] }
end
parts[index] = saved
local group = require("source.browse").group(chips, table.concat(parts, ":"))
group.title = dimension[1]
groups[#groups + 1] = group
end
local list = books(rows)
if #list ~= #rows then return nil end
return list, groups, page * 48 < total
end
---@param wire table|nil
---@return Book[]|nil
function Mapper.search(wire)
if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end
local topics = type(wire.data) == "table" and wire.data.topics or nil
local hit = type(topics) == "table" and topics.hit or nil
if type(hit) ~= "table" then return nil end
return books(hit)
end
---@param wire table|nil
---@return Book[]|nil
function Mapper.home(wire)
if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end
local rows = type(wire.data) == "table" and wire.data.popularity_topics or nil
if type(rows) ~= "table" then return nil end
return books(rows)
end
--- 收藏列表。`data.topics` 是书卡数组,空数组是空收藏。
---@param wire table|nil
---@return Book[]|nil, integer|nil
function Mapper.fav(wire)
if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end
local data = type(wire.data) == "table" and wire.data or nil
local rows = data and data.topics or nil
local total = data and tonumber(data.total)
if type(rows) ~= "table" or not total or total < 0 or total ~= math.floor(total) then return nil end
local list = books(rows)
if #list ~= #rows then return nil end
return list, total
end
--- 话题页拆出来的章节行。
---@param rows table[]|nil
---@return BookChapter[]|nil
function Mapper.chapters(rows)
if type(rows) ~= "table" then return nil end
local out = {}
for _idx, row in ipairs(rows) do
if type(row) == "table" and row.id ~= nil and clean(row.title) ~= "" then
out[#out + 1] = {
idx = #out + 1,
uid = tostring(row.id),
title = clean(row.title),
vip = row.locked == true,
}
end
end
if not out[1] then return nil end
out[1].toc_version = Mapper.TOC_VERSION
return out
end
--- 详情。作者是页面脚本里单独赋的昵称。
---@param info table|nil
---@param nickname string|nil
---@return Book|nil
function Mapper.detail(info, nickname)
local item = book(info or {})
if item and type(nickname) == "string" and nickname ~= "" then item.authors = nickname end
return item
end
--- 话题评论。网页只展示 `replied_comment_id` 为 0 的楼,字段是 user.nickname、content、created_at_info、likes_count。
--- 第二返回值是 data.total。
---@param wire table|nil
---@return { id: string|nil, author: string, text: string, time: string|nil, likes: number|nil }[]|nil
---@return integer|nil
function Mapper.comments(wire)
if type(wire) ~= "table" or tonumber(wire.code) ~= 200 or type(wire.data) ~= "table" then
return nil
end
local rows = wire.data.comments
local total = tonumber(wire.data.total)
if type(rows) ~= "table" or not total or total < 0 then return nil end
local out = {}
for _idx, row in ipairs(rows) do
if type(row) ~= "table" or type(row.content) ~= "string" or tonumber(row.replied_comment_id) == nil then
return nil
end
if tonumber(row.replied_comment_id) == 0 then
local user = type(row.user) == "table" and row.user or {}
local stamp = type(row.created_at_info) == "string" and row.created_at_info:match("^(%S+)") or nil
out[#out + 1] = {
id = (type(row.id) == "string" or type(row.id) == "number") and tostring(row.id) or nil,
author = type(user.nickname) == "string" and user.nickname or "",
text = row.content,
time = stamp,
likes = tonumber(row.likes_count),
}
end
end
return out, total
end
--- 一话的页图 URL。locked 的章节没有图。
---@param wire table|nil
---@return string[]|nil
---@return string|nil
function Mapper.images(wire)
if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil end
local info = type(wire.data) == "table" and wire.data.comic_info or nil
if type(info) ~= "table" then return nil end
if info.locked == true then return nil, "locked" end
local rows = info.comic_images
if type(rows) ~= "table" then return nil end
local urls = {}
for _idx, row in ipairs(rows) do
local url = type(row) == "table"
and (type(row.url1280) == "string" and row.url1280 ~= "" and row.url1280 or row.url) or nil
if type(url) ~= "string" or url == "" then return nil end
urls[#urls + 1] = url
end
if #urls == 0 then return nil end
return urls
end
---@param wire table|nil
---@return { user_id: string }|nil
---@return string|nil
function Mapper.account(wire)
if type(wire) ~= "table" or tonumber(wire.code) ~= 200 then return nil, "invalid" end
if type(wire.data) ~= "table" or type(wire.data.user_info) ~= "table" then return nil, "invalid" end
---@type table<string, any>
local user = wire.data.user_info
local authenticated = tonumber(user.authenticate)
if authenticated == 0 then return nil, "unauthorized" end
if not authenticated or authenticated < 0 then return nil, "invalid" end
local id = user.user_id
if type(id) ~= "number" and type(id) ~= "string" then return nil, "invalid" end
id = tostring(id)
if not id:match("^%d+$") then return nil, "invalid" end
id = id:gsub("^0+", "")
if id == "" then return nil, "invalid" end
return { user_id = id }
end
Mapper.WECHAT_CALLBACK = "https://www.kuaikanmanhua.com/v1/passport/login/pc/user_wechat_login_check"
---@param country string
---@param number string
---@return string|nil
function Mapper.phone(country, number)
country, number = Text.trim(country), Text.trim(number)
if not country:match("^%+%d+$") or #country > 5 then return nil end
if country == "+86" then
if not number:match("^1[3-9]%d%d%d%d%d%d%d%d%d$") then return nil end
elseif not number:match("^%d+$") or #number < 7 or #number > 12 then
return nil
end
return country .. "-" .. number
end
---@param phone string
---@param password string
---@param captcha { ticket: string, random: string }
---@return table
function Mapper.passwordFields(phone, password, captcha)
local AES = require("crypto.aes")
-- 官网公开脚本的 UTF-8 原始密钥、IV 与 PKCS7,不是 Base64 密钥或口令派生。
local key, iv = "CRL66bnFXBaLt39tgU8GJrVymV/jBJqv", "vdjsaj42mxfkck39"
return {
phone = Text.base64Encode(AES.cbc_encrypt(phone, key, iv)),
password = Text.base64Encode(AES.cbc_encrypt(password, key, iv)),
remember = 1, ticket = captcha.ticket, random = captcha.random, verify_provider = "tencent",
}
end
---@param location string|nil
---@return { url: string, state: string }|nil
function Mapper.qrLocation(location)
if type(location) ~= "string" or not location:match("^https://open%.weixin%.qq%.com/connect/qrconnect%?") then return nil end
local params = {}
for key, value in location:match("%?([^#]*)"):gmatch("([^&=]+)=([^&]*)") do
key = Text.urlDecode(key)
if params[key] then return nil end
params[key] = Text.urlDecode(value)
end
if params.appid ~= "wx92ba65b18ed55877" or params.scope ~= "snsapi_login"
or params.response_type ~= "code" or params.redirect_uri ~= Mapper.WECHAT_CALLBACK
or not params.state or params.state == "" then return nil end
return { url = location, state = params.state }
end
---@param raw string
---@return integer|nil
---@return string|nil
function Mapper.qrStatus(raw)
local ok, wire = pcall(require("json").decode, raw)
local status, code
if ok and type(wire) == "table" then
status, code = tonumber(wire.wx_errcode), wire.wx_code
else
status = tonumber(raw:match("wx_errcode%s*=%s*(%d+)"))
code = raw:match("wx_code%s*=%s*['\"]([^'\"]*)['\"]")
end
if not status or (status == 405 and (type(code) ~= "string" or code == "")) then return nil end
return status, code
end
return Mapper
@@ -0,0 +1,239 @@
--[[--
从话题页的 `window.__NUXT__` 里拆目录。
网页把接口响应编成一个函数调用:结构留在函数体,字符串和数字落在参数上。
章节数组是 `comics:[{id:`,作者昵称是函数体里唯一的 `.nickname="..."` 赋值。
@module moonsource_kuaikan.page
--]]
local Page = {}
local JSON = require("json")
--- 参数位置上的对象 / null。不能把 nil 塞进数组,否则后面的参数整体错位。
local HOLE = {}
---@param source string
---@param index integer
---@return integer
local function skip(source, index)
return (source:match("^%s*()", index)) or index
end
---@param source string
---@param index integer 引号所在位置
---@return string|nil
---@return integer|nil
local function readString(source, index)
local quote = source:sub(index, index)
local cursor = index + 1
while cursor <= #source do
local char = source:sub(cursor, cursor)
if char == "\\" then
cursor = cursor + 2
elseif char == quote then
local literal = source:sub(index, cursor)
if quote ~= '"' then
literal = '"' .. literal:sub(2, -2):gsub("\\'", "'"):gsub('"', '\\"') .. '"'
end
local ok, value = pcall(JSON.decode, literal)
if not ok or type(value) ~= "string" then return nil end
return value, cursor + 1
else
cursor = cursor + 1
end
end
return nil
end
--- 跳过从 index 开始的引号字符串,返回结束后的位置。
---@param source string
---@param index integer
---@return integer|nil
local function skipString(source, index)
local _text, next_index = readString(source, index)
return next_index
end
--- 配平 `{}` / `[]`,字符串里的括号不算。
---@param source string
---@param index integer
---@return integer|nil
local function matchBlock(source, index)
local depth = 0
while index <= #source do
local char = source:sub(index, index)
if char == '"' or char == "'" then
index = skipString(source, index)
if not index then return nil end
elseif char == "{" or char == "[" then
depth = depth + 1
index = index + 1
elseif char == "}" or char == "]" then
depth = depth - 1
index = index + 1
if depth == 0 then return index end
else
index = index + 1
end
end
return nil
end
---@param source string
---@param index integer
---@param env table<string, any>
---@return any
---@return integer|nil
local function readValue(source, index, env)
index = skip(source, index)
local char = source:sub(index, index)
if char == '"' or char == "'" then return readString(source, index) end
if char == "{" or char == "[" then return nil, matchBlock(source, index) end
local ident = source:match("^[%a_$][%w_$]*", index)
if ident then
local after = index + #ident
if source:sub(after, after) == "(" then
local close = source:find(")", after + 1, true)
if not close then return nil end
return nil, close + 1
end
if ident == "true" then return true, after end
if ident == "false" then return false, after end
if ident == "null" or ident == "undefined" then return nil, after end
return env[ident], after
end
local number = source:match("^-?%d+%.?%d*", index)
if number then return tonumber(number), index + #number end
return nil, index
end
---@param source string
---@param index integer 指向 `{`
---@param env table<string, any>
---@return table|nil
---@return integer|nil
local function readObject(source, index, env)
index = index + 1
local fields = {}
while index <= #source do
index = skip(source, index)
if source:sub(index, index) == "}" then return fields, index + 1 end
local key = source:match("^[%w_]+", index)
if not key then return nil end
index = index + #key
if source:sub(index, index) ~= ":" then return nil end
local value, next_index = readValue(source, index + 1, env)
if not next_index or next_index <= index then return nil end
fields[key] = value
index = skip(source, next_index)
if source:sub(index, index) == "," then
index = index + 1
elseif source:sub(index, index) ~= "}" then
return nil
end
end
return nil
end
---@param source string
---@param index integer 指向 `(`
---@return any[]|nil
local function readArgs(source, index)
index = index + 1
local args = {}
while index <= #source do
index = skip(source, index)
if source:sub(index, index) == ")" then return args end
local value, next_index = readValue(source, index, {})
if not next_index or next_index <= index then return nil end
args[#args + 1] = value == nil and HOLE or value
index = skip(source, next_index)
local separator = source:sub(index, index)
if separator == "," then index = index + 1
elseif separator ~= ")" then return nil end
end
return nil
end
---@param script string
---@return table<string, any>|nil
local function bind(script)
local params_at = script:find("function(", 1, true)
if not params_at then return nil end
local params_end = script:find(")", params_at + 9, true)
if not params_end then return nil end
local params = {}
for name in script:sub(params_at + 9, params_end - 1):gmatch("[%a_$][%w_$]*") do
params[#params + 1] = name
end
local body_at = skip(script, params_end + 1)
if script:sub(body_at, body_at) ~= "{" then return nil end
local after_body = matchBlock(script, body_at)
if not after_body then return nil end
local args_at = skip(script, after_body)
if script:sub(args_at, args_at) ~= "(" then return nil end
local args = readArgs(script, args_at)
if not args then return nil end
local env = {}
for index, name in ipairs(params) do
local value = args[index]
if value ~= HOLE and (type(value) == "string" or type(value) == "number" or type(value) == "boolean") then
env[name] = value
end
end
return env
end
--- 拆话题页。失败返回 nil。
---@param html string|nil
---@return { info: table, nickname: string, chapters: table[] }|nil
function Page.topic(html)
if type(html) ~= "string" then return nil end
local at = html:find("window.__NUXT__=", 1, true)
if not at then return nil end
local script = html:sub(at)
local env = bind(script)
if not env then return nil end
local info_at = script:find("topicInfo:{", 1, true)
local info = {}
if info_at then
local object = readObject(script, info_at + #"topicInfo:" , env)
if object then info = object end
end
local comics_at = script:find("comics:[{id:", 1, true)
if not comics_at then return nil end
local cursor = script:find("{", comics_at, true)
local chapters = {}
while cursor and script:sub(cursor, cursor) == "{" do
local row, next_cursor = readObject(script, cursor, env)
if not row then return nil end
if row.id == nil or type(row.title) ~= "string" or row.title == "" then return nil end
chapters[#chapters + 1] = {
id = row.id,
title = row.title,
locked = row.locked == true,
}
cursor = skip(script, next_cursor)
if script:sub(cursor, cursor) == "," then
cursor = skip(script, cursor + 1)
elseif script:sub(cursor, cursor) == "]" then
break
else
return nil
end
end
if #chapters == 0 or script:sub(cursor, cursor) ~= "]" then return nil end
local nickname_at = script:find('%.nickname="')
local nickname = nickname_at and readString(script, nickname_at + #".nickname=")
return {
info = info,
nickname = nickname or "",
chapters = chapters,
}
end
return Page
@@ -0,0 +1,149 @@
--[[--
快看手机号密码与短信登录。输入窗、滑块和 HTTP 共用本次候选会话。
@module moonsource_kuaikan.phone_login
--]]
local Mapper = require("moonsource_kuaikan.mapper")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kuaikan")
---@class KuaikanPhoneLogin
---@field mode string
---@field session KuaikanLogin
---@field generation integer
---@field busy boolean|nil
---@field agreed boolean|nil
---@field verification KuaikanVerification|nil
---@field dialog BookThemeInput|nil
---@field on_user fun(account: table)
local PhoneLogin = {}
PhoneLogin.__index = PhoneLogin
function PhoneLogin.new(mode, on_user)
return setmetatable({
mode = mode, on_user = on_user, generation = 0,
session = require("moonsource_kuaikan.login").new(),
}, PhoneLogin)
end
function PhoneLogin:cancel()
self.generation = self.generation + 1
if self.verification then self.verification:cancel(); self.verification = nil end
self.session:cancel()
self.busy, self.dialog = false, nil
end
function PhoneLogin:ready(country, number)
local err
if self.busy then err = _("正在处理,请稍候")
elseif not require("ui/network/manager"):isConnected() then err = _("网络不可用,请先连接 Wi-Fi") end
local phone = Mapper.phone(country, number)
if not err and not phone then err = _("请输入有效的手机号和国际区号") end
if err then require("ui.themes.widgets.toast"):new{ text = err }:show(); return nil end
return phone
end
function PhoneLogin:agree(fn)
if self.agreed then fn(); return end
local gen = self.generation
require("ui.themes.widgets.confirm"):new{
text = _("登录前请阅读并同意快看用户协议和隐私协议")
.. "\nhttps://www.kuaikanmanhua.com/webs/agreement"
.. "\nhttps://h5.kuaikanmanhua.com/normal/protocol/?type=1"
.. "\nhttps://h5.kuaikanmanhua.com/normal/protocol/?type=2",
ok_text = _("同意并继续"),
ok_callback = function()
if gen ~= self.generation then return end
self.agreed = true
fn()
end,
}:show()
end
function PhoneLogin:captcha(country, number, password)
local phone = self:ready(country, number)
if not phone then return end
if self.mode == "password" and password == "" then
require("ui.themes.widgets.toast"):new{ text = _("请输入密码") }:show()
return
end
if self.mode ~= "password" and self.session.sms_retry_at and os.time() < self.session.sms_retry_at then
require("ui.themes.widgets.toast"):new{ text = _("请稍后再获取验证码") }:show()
return
end
self:agree(function()
if not self:ready(country, number) then return end
self.busy = true
local dialog = self.dialog
self.dialog = nil
dialog:close()
local gen = self.generation
local verification = require("moonsource_kuaikan.verify").new(self.session, function(proof, cb)
if self.mode == "password" then self.session:passwordAsync(phone, password, proof, cb)
else self.session:sendCodeAsync(phone, proof, cb) end
end, function(result, err)
if gen ~= self.generation then return end
self.busy, self.verification = false, nil
if result and self.mode == "password" then
self:cancel()
self.on_user(result)
return
end
self:start(country, number)
require("ui.themes.widgets.toast"):new{
text = result and _("验证码已发送") or err or _("登录失败"), timeout = 4,
}:show()
end)
if not verification.done then self.verification = verification end
end)
end
function PhoneLogin:verify(country, number, code)
local phone = self:ready(country, number)
if not phone then return end
code = Text.trim(code)
if phone ~= self.session.sms_phone or not code:match("^%d+$") then
require("ui.themes.widgets.toast"):new{
text = _("请先获取该手机号的验证码,再填写验证码登录"),
}:show()
return
end
self.busy = true
local gen = self.generation
self.session:codeAsync(phone, code, function(account, err)
if gen ~= self.generation then return end
self.busy = false
if not account then require("ui.themes.widgets.toast"):new{ text = err or _("登录失败") }:show(); return end
self.dialog:close()
self:cancel()
self.on_user(account)
end)
end
function PhoneLogin:start(country, number)
local password = self.mode == "password"
local dialog
dialog = require("ui.themes.widgets.input"):new{
title = password and _("快看密码登录") or _("快看短信登录"),
fields = {
{ label = _("国际区号"), text = country or "+86" },
{ label = _("手机号"), text = number or "", input_type = "number" },
{ label = password and _("密码") or _("验证码"),
text_type = password and "password" or nil, input_type = not password and "number" or nil },
},
keep_open = true, ok_text = _("登录"),
actions = not password and { { text = _("获取验证码"), callback = function(cc, phone)
if self.dialog == dialog then self:captcha(cc, phone) end
end } } or nil,
callback = function(cc, phone, value)
if self.dialog ~= dialog then return end
if password then self:captcha(cc, phone, value) else self:verify(cc, phone, value) end
end,
close_callback = function() if self.dialog == dialog then self:cancel() end end,
}
self.dialog = dialog
dialog:show()
end
return PhoneLogin
@@ -0,0 +1,104 @@
--[[--
快看微信扫码窗口。关闭取消在飞请求和轮询;确认后仅通过官方回调兑换会话。
@module moonsource_kuaikan.qrlogin
--]]
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_kuaikan")
---@class KuaikanQRLogin
---@field generation integer
---@field session KuaikanLogin|nil
---@field poll function|nil
---@field waiting table|nil
---@field dialog table|nil
---@field deadline number
---@field on_user fun()
local QRLogin = {}
QRLogin.__index = QRLogin
function QRLogin.new(on_user)
return setmetatable({ on_user = on_user, generation = 0 }, QRLogin)
end
function QRLogin:cancel()
self.generation = self.generation + 1
if self.session then self.session:cancel() end
if self.poll then require("ui/uimanager"):unschedule(self.poll); self.poll = nil end
if self.waiting then self.waiting:close(); self.waiting = nil end
if self.dialog then
local dialog = self.dialog
self.dialog = nil
dialog:close()
end
end
function QRLogin:retry(text)
self:cancel()
require("ui.themes.widgets.confirm"):new{
text = text, ok_text = _("重新获取二维码"), ok_callback = function() self:start() end,
}:show()
end
function QRLogin:pollAsync(gen, uuid, last)
if gen ~= self.generation then return end
if not require("ui/network/manager"):isConnected() then self:retry(_("网络不可用,请先连接 Wi-Fi")); return end
if os.time() >= self.deadline then self:retry(_("二维码已过期")); return end
self.session:qrPollAsync(uuid, last, function(status, code, err)
if gen ~= self.generation then return end
if status == 405 then
self.session:exchangeAsync(code, function(account, reason)
if gen ~= self.generation then return end
if not account then self:retry(reason or _("登录失败")); return end
self:cancel()
self.on_user()
end)
return
end
if status ~= 404 and status ~= 408 then
self:retry(err or (status == 403 and _("已在微信中拒绝登录") or _("二维码已过期")))
return
end
if status == 404 and last ~= 404 then
require("ui.themes.widgets.toast"):new{ text = _("已扫码,请在手机上确认") }:show()
end
self.poll = require("ui.guard").wrap("kuaikan QR poll", function()
self.poll = nil
self:pollAsync(gen, uuid, status)
end)
require("ui/uimanager"):scheduleIn(1, self.poll)
end)
end
function QRLogin:start()
self:cancel()
if not require("ui/network/manager"):isConnected() then
require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi") }:show()
return
end
local gen = self.generation
self.session = require("moonsource_kuaikan.login").new()
self.deadline = os.time() + 300
self.waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("微信扫码登录"), text = _("正在获取二维码…"),
on_cancel = function() self:cancel() end,
}
self.waiting:show()
self.session:qrCreateAsync(function(uuid, err)
if gen ~= self.generation then return end
self.waiting:close()
self.waiting = nil
if not uuid then self:retry(err or _("获取二维码失败")); return end
self.dialog = require("ui.themes.widgets.qr"):new{
title = _("微信扫码登录"), caption = _("用微信扫一扫"),
text = "https://open.weixin.qq.com/connect/confirm?uuid=" .. Text.urlEncode(uuid),
actions = { { text = _("重新获取二维码"), callback = function() self:start() end } },
close_callback = function() if gen == self.generation then self:cancel() end end,
}
self.dialog:show()
self:pollAsync(gen, uuid)
end)
end
return QRLogin
@@ -0,0 +1,134 @@
--[[--
快看账号:微信扫码、手机号密码、短信、官网浏览器授权与 Cookie 导入。
@module moonsource_kuaikan.setting
--]]
local Client = require("moonsource_kuaikan.client")
local CookieLogin = require("source.cookie_login")
local _ = require("l10n").get("moonsource_kuaikan")
local Setting = {}
local COOKIE_PATHS = { ["/"] = true, ["/v2"] = true, ["/v2/"] = true, ["/v2/pweb"] = true, ["/v2/pweb/"] = true }
function Setting.rowStatus()
local cfg = require("utils.settings").getSource("ext.kuaikan")
local on = cfg.logged_in == true and type(cfg.cookie) == "string" and cfg.cookie ~= ""
and type(cfg.user_id) == "string" and cfg.user_id ~= "" and not require("source.auth").expired("ext.kuaikan")
return on and _("已登录") or _("未登录 · 点此登录"), on
end
local function onLogin()
require("source.registry").reload()
require("ui.themes.widgets.toast"):new{ text = _("登录成功"), timeout = 2 }:show()
end
local function pasteCookie()
local Toast = require("ui.themes.widgets.toast")
require("ui.themes.widgets.input"):new{
title = _("快看登录 Cookie"),
fields = { { text = "", hint = _("在快看官网登录后,复制请求标头里的完整 Cookie") } },
ok_text = _("登录"),
callback = function(cookie)
if not require("ui/network/manager"):isConnected() then
Toast:new{ text = _("网络不可用,请先连接 Wi-Fi") }:show()
return
end
local session = require("moonsource_kuaikan.login").new()
local cancelled = false
local waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("快看漫画账号"), text = _("正在校验登录…"),
on_cancel = function() cancelled = true; session:cancel() end,
}
waiting:show()
session:cookieAsync(cookie, function(account, err)
if cancelled then return end
waiting:close()
if account then onLogin()
else Toast:new{ text = err or _("登录失败"), timeout = 3 }:show() end
end)
end,
}:show()
end
Setting.browser = {
domain = "www.kuaikanmanhua.com", scope = "cookie",
login = Client.LOGIN_URL, check = Client.ACCOUNT_URL,
check_json = { path = "data.user_info.authenticate", ok = { 1 } },
icon = "https://festatic.v3mh.com/static-resource/img/32x32/favicon.ico",
isAuthorized = function() local _status, on = Setting.rowStatus(); return on end,
apply = function(payload, cb)
local cookies = {}
for _idx, cookie in ipairs(type(payload.cookies) == "table" and payload.cookies or {}) do
local host = type(cookie) == "table" and type(cookie.domain) == "string"
and cookie.domain:gsub("^%.", ""):lower()
local path = type(cookie) == "table" and cookie.path or "/"
if (host == "kuaikanmanhua.com" or host == "www.kuaikanmanhua.com")
and COOKIE_PATHS[path] then
cookies[#cookies + 1] = cookie
end
end
local session = require("moonsource_kuaikan.login").new()
session:cookieAsync(CookieLogin.fromPayload({ cookies = cookies }, "kuaikanmanhua.com"), function(account, err)
if account then require("source.registry").reload() end
cb(account ~= nil, err)
end)
return { cancel = function() session:cancel() end }
end,
}
function Setting.login()
require("moonsource_kuaikan.qrlogin").new(onLogin):start()
end
function Setting.rows(plugin)
local Row = require("ui.themes.widgets.row")
local rows = {
function(iw)
local status, on = Setting.rowStatus()
return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "account_circle",
title = _("快看漫画账号"), status = status, status_on = on,
subtitle = _("微信扫码登录"), callback = Setting.login })
end,
CookieLogin.browserRow(),
function(iw)
return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "content_paste",
title = _("粘贴 Cookie"), callback = pasteCookie })
end,
function(iw)
return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "password",
title = _("密码登录"), callback = function()
require("moonsource_kuaikan.phone_login").new("password", onLogin):start()
end })
end,
function(iw)
return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "sms",
title = _("短信登录"), callback = function()
require("moonsource_kuaikan.phone_login").new("sms", onLogin):start()
end })
end,
function(iw)
local reviews = require("source.review_setting")
local on = reviews.enabled("ext.kuaikan")
return Row.widget({ width = iw, chevron = false, kind = "toggle", icon = "forum",
title = _("章节评论"), subtitle = _("在章末显示本章讨论,不是段落评论"),
status = on and _("开") or _("关"), status_on = on,
callback = function()
reviews.set("ext.kuaikan", not on)
if plugin and plugin.desktop then plugin.desktop:updateView() end
end })
end,
}
local cfg = require("utils.settings").getSource("ext.kuaikan")
if type(cfg.cookie) == "string" and cfg.cookie ~= "" then
rows[#rows + 1] = require("source.logout").row("ext.kuaikan", _("确定退出快看账号?"), function()
cfg = require("utils.settings").getSource("ext.kuaikan")
cfg.cookie, cfg.user_id, cfg.logged_in = nil, nil, nil
Client.login_revision = Client.login_revision + 1
require("utils.settings").saveSource("ext.kuaikan")
end)
end
return rows
end
return Setting
@@ -0,0 +1,397 @@
--[[--
快看漫画数据源。
免费话不需要登录。登录后默认双向同步收藏与阅读进度。
一话是一组图片,打成 CBZ。
@module source.kuaikan
--]]
local Client = require("moonsource_kuaikan.client")
local Mapper = require("moonsource_kuaikan.mapper")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_kuaikan")
local Kuaikan = {}
---@return BookSourceMeta
function Kuaikan.meta()
return require("moonsource_kuaikan.loadmeta")()
end
---@class KuaikanSource : SourceBase
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
Source.__index = Source
local putProgressAsync
---@return KuaikanSource
function Kuaikan.new()
local meta = Kuaikan.meta()
return setmetatable({
id = meta.id, name = meta.name, type = meta.type,
putProgressAsync = Client.hasAccount() and putProgressAsync or nil,
}, Source)
end
--- 未登录的收藏列表是空的,不能拿来对账。
---@return SourceCapabilities
function Source:capabilities()
local caps = SourceBase.capabilities(self)
caps.shelf_push = Client.hasAccount()
return caps
end
---@return boolean
function Source:configured()
return true
end
---@param opts { force?: boolean, dirty_only?: boolean, on_progress?: fun(text: string, done: integer|nil, total: integer|nil) }|nil
---@param cb fun(result: SyncResult|nil, err: string|nil)
---@return { cancel: fun() }
function Source:syncBooksAsync(opts, cb)
opts = opts or {}
local remote, pipeline = Client.newSync(false), nil
if remote.cookie == "" then return SourceBase.skipped(cb, "not_logged_in") end
remote:checkAsync(function(account, err)
if remote.cancelled then return end
if not account then cb(nil, err); return end
local settings = require("utils.settings")
local cfg = settings.getSource(self.id)
if remote.user_id ~= account.user_id or cfg.logged_in ~= true then
cfg.user_id, cfg.logged_in = account.user_id, true
settings.saveSource(self.id)
remote.user_id = account.user_id
end
remote.writing = true
self.putProgressAsync = putProgressAsync
local pending = true
local job = require("source.shelf").syncAsync(self.id, remote, nil, opts, function(result, reason)
pending, pipeline = false, nil
if remote.cancelled then return end
if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end
if result and remote.push_error then
if not opts.dirty_only then cb(nil, remote.push_error); return end
result.push_error = remote.push_error
end
cb(result, reason)
end)
if pending then pipeline = job end
end)
return { cancel = function()
remote:cancel()
if pipeline then pipeline:cancel() end
end }
end
---@param identity BookIdentity
---@param cb fun(pos: ProgressPosition|nil, err: string|nil, meta: table|nil)
function Source:getProgressAsync(identity, cb)
local cfg = require("utils.settings").getSource(self.id)
if not cfg.cookie or cfg.cookie == "" then return SourceBase.defer(cb, nil, nil, { empty = true }) end
local remote, toc_job = Client.newSync(false), nil
remote:checkAsync(function(account, err)
if remote.cancelled then return end
if not account then cb(nil, err); return end
remote:historyAsync(identity.stable_id, function(comic_id, reason)
if not comic_id then cb(nil, reason, not reason and { empty = true } or nil); return end
local function load(force)
local pending = true
local job = self:loadTocAsync(identity, function(toc, toc_err)
pending, toc_job = false, nil
if remote.cancelled then return end
if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end
if not toc then cb(nil, toc_err); return end
for idx, chapter in ipairs(toc) do
if chapter.uid == comic_id then
cb({ chapter_idx = idx, chapter_title = chapter.title, fraction = (idx - 1) / #toc })
return
end
end
if not force then load(true); return end
cb(nil, _("快看云端章节不在当前目录中"))
end, force)
if pending then toc_job = job end
end
load(false)
end)
end)
return { cancel = function()
remote:cancel()
if toc_job then toc_job:cancel() end
end }
end
---@param self KuaikanSource
---@param identity BookIdentity
---@param pos ProgressPosition
---@param cb fun(ok: boolean|nil, err: string|nil)
putProgressAsync = function(self, identity, pos, cb)
local remote, extra_job = Client.newSync(true), nil
remote:checkAsync(function(account, err)
if remote.cancelled then return end
if not account then cb(nil, err); return end
local pending = true
local job = self:loadTocAsync(identity, function(toc, toc_err)
pending, extra_job = false, nil
if remote.cancelled then return end
if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end
if not toc then cb(nil, toc_err); return end
local idx = pos.chapter_idx or identity.chapter_idx
if not idx then idx = math.min(#toc, math.floor(pos.fraction * #toc) + 1) end
if not toc[idx] then cb(nil, _("快看云端章节不在当前目录中")); return end
local function report(count)
if remote.cancelled then return end
if not remote:current() then cb(nil, _("登录状态已变化,请重试")); return end
local fraction = pos.chapter_fraction
if not fraction then fraction = math.max(0, math.min(1, pos.fraction * #toc - (idx - 1))) end
local record = Mapper.progressReport(identity.stable_id, toc[idx].uid, pos, fraction, count, os.time() * 1000)
if not record then cb(nil, _("响应无效")); return end
remote:reportProgressAsync(record, cb)
end
if pos.total_pages and pos.total_pages > 0 then report(pos.total_pages); return end
local fetching = true
local images_job = Client.imagesAsync(toc[idx].uid, function(urls, image_err)
fetching, extra_job = false, nil
if remote.cancelled then return end
if not urls then cb(nil, image_err); return end
report(#urls)
end)
if fetching then extra_job = images_job end
end)
if pending then extra_job = job end
end)
return { cancel = function()
remote:cancel()
if extra_job then extra_job:cancel() end
end }
end
---@param keyword string
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
function Source:searchAsync(keyword, cb)
return Client.searchAsync(keyword, function(books, err)
if not books then cb(nil, err or _("请求失败")); return end
cb({ data = books })
end)
end
---@param opts table|nil
---@param cb fun(res: { data: Book[] }|nil, err: string|nil)
function Source:browseAsync(opts, cb)
local node, limit = Mapper.storeNode(opts and opts.node), opts and opts.limit or 60
local cancelled, active = false, nil
local loaded = false
local first = Client.storeAsync(node, 1, function(books, err, more, groups)
loaded = true
if cancelled then return end
active = nil
if not books then cb(nil, err); return end
local finished = false
local pages = require("source.browse").pages(function(page, done)
if page == 1 then done(books, nil, more); return end
return Client.storeAsync(node, page, done)
end, limit, groups, function(result, reason)
finished, active = true, nil
if cancelled then return end
if result then
for index = #result.data, limit + 1, -1 do result.data[index] = nil end
end
cb(result, reason)
end)
if not finished then active = pages end
end)
if not loaded then active = first end
return { cancel = function()
cancelled = true
if active then active.cancel() end
end }
end
---@param self KuaikanSource
---@param identity BookIdentity
---@param cb fun(page: table|nil, err: string|nil)
local function loadPage(self, identity, cb)
return Client.topicAsync(identity.stable_id, function(page, err)
if not page then cb(nil, err); return end
local chapters = Mapper.chapters(page.chapters)
if not chapters then cb(nil, _("漫画目录为空")); return end
if not Toc.put(self.id, identity.stable_id, chapters) then cb(nil, _("章节目录保存失败")); return end
page.chapters = chapters
page.book = Mapper.detail(page.info, page.nickname)
cb(page)
end)
end
function Source:getDetailAsync(identity, cb)
return loadPage(self, identity, function(page, err)
if page and page.book then cb(require("book.store").rememberDetail(page.book)); return end
local row = identity.book or require("book.books_db").get(self.id, identity.stable_id)
if row then cb(row); return end
cb(nil, err or _("请求失败"))
end)
end
function Source:loadTocAsync(identity, cb, force)
if not force then
local cached = Toc.read(self.id, identity.stable_id)
if cached and #cached > 0 and cached[1].toc_version == Mapper.TOC_VERSION then
return SourceBase.defer(cb, cached)
end
end
return loadPage(self, identity, function(page, err)
if not page then cb(nil, err); return end
cb(page.chapters)
end)
end
Source.refreshTocAsync = function(self, identity, cb)
return self:loadTocAsync(identity, cb, true)
end
---@param identity BookIdentity
---@param opts table
---@param toc BookChapter[]
---@return integer
local function startIndex(identity, opts, toc)
local idx = opts.chapter_idx
if not idx then
local pending = require("book.progress_db").get(identity.source_id, identity.stable_id)
idx = pending and (pending.chapter_idx or math.floor((pending.fraction or 0) * #toc) + 1)
end
return math.max(1, math.min(#toc, idx or 1))
end
---@param identity BookIdentity
---@param opts table|nil
---@param cb fun(path: string|nil, err: string|nil)
---@return { cancel: fun() }
function Source:openBookAsync(identity, opts, cb)
opts = opts or {}
local Chapter = require("moonsource_kuaikan.chapter")
local function finish(path, idx)
local ok, err = require("book.store").touch(path, identity, {
chapter_idx = idx,
book = identity.book,
})
cb(ok and path or nil, err)
end
local toc = Toc.read(identity.source_id, identity.stable_id)
if toc and #toc > 0 then
local idx = startIndex(identity, opts, toc)
local path = Chapter.existing(identity, toc[idx])
if path then return SourceBase.defer(finish, path, idx) end
end
if not require("ui/network/manager"):isConnected() then
return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi"))
end
local cancelled, active, dialog = false, nil, nil
local function closeDialog()
if dialog then dialog:close(); dialog = nil end
end
require("ui/uimanager"):nextTick(function()
if cancelled then return end
dialog = require("ui.themes.widgets.progress_dialog"):new{
title = identity.book and identity.book.title or identity.stable_id,
dismissable = false,
}
dialog:show()
dialog:set(_("正在准备漫画…"))
local loaded = false
local toc_job = self:loadTocAsync(identity, function(fresh, err)
loaded = true
active = nil
if cancelled then return end
if not fresh then closeDialog(); cb(nil, err); return end
local idx = startIndex(identity, opts, fresh)
local materialized = false
local chapter_job = Chapter.materializeAsync(identity, fresh[idx], function(done, total)
if dialog and total > 0 then dialog:update(_("正在准备漫画…"), done, total) end
end, function(path, materialize_err)
materialized = true
active = nil
closeDialog()
if cancelled then return end
if not path then cb(nil, materialize_err); return end
finish(path, idx)
end)
if not materialized then active = chapter_job end
end)
if not loaded then active = toc_job end
end)
return { cancel = function()
cancelled = true
if active then active.cancel() end
closeDialog()
end }
end
function Source:bookReviewsAsync(identity, cb)
return Client.commentsAsync(identity.stable_id, function(items, err, pages)
if not items then cb(nil, err); return end
cb({ items = items, pages = pages, title = _("话题页评论(首话)") })
end)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
return require("moonsource_kuaikan.chapter").prefetchAsync(identity, toc, from_idx, count, nil, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
local cancelled, active = false, nil
local loaded = false
local toc_job = self:loadTocAsync(identity, function(toc, err)
loaded = true
active = nil
if cancelled then return end
if not toc then cb(false, 0, err, 0, 0); return end
local from_idx, count = require("source.chapter").cacheRange(toc, range)
local finished = false
local cache_job = require("moonsource_kuaikan.chapter").prefetchAsync(identity, toc, from_idx, count, {
progress = on_progress,
interval_seconds = 1.5,
}, function(cached, total, failed, last_err)
finished, active = true, nil
if not cancelled then cb(failed == 0, cached, last_err, total, failed) end
end)
if not finished then active = cache_job end
end)
if not loaded then active = toc_job end
return { cancel = function()
cancelled = true
if active then active.cancel() end
end }
end
function Source:paragraphReviewsEnabled()
return require("source.review_setting").enabled(self.id)
end
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
return require("book.review_cache").pageAsync(identity, range, max_idx, function(done)
return require("source.with_chapter_uid").run(self, identity, _("目录为空"),
function(uid, finish)
return Client.commentPageAsync(uid, max_idx, function(items, err, _pages, page)
if not items then finish(nil, err); return end
for _idx, item in ipairs(items) do
if not item.id or item.id == "" or item.id == "0" then finish(nil, _("响应无效")); return end
item.content, item.replies = item.text, 0
item.time = item.time or ""
end
finish({ items = items, total = page.total, max_idx = page.max_idx, more = page.more })
end)
end, done)
end, cb)
end
function Source:chapterReviewHotspotsAsync(identity, cb)
return self:paragraphReviewPageAsync(identity, "chapter", 0, function(page, err)
if not page then cb(nil, err); return end
cb({ { range = "chapter", text = identity.book and identity.book.title or "",
total = page.total, badge = tostring(page.total), heading = _("章节评论") } })
end)
end
return Kuaikan
@@ -0,0 +1,113 @@
--[[--
快看腾讯滑块。浏览器只交验证凭据,手机号、密码、短信码和候选 Cookie 留在设备。
临时票据绑定本次输入与候选会话,五分钟截止,提交一次即收回。
@module moonsource_kuaikan.verify
--]]
local Ext = require("utils.extension")
local _ = require("l10n").get("moonsource_kuaikan")
---@class KuaikanVerification
---@field ticket string
---@field session KuaikanLogin
---@field submit (fun(captcha: table, cb: function))|nil
---@field callback fun(result: any, err: string|nil)
---@field expires integer
---@field dialog BookThemeQR|nil
---@field timeout function
---@field pending boolean|nil
---@field done boolean|nil
local Verification = {}
Verification.__index = Verification
---@type table<string, KuaikanVerification>
local sessions = {}
function Verification:cancel()
if self.done then return end
self.done = true
sessions[self.ticket] = nil
require("ui/uimanager"):unschedule(self.timeout)
self.session:cancel()
local dialog = self.dialog
self.dialog = nil
if dialog then dialog:close() end
self.submit = nil
end
function Verification:finish(result, err)
if self.done then return end
self:cancel()
self.callback(result, err)
end
---@param session KuaikanLogin
---@param submit fun(captcha: table, cb: function)
---@param cb fun(result: any, err: string|nil)
---@return KuaikanVerification
function Verification.new(session, submit, cb)
local self = setmetatable({
session = session, submit = submit, callback = cb,
ticket = require("utils.random").hex(24), expires = os.time() + 300,
}, Verification)
self.timeout = require("ui.guard").wrap("kuaikan verification timeout", function()
self:finish(nil, _("验证已过期,请重新发起验证"))
end)
sessions[self.ticket] = self
require("ui/uimanager"):scheduleIn(300, self.timeout)
self.dialog = Ext.call("web.open_page", "/kuaikan_verify.html#" .. self.ticket,
_("快看安全验证"), _("用同一 Wi-Fi 下的手机扫码完成安全验证;手机号、密码和短信码只在设备填写。"), {
close_callback = function() self:finish(nil, _("验证已取消")) end,
})
if not self.dialog then
self:finish(nil, _("无法打开远程验证,请先连接 Wi-Fi 并启用远程管理功能"))
end
return self
end
local function handle(method, action, params, cb)
local function reply(status, body)
cb(status, body, { "Cache-Control: no-store" })
end
if method ~= "POST" then return reply(405, { error = "Method Not Allowed" }) end
if action ~= "config" and action ~= "verify" then return reply(404, { error = "Not Found" }) end
local self = type(params.ticket) == "string" and sessions[params.ticket]
if not self or os.time() >= self.expires then
return reply(403, { error = _("验证已过期,请重新发起验证") })
end
if action == "config" then
return reply(200, {
appid = "2034681882", title = _("快看安全验证"), instruction = _("请完成下方安全验证"),
pending = _("正在提交验证…"), success = _("验证已提交,请回到设备查看结果。"),
failure = _("验证失败,请重新验证"), load_error = _("滑块加载失败,请检查网络后刷新网页"),
cancelled = _("验证已取消"), retry = _("重试"),
})
end
if type(params.captcha_ticket) ~= "string" or params.captcha_ticket == "" or #params.captcha_ticket > 4096
or params.captcha_ticket:match("^trerror_") or type(params.randstr) ~= "string"
or params.randstr == "" or #params.randstr > 256 then
return reply(400, { error = _("验证凭据无效") })
end
if self.pending then return reply(409, { error = _("正在提交验证…") }) end
self.pending = true
local submit = assert(self.submit, "active verification has no submission")
submit({ ticket = params.captcha_ticket, random = params.randstr }, function(result, err)
if self.done then return reply(403, { error = _("验证已过期,请重新发起验证") }) end
if os.time() >= self.expires then
self:finish(nil, _("验证已过期,请重新发起验证"))
return reply(403, { error = _("验证已过期,请重新发起验证") })
end
if result then reply(200, { ok = true })
else reply(400, { error = _("验证或登录失败,请回到设备查看并重试") }) end
self:finish(result, err)
end)
end
local dir = debug.getinfo(1, "S").source:sub(2):match("(.*/)")
Ext.add("web.routes", {
name = "kuaikan_verify", dir = dir .. "web",
assets = { "kuaikan_verify.html", "kuaikan_verify.js" },
public = { config = true, verify = true }, handle = handle,
})
return Verification
@@ -0,0 +1,25 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="referrer" content="no-referrer">
<title>月读</title>
<link rel="stylesheet" href="/style.css">
<style>
main{max-width:520px;margin:10vh auto;padding:24px}
.panel{padding:24px}#captcha{min-height:180px;margin:24px 0}
#status{overflow-wrap:anywhere;white-space:pre-line}button[hidden]{display:none}
</style>
</head>
<body>
<main><section class="panel">
<h1 id="title">月读</h1>
<p id="instruction"></p>
<div id="captcha"></div>
<p id="status" role="status" aria-live="polite"></p>
<button id="retry" type="button" hidden></button>
</section></main>
<script src="/kuaikan_verify.js"></script>
</body>
</html>
@@ -0,0 +1,98 @@
(async function () {
'use strict';
const ticket = location.hash.slice(1);
const status = document.getElementById('status');
const retry = document.getElementById('retry');
let messages, captcha, loading = true, submitting = false, done = false;
async function request(action, body) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 90000);
try {
const response = await fetch('/api/kuaikan_verify/' + action, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...body, ticket }),
signal: controller.signal,
});
const result = await response.json();
if (!response.ok) throw new Error(result.error || response.statusText);
return result;
} finally {
clearTimeout(timer);
}
}
function failed(error) {
status.textContent = error.message || messages.failure;
retry.hidden = false;
}
async function submit(result) {
if (done || submitting) return;
if (!result || result.ret !== 0 || result.errorCode || typeof result.ticket !== 'string'
|| !result.ticket || typeof result.randstr !== 'string' || !result.randstr
|| result.ticket.startsWith('trerror_')) {
failed(new Error(result && result.ret === 2 ? messages.cancelled : messages.failure));
return;
}
submitting = true;
retry.hidden = true;
status.textContent = messages.pending;
try {
await request('verify', { captcha_ticket: result.ticket, randstr: result.randstr });
done = true;
status.textContent = messages.success;
document.getElementById('captcha').hidden = true;
} catch (error) {
failed(error);
} finally {
submitting = false;
}
}
function loadScript() {
if (typeof window.TencentCaptcha === 'function') return Promise.resolve();
return new Promise((resolve, reject) => {
const script = document.createElement('script');
const timer = setTimeout(() => finish(messages.load_error), 20000);
function finish(error) {
clearTimeout(timer);
script.onload = script.onerror = null;
if (error) { script.remove(); reject(new Error(error)); }
else resolve();
}
script.src = 'https://turing.captcha.qcloud.com/TJCaptcha.js';
script.onload = () => finish(typeof window.TencentCaptcha === 'function' ? null : messages.load_error);
script.onerror = () => finish(messages.load_error);
document.head.appendChild(script);
});
}
async function load() {
await loadScript();
if (captcha) captcha.destroy();
document.getElementById('captcha').hidden = false;
document.getElementById('captcha').innerHTML = '';
captcha = new window.TencentCaptcha(document.getElementById('captcha'), messages.appid, submit, {
type: 'embed', userLanguage: 'zh-cn',
});
captcha.show();
}
retry.onclick = async () => {
if (done || loading || submitting) return;
loading = true;
retry.hidden = true;
status.textContent = '';
try { messages = await request('config', {}); await load(); }
catch (error) { failed(error); }
finally { loading = false; }
};
try {
messages = await request('config', {});
document.title = document.getElementById('title').textContent = messages.title;
document.getElementById('instruction').textContent = messages.instruction;
retry.textContent = messages.retry;
await load();
} catch (error) {
if (messages) failed(error);
else status.textContent = error.message;
} finally {
loading = false;
}
})();