✨ 初始提交:月读第三方书源插件集合
每个书源一个独立插件目录,含微信读书公众号订阅、书架导入等完整功能。 Co-authored-by: Copilot <[email protected]>
This commit is contained in:
commit
77c37bc89a
27 files changed
+4305
No files matched your search
@@ -0,0 +1,22 @@
|
||||
# 豆瓣阅读
|
||||
|
||||
| 能力 | 是否支持 | 备注 |
|
||||
| --- | --- | --- |
|
||||
| App 扫码与短信登录 | 支持 | 豆瓣阅读 App 扫码;短信支持国际区号,历史授权迁移交由官网确认 |
|
||||
| 浏览器登录与 Cookie 导入 | 支持 | 手动粘贴或浏览器扩展回传 |
|
||||
| 设备密码登录 | 不支持 | 未接入 |
|
||||
| 搜索与分类书城 | 支持 | 原创、出版动态分类、子分类及排序、资费和状态筛选 |
|
||||
| 书架拉取与分组 | 支持 | 官网分组可作为书库分类 |
|
||||
| 加入远端书架 | 支持 | 本地先生效,上传后回读确认 |
|
||||
| 移出远端书架 | 已实现,未实测 | 清缓存、留墓碑;远端确认后清记录 |
|
||||
| 目录与正文 | 支持 | 专栏按章;出版电子书按正文目录切章,免费内容可匿名读取 |
|
||||
| 已购正文 | 已实现,未实测 | 以官方阅读权限为准,不绕过购买 |
|
||||
| 章节与全本缓存 | 支持 | 兼容旧缓存,已缓存章节可离线续读和重开 |
|
||||
| 阅读进度同步 | 部分支持 | 专栏下行不能恢复最近章,上行持久化未确认;出版仅近似章首比例 |
|
||||
| 阅读时长同步 | 部分支持 | 上传本地会话,拉取累计及近 30 日时长;不把访问记录伪造为阅读会话 |
|
||||
| 个人笔记同步 | 不支持 | 未接个人划线、书签和笔记双向同步 |
|
||||
| 整书书评 | 部分支持 | 长短评首批预览;首页匿名,后续页需登录 |
|
||||
| 章评 | 部分支持 | 仅专栏章节;章末入口、分页和缓存,后续页需登录且未完成真实登录实测 |
|
||||
| 段评 | 支持 | 保留按段落 ID 定位的他人批注,与章评共存 |
|
||||
| 评论回复与写操作 | 不支持 | 未接回复分页、发评、点赞或删评 |
|
||||
| 账号切换 | 部分支持 | 同账号可续期;换号须先退出清理旧数据,未同步记录会丢失 |
|
||||
@@ -0,0 +1,5 @@
|
||||
local _ = require("gettext")
|
||||
return {
|
||||
fullname = _("月读书源:豆瓣读书"),
|
||||
description = _("给月读增加「豆瓣读书」书源。需要同时安装月读,与平台官方无关。"),
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
--[[--
|
||||
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
|
||||
--]]
|
||||
local WidgetContainer = require("ui/widget/container/widgetcontainer")
|
||||
|
||||
return WidgetContainer:extend{
|
||||
name = "moonsource_douban",
|
||||
is_doc_only = false,
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
--[[--
|
||||
月读第三方书源描述:豆瓣读书。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
|
||||
--]]
|
||||
|
||||
local function lazy(module)
|
||||
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
|
||||
end
|
||||
|
||||
return {
|
||||
api = 1,
|
||||
provides = { source = true },
|
||||
meta = function() return require("moonsource_douban.source").meta() end,
|
||||
new = function() return require("moonsource_douban.source").new() end,
|
||||
setting = lazy("moonsource_douban.setting"),
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
--[[--
|
||||
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
|
||||
|
||||
豆瓣阅读网页搜索和免费章节不需要登录。书架和已购正文要豆瓣阅读 App 扫码。
|
||||
|
||||
@module moonsource_douban._meta
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_douban")
|
||||
|
||||
return {
|
||||
id = "ext.douban",
|
||||
name = _("豆瓣阅读"),
|
||||
type = "chapter",
|
||||
description = _("豆瓣阅读书架与在线阅读"),
|
||||
abilities = { _("搜索与发现"), _("书架同步"), _("进度同步"), _("统计同步"), _("VIP 章节"), _("段评"), _("书评"), _("章节评论") },
|
||||
}
|
||||
@@ -0,0 +1,827 @@
|
||||
--[[--
|
||||
豆瓣阅读网页接口。
|
||||
|
||||
搜索、专栏目录和免费章节不登录也能读。正文密钥在匿名时是 SHA-256("anonymous")。
|
||||
登录是豆瓣阅读 App 扫码:先跟到 accounts.arkread.com 的授权页,再轮询二维码。
|
||||
扫码成功后授权页跳回 read.douban.com,会话是 Set-Cookie,解密密钥换成用户编号。
|
||||
|
||||
@module moonsource_douban.client
|
||||
--]]
|
||||
|
||||
local JSON = require("json")
|
||||
local Mapper = require("moonsource_douban.mapper")
|
||||
local Request = require("http.request")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_douban")
|
||||
|
||||
local Client = {}
|
||||
|
||||
local SOURCE_ID = "ext.douban"
|
||||
local READ_HOST = "read.douban.com"
|
||||
local ACCOUNT_HOST = "accounts.arkread.com"
|
||||
local READ = "https://" .. READ_HOST
|
||||
local ACCOUNT = "https://" .. ACCOUNT_HOST
|
||||
local LOGIN_URL = READ .. "/oidc/login?redir=https%3A%2F%2Fread.douban.com%2F"
|
||||
local LOGIN_EXPIRED = "豆瓣阅读登录已失效,请点「重新登录」,用豆瓣阅读 App 扫码。"
|
||||
|
||||
local active = { jars = {} }
|
||||
local anonymous = { jars = {}, public = true }
|
||||
local login_epoch = 0
|
||||
local article_cache = {}
|
||||
local loaded = false
|
||||
|
||||
local function remember(host, header, session)
|
||||
if type(host) ~= "string" or type(header) ~= "string" or header == "" then return end
|
||||
session = session or active
|
||||
local jar = session.jars[host] or {}
|
||||
session.jars[host] = jar
|
||||
local name, value = header:match("^%s*([^=;%s]+)=([^;]*)")
|
||||
if name then jar[name] = value ~= "" and value or nil end
|
||||
end
|
||||
|
||||
function Client.reset()
|
||||
active = { jars = {} }
|
||||
login_epoch = login_epoch + 1
|
||||
article_cache = {}
|
||||
loaded = false
|
||||
end
|
||||
|
||||
function Client.load()
|
||||
active = { jars = {} }
|
||||
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
|
||||
for pair in (cookie or ""):gmatch("[^;]+") do remember(READ_HOST, pair) end
|
||||
loaded = true
|
||||
end
|
||||
|
||||
---@param host string
|
||||
---@return string|nil
|
||||
function Client.cookieFor(host, session)
|
||||
local jar = (session or active).jars[host]
|
||||
if not jar then return nil end
|
||||
local names = {}
|
||||
for name in pairs(jar) do names[#names + 1] = name end
|
||||
table.sort(names)
|
||||
if #names == 0 then return nil end
|
||||
local parts = {}
|
||||
for _idx, name in ipairs(names) do parts[#parts + 1] = name .. "=" .. jar[name] end
|
||||
return table.concat(parts, "; ")
|
||||
end
|
||||
|
||||
---@return boolean
|
||||
function Client.loggedIn()
|
||||
local cfg = require("utils.settings").getSource(SOURCE_ID)
|
||||
return cfg.logged_in == true and type(cfg.user_id) == "string" and cfg.user_id ~= ""
|
||||
and type(cfg.cookie) == "string" and cfg.cookie ~= ""
|
||||
end
|
||||
|
||||
---@return string|nil
|
||||
function Client.userId()
|
||||
local cfg = require("utils.settings").getSource(SOURCE_ID)
|
||||
if cfg.logged_in == true and type(cfg.user_id) == "string" and cfg.user_id ~= "" then return cfg.user_id end
|
||||
return nil
|
||||
end
|
||||
|
||||
---@param user { id: string, name: string }
|
||||
local function persist(user, session)
|
||||
local settings = require("utils.settings")
|
||||
local cfg = settings.getSource(SOURCE_ID)
|
||||
cfg.cookie = Client.cookieFor(READ_HOST, session)
|
||||
cfg.user_id = user.id
|
||||
cfg.name = user.name
|
||||
cfg.logged_in = true
|
||||
settings.saveSource(SOURCE_ID)
|
||||
login_epoch = login_epoch + 1
|
||||
Client.load()
|
||||
active.read_csrf = session.read_csrf
|
||||
article_cache = {}
|
||||
end
|
||||
|
||||
---@param url string
|
||||
---@return string
|
||||
local function hostOf(url)
|
||||
return url:match("^https://([^/?#]+)")
|
||||
end
|
||||
|
||||
---@param code any
|
||||
---@return boolean
|
||||
local function httpOk(code)
|
||||
code = tonumber(code)
|
||||
return code ~= nil and code >= 200 and code < 300
|
||||
end
|
||||
|
||||
---@param host string
|
||||
---@param res table|nil
|
||||
---@return string|nil
|
||||
local function expired(host, res, cookie)
|
||||
if host == READ_HOST and tonumber(res and res.code) == 401
|
||||
and cookie == require("utils.settings").getSource(SOURCE_ID).cookie
|
||||
and Client.loggedIn() then
|
||||
return require("source.auth").expire(SOURCE_ID, _(LOGIN_EXPIRED))
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
---@param res table|nil
|
||||
local function absorb(host, res, session)
|
||||
if not res then return end
|
||||
for _idx, line in ipairs(Request.headerAll(res, "Set-Cookie")) do remember(host, line, session) end
|
||||
end
|
||||
|
||||
---@param method string
|
||||
---@param url string
|
||||
---@param body string|nil
|
||||
---@param content_type string|nil
|
||||
---@param cb fun(res: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function raw(method, url, body, content_type, cb, session)
|
||||
if not loaded then Client.load() end
|
||||
session = session or active
|
||||
local host = hostOf(url)
|
||||
if host ~= READ_HOST and host ~= ACCOUNT_HOST then
|
||||
return require("source.base").defer(cb, nil, _("登录跳转地址无效"))
|
||||
end
|
||||
local headers = { Accept = "application/json, text/html;q=0.8" }
|
||||
local cookie = not session.public and Client.cookieFor(host, session) or nil
|
||||
if cookie then headers.Cookie = cookie end
|
||||
if content_type then headers["Content-Type"] = content_type end
|
||||
if host == ACCOUNT_HOST and session.csrf then
|
||||
headers["X-CSRF-Token"] = session.csrf
|
||||
headers.Referer = ACCOUNT .. "/"
|
||||
end
|
||||
if host == READ_HOST and method ~= "GET" and session.read_csrf then headers["X-CSRF-Token"] = session.read_csrf end
|
||||
return Request.request({
|
||||
url = url,
|
||||
method = method,
|
||||
body = body,
|
||||
headers = headers,
|
||||
cache_ttl = 0,
|
||||
timeout = require("http.timeout").net(0.5),
|
||||
}, function(res, err)
|
||||
if session.cancelled then return end
|
||||
if not session.public then absorb(host, res, session) end
|
||||
if res and host == READ_HOST then
|
||||
local token = Mapper.readCsrf(res.body)
|
||||
if token then session.read_csrf = token end
|
||||
end
|
||||
if err or not res then cb(nil, err and tostring(err) or _("请求失败")); return end
|
||||
cb(res)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 登录后 read.douban.com 的写请求要带首页里的 CSRF。没有就先拉一次首页。
|
||||
---@param method string
|
||||
---@param url string
|
||||
---@param body string|nil
|
||||
---@param content_type string|nil
|
||||
---@param cb fun(res: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function send(method, url, body, content_type, cb)
|
||||
if not loaded then Client.load() end
|
||||
local session = active
|
||||
if method == "GET" or hostOf(url) ~= READ_HOST or session.read_csrf or not Client.loggedIn() then
|
||||
return raw(method, url, body, content_type, cb)
|
||||
end
|
||||
local cancelled, job = false, nil
|
||||
local handle = { cancel = function()
|
||||
cancelled = true
|
||||
if job and job.cancel then job.cancel() end
|
||||
end }
|
||||
local advanced = false
|
||||
local first = raw("GET", READ .. "/", nil, nil, function(res, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if session ~= active then cb(nil, _("登录状态已变化,请重试")); return end
|
||||
if not res or not httpOk(res.code) then cb(nil, err or _("请求失败")); return end
|
||||
if not session.read_csrf then cb(nil, _("请求失败")); return end
|
||||
job = raw(method, url, body, content_type, function(res2, err2)
|
||||
if not cancelled then cb(res2, err2) end
|
||||
end)
|
||||
end)
|
||||
if not advanced then job = first end
|
||||
return handle
|
||||
end
|
||||
|
||||
---@param method string
|
||||
---@param url string
|
||||
---@param payload table|nil
|
||||
---@param cb fun(wire: table|nil, err: string|nil, res: table|nil)
|
||||
---@return HttpJob
|
||||
local function jsonCall(method, url, payload, cb, public)
|
||||
local body, content_type
|
||||
if method ~= "GET" then
|
||||
body = payload and JSON.encode(payload) or "{}"
|
||||
content_type = "application/json"
|
||||
end
|
||||
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
|
||||
local function done(res, err)
|
||||
if not res then cb(nil, err or _("请求失败")); return end
|
||||
if not public and cookie ~= require("utils.settings").getSource(SOURCE_ID).cookie then
|
||||
cb(nil, _("登录状态已变化,请重试")); return
|
||||
end
|
||||
local reason = not public and expired(hostOf(url), res, cookie)
|
||||
if reason then cb(nil, reason, res); return end
|
||||
if not httpOk(res.code) then cb(nil, _("请求失败"), res); return end
|
||||
local ok, wire = pcall(JSON.decode, res.body or "")
|
||||
if not ok or type(wire) ~= "table" then cb(nil, _("请求失败"), res); return end
|
||||
cb(wire, nil, res)
|
||||
end
|
||||
if public then return raw(method, url, body, content_type, done, anonymous) end
|
||||
return send(method, url, body, content_type, done)
|
||||
end
|
||||
|
||||
---@param url string
|
||||
---@param hops integer
|
||||
---@param cb fun(body: string|nil, err: string|nil, final_url: string|nil)
|
||||
---@return HttpJob
|
||||
local function follow(url, hops, cb, session)
|
||||
local cancelled, job = false, nil
|
||||
local function step(current, count)
|
||||
local advanced = false
|
||||
local next_job = raw("GET", current, nil, nil, function(res, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not res then cb(nil, err or _("登录失败")); return end
|
||||
local code = tonumber(res.code)
|
||||
if code == 301 or code == 302 or code == 303 or code == 307 or code == 308 then
|
||||
if count >= 6 then cb(nil, _("登录失败")); return end
|
||||
local location = Request.header(res, "Location")
|
||||
if type(location) ~= "string" or location == "" then cb(nil, _("登录失败")); return end
|
||||
if location:sub(1, 2) == "//" then location = "https:" .. location
|
||||
elseif location:sub(1, 1) == "/" then location = current:match("^(https://[^/]+)") .. location end
|
||||
step(location, count + 1)
|
||||
return
|
||||
end
|
||||
if not httpOk(code) then cb(nil, _("登录失败")); return end
|
||||
cb(res.body or "", nil, current)
|
||||
end, session)
|
||||
if not advanced then job = next_job end
|
||||
end
|
||||
step(url, hops)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param keyword string
|
||||
---@param cb fun(books: Book[]|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.searchAsync(keyword, cb)
|
||||
return jsonCall("POST", READ .. "/j/search_v2", Mapper.searchBody(keyword), function(wire, err)
|
||||
if not wire then cb(nil, err); return end
|
||||
cb(Mapper.searchBooks(wire))
|
||||
end, true)
|
||||
end
|
||||
|
||||
function Client.categoriesAsync(cb)
|
||||
return raw("GET", READ .. "/category/", nil, nil, function(res, err)
|
||||
if not res or not httpOk(res.code) then cb(nil, err or _("请求失败")); return end
|
||||
cb(Mapper.categories(res.body))
|
||||
end, anonymous)
|
||||
end
|
||||
|
||||
function Client.catalogAsync(opts, page, cb)
|
||||
return jsonCall("POST", READ .. "/j/kind/", Mapper.catalogBody(opts, page), function(wire, err)
|
||||
if not wire then cb(nil, err); return end
|
||||
local books, reason = Mapper.searchBooks(wire)
|
||||
local total = tonumber(wire.total)
|
||||
if not books or not total or total < 0 then cb(nil, reason or _("响应无效")); return end
|
||||
cb(books, nil, #wire.list == 20 and page * 20 < total)
|
||||
end, true)
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param cb fun(target: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function accessAsync(works_id, cb, public)
|
||||
return jsonCall("POST", READ .. "/j/graphql", Mapper.worksBody(works_id, Mapper.ACCESS_HASH), function(wire, err)
|
||||
if not wire then cb(nil, err); return end
|
||||
local target = Mapper.reader(Mapper.readerUrl(wire))
|
||||
if not target then cb(nil, _("请求失败")); return end
|
||||
cb(target)
|
||||
end, public)
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param cb fun(book: Book|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.detailAsync(works_id, cb)
|
||||
local cancelled, job = false, nil
|
||||
local advanced = false
|
||||
local first = accessAsync(works_id, function(target, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not target then cb(nil, err); return end
|
||||
if target.kind == "column" then
|
||||
job = jsonCall("GET", READ .. "/j/column/" .. target.column_id .. "/", nil, function(wire, col_err)
|
||||
if cancelled then return end
|
||||
local row = wire and Mapper.columnBook(works_id, wire)
|
||||
if row then cb(row); return end
|
||||
cb(nil, col_err or _("请求失败"))
|
||||
end)
|
||||
return
|
||||
end
|
||||
job = jsonCall("POST", READ .. "/j/graphql", Mapper.worksBody(works_id, Mapper.INFO_HASH), function(wire, info_err)
|
||||
if cancelled then return end
|
||||
local row = wire and Mapper.infoBook(works_id, wire)
|
||||
if row then cb(row); return end
|
||||
cb(nil, info_err or _("请求失败"))
|
||||
end)
|
||||
end)
|
||||
if not advanced then job = first end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param aid string
|
||||
---@param cb fun(article: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.articleAsync(aid, cb)
|
||||
local cached = article_cache[aid]
|
||||
if cached then return require("source.base").defer(cb, cached) end
|
||||
local user_id = Client.userId()
|
||||
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
|
||||
return send("POST", READ .. "/j/article_v2/get_reader_data", "aid=" .. Text.urlEncode(tostring(aid)),
|
||||
"application/x-www-form-urlencoded", function(res, err)
|
||||
if not res then cb(nil, err or _("请求失败")); return end
|
||||
if cookie ~= require("utils.settings").getSource(SOURCE_ID).cookie then
|
||||
cb(nil, _("登录状态已变化,请重试")); return
|
||||
end
|
||||
local reason = expired(READ_HOST, res, cookie)
|
||||
if reason then cb(nil, reason); return end
|
||||
if not httpOk(res.code) then cb(nil, _("请求失败")); return end
|
||||
local ok, wire = pcall(JSON.decode, res.body or "")
|
||||
if not ok or type(wire) ~= "table" then cb(nil, _("请求失败")); return end
|
||||
if wire.r and tonumber(wire.r) ~= 0 then
|
||||
cb(nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("请求失败"))
|
||||
return
|
||||
end
|
||||
if type(wire.data) ~= "string" or wire.data == "" then cb(nil, _("正文为空")); return end
|
||||
local article, decrypt_err = Mapper.decrypt(wire.data, user_id)
|
||||
if not article then cb(nil, decrypt_err); return end
|
||||
article_cache[tostring(aid)] = article
|
||||
cb(article)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param cb fun(chapters: BookChapter[]|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.tocAsync(works_id, cb)
|
||||
local cancelled, job = false, nil
|
||||
local advanced = false
|
||||
local first = accessAsync(works_id, function(target, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not target then cb(nil, err); return end
|
||||
if target.kind == "column" then
|
||||
job = jsonCall("GET", READ .. "/j/column/" .. target.column_id .. "/", nil, function(wire, col_err)
|
||||
if cancelled then return end
|
||||
if not wire then cb(nil, col_err); return end
|
||||
cb(Mapper.columnChapters(wire))
|
||||
end)
|
||||
return
|
||||
end
|
||||
job = Client.articleAsync(target.aid, function(article, article_err)
|
||||
if cancelled then return end
|
||||
if not article then cb(nil, article_err); return end
|
||||
cb(Mapper.ebookChapters(article, target.aid))
|
||||
end)
|
||||
end)
|
||||
if not advanced then job = first end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
--- 本章这些段落上的他人批注。正文段落编号用逗号拼进表单。
|
||||
---@param aid string
|
||||
---@param paragraph_ids string[]
|
||||
---@param cb fun(rows: table|nil, err: string|nil)
|
||||
---@return HttpJob|{ cancel: fun() }
|
||||
function Client.annotationsAsync(aid, paragraph_ids, cb)
|
||||
if type(paragraph_ids) ~= "table" or paragraph_ids[1] == nil then
|
||||
return require("source.base").defer(cb, {})
|
||||
end
|
||||
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
|
||||
local body = "paragraph_ids=" .. Text.urlEncode(table.concat(paragraph_ids, ","))
|
||||
local url = READ .. "/j/article_v2/" .. Text.urlEncode(tostring(aid)) .. "/annotations_by_paragraphs"
|
||||
return send("POST", url, body, "application/x-www-form-urlencoded", function(res, err)
|
||||
if not res then cb(nil, err or _("请求失败")); return end
|
||||
local reason = expired(READ_HOST, res, cookie)
|
||||
if reason then cb(nil, reason); return end
|
||||
if not httpOk(res.code) then cb(nil, _("请求失败")); return end
|
||||
local ok, wire = pcall(JSON.decode, res.body or "")
|
||||
if not ok or type(wire) ~= "table" or (next(wire) ~= nil and wire[1] == nil) then
|
||||
cb(nil, _("响应无效")); return
|
||||
end
|
||||
cb(wire)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param aid string
|
||||
---@param start_pid number|nil
|
||||
---@param end_pid number|nil
|
||||
---@param cb fun(text: string|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.textAsync(aid, start_pid, end_pid, cb)
|
||||
return Client.articleAsync(aid, function(article, err)
|
||||
if not article then cb(nil, err); return end
|
||||
local text = Mapper.blocksText(article, start_pid, end_pid)
|
||||
if text == "" then cb(nil, _("正文为空")); return end
|
||||
cb(text)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param cb fun(books: Book[]|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.shelfAsync(cb)
|
||||
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
local cancelled, job = false, nil
|
||||
local function loadWorks(ids, groups)
|
||||
job = jsonCall("POST", READ .. "/j/graphql", Mapper.shelfWorksBody(ids), function(detail, err)
|
||||
if cancelled then return end
|
||||
if not detail then cb(nil, err); return end
|
||||
cb(Mapper.shelfWorks(detail, groups, ids))
|
||||
end)
|
||||
end
|
||||
local function loadGroupDetails(ids, folder_ids)
|
||||
local advanced = false
|
||||
local pending = jsonCall("POST", READ .. "/j/graphql", {
|
||||
variables = { folderIds = folder_ids, userId = Client.userId() },
|
||||
extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SHELF_FOLDERS_HASH } },
|
||||
}, function(wire, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not wire then cb(nil, err); return end
|
||||
local groups, group_err = Mapper.shelfGroups(wire, folder_ids)
|
||||
if not groups then cb(nil, group_err); return end
|
||||
loadWorks(ids, groups)
|
||||
end)
|
||||
if not advanced then job = pending end
|
||||
end
|
||||
local function loadGroups(ids)
|
||||
local advanced = false
|
||||
local pending = jsonCall("GET", READ .. "/j/bookshelf/folder/", nil, function(wire, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not wire then cb(nil, err); return end
|
||||
local folder_ids, folder_err = Mapper.folderIds(wire)
|
||||
if not folder_ids then cb(nil, folder_err); return end
|
||||
if #folder_ids == 0 then loadWorks(ids, {}); return end
|
||||
loadGroupDetails(ids, folder_ids)
|
||||
end)
|
||||
if not advanced then job = pending end
|
||||
end
|
||||
local advanced = false
|
||||
local first = jsonCall("GET", READ .. "/j/bookshelf/", nil, function(wire, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not wire then cb(nil, err); return end
|
||||
local ids, id_err = Mapper.shelfIds(wire)
|
||||
if not ids then cb(nil, id_err); return end
|
||||
if #ids == 0 then cb({}); return end
|
||||
if require("source.category_setting").enabled(SOURCE_ID) then loadGroups(ids)
|
||||
else loadWorks(ids) end
|
||||
end)
|
||||
if not advanced then job = first end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param method string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function shelfWrite(works_id, method, cb)
|
||||
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
return jsonCall(method, READ .. "/j/bookshelf/", { worksIds = { tostring(works_id) } }, function(wire, err)
|
||||
if not wire then cb(nil, err or (method == "DELETE" and _("移出豆瓣阅读书架失败") or _("加入豆瓣阅读书架失败"))); return end
|
||||
cb(true)
|
||||
end)
|
||||
end
|
||||
|
||||
function Client.addAsync(works_id, cb)
|
||||
return shelfWrite(works_id, "POST", cb)
|
||||
end
|
||||
|
||||
function Client.removeAsync(works_id, cb)
|
||||
return shelfWrite(works_id, "DELETE", cb)
|
||||
end
|
||||
|
||||
--- 进度和阅读时长的回包没有字段可用,2xx 就算写上了。
|
||||
---@param url string
|
||||
---@param body string
|
||||
---@param content_type string
|
||||
---@param fail string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
local function write(url, body, content_type, fail, cb)
|
||||
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
local cookie = require("utils.settings").getSource(SOURCE_ID).cookie
|
||||
return send("POST", url, body, content_type, function(res, err)
|
||||
if not res then cb(nil, err or fail); return end
|
||||
local reason = expired(READ_HOST, res, cookie)
|
||||
if reason then cb(nil, reason); return end
|
||||
if not httpOk(res.code) then cb(nil, fail); return end
|
||||
if res.body and res.body ~= "" then
|
||||
local ok, wire = pcall(JSON.decode, res.body)
|
||||
if not ok or type(wire) ~= "table"
|
||||
or (wire.r ~= nil and wire.r ~= 0 and wire.r ~= false) then
|
||||
cb(nil, fail)
|
||||
return
|
||||
end
|
||||
end
|
||||
cb(true)
|
||||
end)
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param cb fun(mark: { paragraph_id: string }|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.progressAsync(works_id, cb)
|
||||
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
return jsonCall("GET", READ .. "/j/progress/?works_id=" .. tostring(works_id), nil, function(wire, err)
|
||||
if not wire then cb(nil, err); return end
|
||||
local mark, empty = Mapper.progress(wire)
|
||||
if empty then cb(nil); return end
|
||||
if not mark then cb(nil, _("请求失败")); return end
|
||||
cb(mark)
|
||||
end)
|
||||
end
|
||||
|
||||
--- 上传正文段落及分段索引;百分比只在整本(非专栏)时带上,和网页一致。
|
||||
---@param works_id string
|
||||
---@param paragraph_id string
|
||||
---@param idx integer
|
||||
---@param total integer
|
||||
---@param with_percent boolean
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
---@param position table|nil 官网正文分段索引
|
||||
---@return HttpJob
|
||||
function Client.putProgressAsync(works_id, paragraph_id, idx, total, with_percent, cb, position)
|
||||
local count = total > 0 and total or 1
|
||||
local payload = {
|
||||
works_id = tonumber(works_id) or works_id,
|
||||
paragraph_id = tonumber(paragraph_id) or paragraph_id,
|
||||
paragraph_offset = 0,
|
||||
part_sequence = position and position.part_sequence or idx - 1,
|
||||
part_paragraph_sequence = position and position.part_paragraph_sequence or 0,
|
||||
}
|
||||
if with_percent then payload.percentage = math.floor((idx - 1) / count * 100) end
|
||||
return write(READ .. "/j/progress/", Text.formEncode(payload),
|
||||
"application/x-www-form-urlencoded", _("豆瓣阅读进度保存失败"), cb)
|
||||
end
|
||||
|
||||
--- 阅读时长。网页把会话数组原样 POST 到 /j/reading_time,时间是 ISO。
|
||||
---@param sessions table[]
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.pushReadingAsync(sessions, cb)
|
||||
return write(READ .. "/j/reading_time", JSON.encode(sessions),
|
||||
"application/json", _("豆瓣阅读阅读记录保存失败"), cb)
|
||||
end
|
||||
|
||||
function Client.readingStatsAsync(begin_date, cb)
|
||||
if not Client.loggedIn() then return require("source.base").defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
return jsonCall("POST", READ .. "/j/graphql", {
|
||||
variables = { userId = Client.userId(), beginDate = begin_date },
|
||||
extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.READING_TIME_HASH } },
|
||||
}, cb)
|
||||
end
|
||||
|
||||
---@class DoubanLogin
|
||||
---@field jars table
|
||||
---@field epoch integer
|
||||
---@field cancelled boolean|nil
|
||||
---@field csrf string|nil
|
||||
---@field read_csrf string|nil
|
||||
local Login = {}
|
||||
Login.__index = Login
|
||||
|
||||
---@param cookie string|nil
|
||||
---@return DoubanLogin
|
||||
function Client.newLogin(cookie)
|
||||
local session = setmetatable({ jars = {}, epoch = login_epoch }, Login)
|
||||
for pair in (cookie or ""):gmatch("[^;]+") do remember(READ_HOST, pair, session) end
|
||||
return session
|
||||
end
|
||||
|
||||
function Login:cancel()
|
||||
self.cancelled = true
|
||||
end
|
||||
|
||||
function Login:commit(user)
|
||||
if self.cancelled or self.epoch ~= login_epoch then return nil, _("登录状态已变化,请重试") end
|
||||
if not Client.cookieFor(READ_HOST, self) then return nil, _("登录失败") end
|
||||
local cfg = require("utils.settings").getSource(SOURCE_ID)
|
||||
if (cfg.logged_in or cfg.cookie or cfg.user_id) and cfg.user_id ~= user.id then
|
||||
local cleared = require("source.logout").clear(SOURCE_ID, function()
|
||||
cfg.cookie, cfg.user_id, cfg.name, cfg.logged_in = nil, nil, nil, nil
|
||||
require("utils.settings").saveSource(SOURCE_ID)
|
||||
Client.reset()
|
||||
end)
|
||||
if not cleared then return nil, _("准备本地同步失败") end
|
||||
end
|
||||
persist(user, self)
|
||||
return true
|
||||
end
|
||||
|
||||
function Login:checkCookieAsync(cb)
|
||||
return follow(READ .. "/", 0, function(html, err, final_url)
|
||||
if self.cancelled or self.epoch ~= login_epoch then cb(false, _("登录状态已变化,请重试")); return end
|
||||
local user = html and hostOf(final_url) == READ_HOST and Mapper.user(html)
|
||||
if not user then cb(false, err or _("登录失败")); return end
|
||||
cb(true, nil, user)
|
||||
end, self)
|
||||
end
|
||||
|
||||
---@param cb fun(authorize: string|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Login:beginAsync(cb)
|
||||
return follow(LOGIN_URL, 0, function(html, err, authorize)
|
||||
if not html then cb(nil, err or _("登录失败")); return end
|
||||
self.csrf = Mapper.csrf(html)
|
||||
if not self.csrf or hostOf(authorize) ~= ACCOUNT_HOST then cb(nil, _("登录失败")); return end
|
||||
self.authorize = authorize
|
||||
cb(authorize)
|
||||
end, self)
|
||||
end
|
||||
|
||||
local function accountResponse(res, err)
|
||||
if not res then return nil, err or _("请求失败") end
|
||||
local ok, wire = pcall(JSON.decode, res.body or "")
|
||||
if not httpOk(res.code) then
|
||||
if ok and type(wire) == "table" and type(wire.message) == "string" and wire.message ~= "" then
|
||||
return nil, wire.message
|
||||
end
|
||||
return nil, _("请求失败")
|
||||
end
|
||||
if not ok or type(wire) ~= "table" then return nil, _("响应无效") end
|
||||
return wire
|
||||
end
|
||||
|
||||
---@param phone string 国际区号与手机号,例如 +86…
|
||||
---@param cb fun(retry_after: number|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Login:sendPhoneCodeAsync(phone, cb)
|
||||
return raw("POST", ACCOUNT .. "/oidc/phone/verify_code", JSON.encode({ phone_number = phone }),
|
||||
"application/json", function(res, err)
|
||||
local wire, reason = accountResponse(res, err)
|
||||
if not wire then cb(nil, reason); return end
|
||||
if not (type(wire.retry_after) == "number" and wire.retry_after >= 0 and wire.retry_after < math.huge) then
|
||||
cb(nil, _("响应无效")); return
|
||||
end
|
||||
cb(wire.retry_after)
|
||||
end, self)
|
||||
end
|
||||
|
||||
---@param phone string
|
||||
---@param code string
|
||||
---@param cb fun(user: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Login:verifyPhoneAsync(phone, code, cb)
|
||||
local cancelled, job, advanced = false, nil, false
|
||||
local first = raw("POST", ACCOUNT .. "/oidc/phone/verify", JSON.encode({ phone_number = phone, code = code }),
|
||||
"application/json", function(res, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
local wire, reason = accountResponse(res, err)
|
||||
if not wire then cb(nil, reason); return end
|
||||
if type(wire.transfer_info) == "table" then
|
||||
cb(nil, _("此账号需要在豆瓣阅读官网确认历史数据授权,完成后再登录")); return
|
||||
end
|
||||
job = self:finishQrAsync(self.authorize, function(user, finish_err)
|
||||
if not cancelled then cb(user, finish_err) end
|
||||
end)
|
||||
end, self)
|
||||
if not advanced then job = first end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param cb fun(ticket: { qr: string, code: string, authorize: string, expires_in: number }|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Login:beginQrAsync(cb)
|
||||
local cancelled, job = false, nil
|
||||
local advanced = false
|
||||
local first = self:beginAsync(function(authorize, err)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not authorize then cb(nil, err or _("获取二维码失败")); return end
|
||||
job = raw("POST", ACCOUNT .. "/oidc/qrcode/generate", nil, "application/json", function(res, gen_err)
|
||||
if cancelled then return end
|
||||
if not res or not httpOk(res.code) then cb(nil, gen_err or _("获取二维码失败")); return end
|
||||
local decoded, wire = pcall(JSON.decode, res.body or "")
|
||||
if not decoded then cb(nil, _("获取二维码失败")); return end
|
||||
local ticket = wire and Mapper.qr(wire, ACCOUNT)
|
||||
if not ticket or type(authorize) ~= "string" then cb(nil, gen_err or _("获取二维码失败")); return end
|
||||
cb({ qr = ticket.qr, code = ticket.code, authorize = authorize, expires_in = ticket.expires_in })
|
||||
end, self)
|
||||
end)
|
||||
if not advanced then job = first end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param code string
|
||||
---@param cb fun(kind: string|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Login:qrStatusAsync(code, cb)
|
||||
return raw("POST", ACCOUNT .. "/oidc/qrcode/status", JSON.encode({ code = code }), "application/json", function(res, err)
|
||||
if not res or not httpOk(res.code) then cb(nil, err or _("登录失败")); return end
|
||||
local decoded, wire = pcall(JSON.decode, res.body or "")
|
||||
local kind = decoded and Mapper.qrStatus(wire)
|
||||
if not kind then cb(nil, _("登录失败")); return end
|
||||
cb(kind)
|
||||
end, self)
|
||||
end
|
||||
|
||||
---@param authorize string
|
||||
---@param cb fun(user: { id: string, name: string }|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Login:finishQrAsync(authorize, cb)
|
||||
local cancelled, job = false, nil
|
||||
local advanced = false
|
||||
local first = follow(authorize, 0, function(html, err, final_url)
|
||||
advanced = true
|
||||
if cancelled then return end
|
||||
if not html then cb(nil, err or _("登录失败")); return end
|
||||
local user = Mapper.user(html)
|
||||
if user and hostOf(final_url) == READ_HOST then
|
||||
local ok, reason = self:commit(user)
|
||||
cb(ok and user or nil, reason)
|
||||
return
|
||||
end
|
||||
if hostOf(final_url) == READ_HOST then cb(nil, _("登录失败")); return end
|
||||
job = follow(READ .. "/", 0, function(home, home_err)
|
||||
if cancelled then return end
|
||||
user = home and Mapper.user(home)
|
||||
if not user then cb(nil, home_err or _("登录失败")); return end
|
||||
local ok, reason = self:commit(user)
|
||||
cb(ok and user or nil, reason)
|
||||
end, self)
|
||||
end, self)
|
||||
if not advanced then job = first end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param chapter_id string|nil
|
||||
---@param offset integer
|
||||
---@param cb fun(page: table|nil, err: string|nil)
|
||||
---@return HttpJob
|
||||
function Client.communityAsync(works_id, chapter_id, offset, cb)
|
||||
if offset > 0 and not Client.loggedIn() then
|
||||
return require("source.base").defer(cb, nil, _("请先登录豆瓣阅读"))
|
||||
end
|
||||
local cancelled, job, pending = false, nil, true
|
||||
local function fetch(column_id)
|
||||
local body = Mapper.worksBody(works_id,
|
||||
"sha256:ec47b1cca2876392e72ca83dd4d59b12e2e27b72366d2c1b7a8e9ff672f4bb7c")
|
||||
if chapter_id then
|
||||
body.extensions.persistedQuery.sha256Hash =
|
||||
"sha256:161b3ceea6f04246919461367c6c071d62020836125a9ba6c42022295717a30a"
|
||||
body.variables.worksId = nil
|
||||
body.variables.columnId = column_id
|
||||
body.variables.chapterId = chapter_id
|
||||
end
|
||||
body.variables.start, body.variables.limit = offset, 20
|
||||
body.variables.sort, body.variables.isAdmin = "TIME_DESC", false
|
||||
return jsonCall("POST", READ .. "/j/graphql", body, function(wire, err)
|
||||
if cancelled then return end
|
||||
if not wire then cb(nil, err); return end
|
||||
cb(Mapper.communityPage(wire, offset, chapter_id))
|
||||
end, offset == 0)
|
||||
end
|
||||
if not chapter_id then return fetch() end
|
||||
local first = accessAsync(works_id, function(target, err)
|
||||
pending = false
|
||||
if cancelled then return end
|
||||
if not target then cb(nil, err); return end
|
||||
if target.kind ~= "column" then
|
||||
cb({ items = {}, total = 0, more = false, max_idx = offset, unsupported = true })
|
||||
return
|
||||
end
|
||||
job = fetch(target.column_id)
|
||||
end, true)
|
||||
if pending then job = first end
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
return Client
|
||||
@@ -0,0 +1,62 @@
|
||||
return {
|
||||
["书评预览"] = "Book comment previews",
|
||||
["豆瓣阅读手机号登录"] = "Douban Read SMS sign-in",
|
||||
["国际区号"] = "Country calling code",
|
||||
["请输入有效的手机号和国际区号"] = "Enter a valid phone number and country calling code.",
|
||||
["请稍后再获取验证码"] = "Please wait before requesting another code.",
|
||||
["验证码已发送"] = "Verification code sent",
|
||||
["正在获取验证码…"] = "Requesting a verification code…",
|
||||
["正在处理,请稍候"] = "Processing, please wait.",
|
||||
["请先获取该手机号的验证码,再填写验证码登录"] = "Request a code for this phone number, then enter it to sign in.",
|
||||
["登录前请阅读并同意豆瓣阅读使用协议、隐私政策和社区指导原则"] = "Before signing in, read and agree to the Douban Read terms, privacy policy and community guidelines.",
|
||||
["同意并登录"] = "Agree and sign in",
|
||||
["此账号需要在豆瓣阅读官网确认历史数据授权,完成后再登录"] = "This account requires authorization for historical data on the official Douban Read website. Complete that step before signing in here.",
|
||||
["豆瓣阅读登录 Cookie"] = "Douban Read login Cookie",
|
||||
["切换豆瓣阅读账号前,请先退出旧账号;退出会清理该源的本地书架和阅读记录"] = "Sign out of the old Douban Read account before switching accounts. Signing out clears this source's local shelf and reading records.",
|
||||
["登录状态已变化,请重试"] = "The login session changed. Please retry.",
|
||||
["登录跳转地址无效"] = "Invalid login redirect",
|
||||
["原创"] = "Original",
|
||||
["销量"] = "Sales",
|
||||
["好评"] = "Top rated",
|
||||
["价格最低"] = "Lowest price",
|
||||
["豆瓣高分"] = "Douban rating",
|
||||
["章节评论"] = "Chapter comments",
|
||||
["请先登录豆瓣阅读"] = "Please sign in to Douban Read first",
|
||||
["获取验证码"] = "Get code",
|
||||
["豆瓣阅读"] = "Douban Read",
|
||||
["豆瓣阅读书架与在线阅读"] = "Douban Read shelf and online reading",
|
||||
["豆瓣阅读扫码登录"] = "Douban Read QR sign-in",
|
||||
["用豆瓣阅读 App 扫一扫"] = "Scan with the Douban Read app",
|
||||
["打开豆瓣阅读 App,扫屏幕上的二维码"] = "Open the Douban Read app and scan the QR code",
|
||||
["豆瓣阅读账号"] = "Douban Read account",
|
||||
["未登录豆瓣阅读"] = "Not signed in to Douban Read",
|
||||
["豆瓣阅读目录为空"] = "Douban Read chapter list is empty",
|
||||
["豆瓣阅读登录已失效,请点「重新登录」,用豆瓣阅读 App 扫码。"] = "Douban Read sign-in has expired. Tap Sign in again and scan with the Douban Read app.",
|
||||
["确定退出豆瓣阅读账号?"] = "Sign out of Douban Read?",
|
||||
["豆瓣阅读书架数据无法识别"] = "Douban Read shelf data was not recognized",
|
||||
["移出豆瓣阅读书架失败"] = "Could not remove the book from the Douban Read shelf",
|
||||
["加入豆瓣阅读书架失败"] = "Could not add the book to the Douban Read shelf",
|
||||
["豆瓣阅读进度保存失败"] = "Could not save the Douban Read position",
|
||||
["豆瓣阅读阅读记录保存失败"] = "Could not save the Douban Read reading time",
|
||||
["缺少豆瓣阅读章节位置"] = "Missing the Douban Read chapter position",
|
||||
["正文为空"] = "Chapter text is empty",
|
||||
["正文解密失败"] = "Could not decrypt the chapter",
|
||||
["手机号验证码登录"] = "Sign in with an SMS code",
|
||||
["本章未购买"] = "This chapter has not been purchased",
|
||||
["出版"] = "Published",
|
||||
["价格"] = "Price",
|
||||
["免费"] = "Free",
|
||||
["付费"] = "Paid",
|
||||
["连载中"] = "Ongoing",
|
||||
["已完结"] = "Completed",
|
||||
["未登录 · 点此扫码"] = "Not signed in · tap to scan",
|
||||
["正在登录…"] = "Signing in…",
|
||||
["章节目录保存失败"] = "Failed to save chapter list",
|
||||
["手机号"] = "Phone number",
|
||||
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header",
|
||||
["VIP 章节"] = "VIP chapters",
|
||||
["书架同步"] = "Shelf sync",
|
||||
["搜索与发现"] = "Search and discover",
|
||||
["统计同步"] = "Statistics sync",
|
||||
["进度同步"] = "Progress sync",
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
return {
|
||||
["书评预览"] = "書評預覽",
|
||||
["豆瓣阅读手机号登录"] = "豆瓣閱讀手機號碼登入",
|
||||
["国际区号"] = "國際區碼",
|
||||
["请输入有效的手机号和国际区号"] = "請輸入有效的手機號碼和國際區碼",
|
||||
["请稍后再获取验证码"] = "請稍後再取得驗證碼",
|
||||
["验证码已发送"] = "驗證碼已發送",
|
||||
["正在获取验证码…"] = "正在取得驗證碼…",
|
||||
["正在处理,请稍候"] = "正在處理,請稍候",
|
||||
["请先获取该手机号的验证码,再填写验证码登录"] = "請先取得該手機號碼的驗證碼,再填寫驗證碼登入",
|
||||
["登录前请阅读并同意豆瓣阅读使用协议、隐私政策和社区指导原则"] = "登入前請閱讀並同意豆瓣閱讀使用協議、隱私政策和社群指導原則",
|
||||
["同意并登录"] = "同意並登入",
|
||||
["此账号需要在豆瓣阅读官网确认历史数据授权,完成后再登录"] = "此帳號需要在豆瓣閱讀官網確認歷史資料授權,完成後再登入",
|
||||
["豆瓣阅读登录 Cookie"] = "豆瓣閱讀登入 Cookie",
|
||||
["切换豆瓣阅读账号前,请先退出旧账号;退出会清理该源的本地书架和阅读记录"] = "切換豆瓣閱讀帳號前,請先登出舊帳號;登出會清理此書源的本機書架和閱讀記錄",
|
||||
["登录状态已变化,请重试"] = "登入狀態已改變,請重試",
|
||||
["登录跳转地址无效"] = "登入重新導向網址無效",
|
||||
["原创"] = "原創",
|
||||
["销量"] = "銷量",
|
||||
["好评"] = "好評",
|
||||
["价格最低"] = "價格最低",
|
||||
["豆瓣高分"] = "豆瓣高分",
|
||||
["章节评论"] = "章節評論",
|
||||
["请先登录豆瓣阅读"] = "請先登入豆瓣閱讀",
|
||||
["获取验证码"] = "取得驗證碼",
|
||||
["豆瓣阅读"] = "豆瓣閱讀",
|
||||
["豆瓣阅读书架与在线阅读"] = "豆瓣閱讀書架與線上閱讀",
|
||||
["豆瓣阅读扫码登录"] = "豆瓣閱讀掃碼登入",
|
||||
["用豆瓣阅读 App 扫一扫"] = "用豆瓣閱讀 App 掃一掃",
|
||||
["打开豆瓣阅读 App,扫屏幕上的二维码"] = "打開豆瓣閱讀 App,掃螢幕上的二維碼",
|
||||
["豆瓣阅读账号"] = "豆瓣閱讀帳號",
|
||||
["未登录豆瓣阅读"] = "未登入豆瓣閱讀",
|
||||
["豆瓣阅读目录为空"] = "豆瓣閱讀目錄為空",
|
||||
["豆瓣阅读登录已失效,请点「重新登录」,用豆瓣阅读 App 扫码。"] = "豆瓣閱讀登入已失效,請點「重新登入」,用豆瓣閱讀 App 掃碼。",
|
||||
["确定退出豆瓣阅读账号?"] = "確定退出豆瓣閱讀帳號?",
|
||||
["豆瓣阅读书架数据无法识别"] = "豆瓣閱讀書架資料無法識別",
|
||||
["移出豆瓣阅读书架失败"] = "移出豆瓣閱讀書架失敗",
|
||||
["加入豆瓣阅读书架失败"] = "加入豆瓣閱讀書架失敗",
|
||||
["豆瓣阅读进度保存失败"] = "豆瓣閱讀進度保存失敗",
|
||||
["豆瓣阅读阅读记录保存失败"] = "豆瓣閱讀閱讀記錄保存失敗",
|
||||
["缺少豆瓣阅读章节位置"] = "缺少豆瓣閱讀章節位置",
|
||||
["正文为空"] = "正文為空",
|
||||
["正文解密失败"] = "正文解密失敗",
|
||||
["手机号验证码登录"] = "手機號碼驗證碼登入",
|
||||
["本章未购买"] = "本章未購買",
|
||||
["出版"] = "出版",
|
||||
["价格"] = "價格",
|
||||
["免费"] = "免費",
|
||||
["付费"] = "付費",
|
||||
["连载中"] = "連載中",
|
||||
["已完结"] = "已完結",
|
||||
["未登录 · 点此扫码"] = "未登入 · 點此掃碼",
|
||||
["正在登录…"] = "正在登入…",
|
||||
["章节目录保存失败"] = "章節目錄儲存失敗",
|
||||
["手机号"] = "手機號碼",
|
||||
["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie",
|
||||
["VIP 章节"] = "VIP 章節",
|
||||
["书架同步"] = "書架同步",
|
||||
["搜索与发现"] = "搜尋與發現",
|
||||
["统计同步"] = "統計同步",
|
||||
["进度同步"] = "進度同步",
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
return function()
|
||||
local copy = {}
|
||||
for k, v in pairs(require("moonsource_douban._meta")) do copy[k] = v end
|
||||
return copy
|
||||
end
|
||||
@@ -0,0 +1,813 @@
|
||||
--[[--
|
||||
豆瓣阅读网页响应 → 领域对象。纯函数,不发请求。
|
||||
|
||||
搜索和作品查询是持久化 GraphQL:请求里只有 sha256,没有查询文本。
|
||||
正文是 Base64 后的 AES-256-CBC。末尾 16 字节是 IV,再往前的密文才解密,最后 13 字节丢掉。
|
||||
密钥是 SHA-256("anonymous"),登录后换成 SHA-256(用户编号)。
|
||||
|
||||
@module moonsource_douban.mapper
|
||||
--]]
|
||||
|
||||
local Aes = require("crypto.aes")
|
||||
local CategorySetting = require("source.category_setting")
|
||||
local JSON = require("json")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_douban")
|
||||
|
||||
local Mapper = {}
|
||||
|
||||
local SOURCE_ID = "ext.douban"
|
||||
|
||||
Mapper.TOC_VERSION = 2
|
||||
Mapper.SEARCH_HASH = "sha256:92911ffc68782f44a56764094edc0068f283c29fb447277f8ed2911af6bbd0a0"
|
||||
Mapper.ACCESS_HASH = "sha256:bf9257d4f673ee55c4ef0fbf7f495a4cf1fd972048ef4a823d92f40636c36f25"
|
||||
Mapper.INFO_HASH = "sha256:2ba0b5cafe47036cf931fcf749803c0fed974b448cd479e48fc35edd75e540a7"
|
||||
--- 书架页先拿编号,再用这条查询补 title / author / cover。
|
||||
Mapper.SHELF_WORKS_HASH = "sha256:d9cff923ff4ed25849b6dc0d493b027533c4f252647107f2226de11b78f7b831"
|
||||
Mapper.SHELF_FOLDERS_HASH = "sha256:226417726ce78055a35e7281426637272fdaaef4a001e15a975a41e37a2331cc"
|
||||
Mapper.READING_TIME_HASH = "sha256:03a310ea89efc4801c0071c4d3c5bcae7ae9227cada95c731e7222a0811e491f"
|
||||
|
||||
local SEARCH_VARIABLES = {
|
||||
includeRating = false,
|
||||
includeBookRating = false,
|
||||
includeUpdateTime = false,
|
||||
includeSaleInfo = false,
|
||||
includePurchase = false,
|
||||
includeLibraryCount = false,
|
||||
includeFandom = false,
|
||||
includeFanfictionTags = false,
|
||||
}
|
||||
|
||||
---@param value any
|
||||
---@return string
|
||||
local function clean(value)
|
||||
if type(value) ~= "string" then return "" end
|
||||
return Text.trim(Text.xmlDecode(value))
|
||||
end
|
||||
|
||||
---@param title any
|
||||
---@param idx integer
|
||||
---@return string
|
||||
local function chapterTitle(title, idx)
|
||||
local cleaned = clean(title)
|
||||
if cleaned ~= "" then return cleaned end
|
||||
return require("ffi/util").template(_("第 %1 章"), idx)
|
||||
end
|
||||
|
||||
---@param cover any
|
||||
---@return string|nil
|
||||
local function picture(cover)
|
||||
if type(cover) ~= "string" or cover == "" then return nil end
|
||||
cover = Text.xmlDecode(cover)
|
||||
if cover:sub(1, 2) == "//" then return "https:" .. cover end
|
||||
return cover
|
||||
end
|
||||
|
||||
---@param author any
|
||||
---@return string
|
||||
local function authors(author)
|
||||
if type(author) == "string" then return clean(author) end
|
||||
if type(author) ~= "table" then return "" end
|
||||
if type(author.name) == "string" then return clean(author.name) end
|
||||
local names = {}
|
||||
for _idx, person in ipairs(author) do
|
||||
local name = type(person) == "table" and person.name or person
|
||||
if type(name) == "string" and name ~= "" then names[#names + 1] = clean(name) end
|
||||
end
|
||||
return table.concat(names, " ")
|
||||
end
|
||||
|
||||
---@param id any
|
||||
---@param title any
|
||||
---@param author any
|
||||
---@param intro any
|
||||
---@param cover any
|
||||
---@param category any
|
||||
---@return Book
|
||||
local function book(id, title, author, intro, cover, category)
|
||||
return {
|
||||
source_id = SOURCE_ID,
|
||||
stable_id = tostring(id),
|
||||
title = clean(title),
|
||||
authors = authors(author),
|
||||
intro = clean(intro),
|
||||
cover = picture(cover),
|
||||
category = clean(category) ~= "" and clean(category) or nil,
|
||||
}
|
||||
end
|
||||
|
||||
---@param works_id any
|
||||
---@param hash string
|
||||
---@return table
|
||||
function Mapper.worksBody(works_id, hash)
|
||||
return {
|
||||
variables = { worksId = tostring(works_id) },
|
||||
extensions = { persistedQuery = { version = 1, sha256Hash = hash } },
|
||||
}
|
||||
end
|
||||
|
||||
---@param keyword string
|
||||
---@return table
|
||||
function Mapper.searchBody(keyword)
|
||||
return {
|
||||
sort = "default",
|
||||
page = 1,
|
||||
q = keyword,
|
||||
extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SEARCH_HASH } },
|
||||
variables = SEARCH_VARIABLES,
|
||||
}
|
||||
end
|
||||
|
||||
---@param opts table
|
||||
---@param page integer
|
||||
---@return table
|
||||
function Mapper.catalogBody(opts, page)
|
||||
local body = {
|
||||
kind = tonumber(opts.category),
|
||||
sort = opts.sort,
|
||||
page = page,
|
||||
extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SEARCH_HASH } },
|
||||
variables = SEARCH_VARIABLES,
|
||||
}
|
||||
if opts.pay == "free" then body.minPrice, body.maxPrice = 0, 0
|
||||
elseif opts.pay == "paid" then body.minPrice = 1 end
|
||||
if opts.state == "complete" then body.isFinished = true
|
||||
elseif opts.state == "serial" then body.isFinished = false end
|
||||
return body
|
||||
end
|
||||
|
||||
---@param html string
|
||||
---@return table<string, { id: string, title: string }[]>|nil
|
||||
---@return string|nil
|
||||
function Mapper.categories(html)
|
||||
local raw = type(html) == "string" and html:match("Ark%.kindTree%s*=%s*(%b[])")
|
||||
local ok, tree = pcall(JSON.decode, raw or "")
|
||||
if not ok or type(tree) ~= "table" then return nil, _("响应无效") end
|
||||
local categories = { original = {}, publish = {} }
|
||||
local function append(rows, out)
|
||||
for _idx, row in ipairs(rows) do
|
||||
if type(row) ~= "table" or type(row.id) ~= "number" or type(row.name) ~= "string"
|
||||
or type(row.children) ~= "table" then return false end
|
||||
out[#out + 1] = { id = tostring(row.id), title = clean(row.name) }
|
||||
if not append(row.children, out) then return false end
|
||||
end
|
||||
return true
|
||||
end
|
||||
for _idx, root in ipairs(tree) do
|
||||
if type(root) ~= "table" then return nil, _("响应无效") end
|
||||
local channel = root.id == 0 and "original" or root.id == 1 and "publish" or nil
|
||||
if channel and (type(root.children) ~= "table" or not append(root.children, categories[channel])) then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
end
|
||||
if #categories.original == 0 or #categories.publish == 0 then return nil, _("响应无效") end
|
||||
return categories
|
||||
end
|
||||
|
||||
---@param item table
|
||||
---@return Book|nil
|
||||
local function worksBook(item)
|
||||
if type(item) ~= "table" or item.isAudio == true or item.isBundle == true then return nil end
|
||||
local id = item.id or item.worksId or item.works_id
|
||||
local title = item.title or item.name
|
||||
if id == nil or title == nil or title == "" then return nil end
|
||||
local category = item.category
|
||||
if type(item.kinds) == "table" and type(item.kinds[1]) == "table" then
|
||||
category = item.kinds[1].shortName or item.kinds[1].name
|
||||
end
|
||||
return book(id, title, item.author or item.agent, item.abstract or item.intro, item.cover or item.cover_url, category)
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@return Book[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.searchBooks(wire)
|
||||
if type(wire) ~= "table" or type(wire.list) ~= "table" then
|
||||
return nil, type(wire) == "table" and type(wire.error) == "string" and wire.error or _("请求失败")
|
||||
end
|
||||
local books = {}
|
||||
for _idx, item in ipairs(wire.list) do
|
||||
local row = worksBook(item)
|
||||
if row then books[#books + 1] = row end
|
||||
end
|
||||
return books
|
||||
end
|
||||
|
||||
---@param url string|nil
|
||||
---@return { kind: string, column_id: string|nil, aid: string|nil }|nil
|
||||
function Mapper.reader(url)
|
||||
if type(url) ~= "string" then return nil end
|
||||
local column_id = url:match("/reader/column/(%d+)/")
|
||||
if column_id then return { kind = "column", column_id = column_id } end
|
||||
local aid = url:match("/reader/ebook/(%d+)")
|
||||
if aid then return { kind = "ebook", aid = aid } end
|
||||
return nil
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@return string|nil
|
||||
function Mapper.readerUrl(wire)
|
||||
local data = type(wire) == "table" and wire.data or nil
|
||||
local works = type(data) == "table" and data.works or nil
|
||||
local url = type(works) == "table" and works.readerUrl or nil
|
||||
if type(url) ~= "string" or url == "" then return nil end
|
||||
return url
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param wire table|nil
|
||||
---@return Book|nil
|
||||
function Mapper.columnBook(works_id, wire)
|
||||
if type(wire) ~= "table" or wire.type ~= "column" or type(wire.title) ~= "string" then return nil end
|
||||
return book(works_id, wire.title, wire.agent, wire.abstract, wire.cover or wire.retina_cover, wire.category)
|
||||
end
|
||||
|
||||
---@param works_id string
|
||||
---@param wire table|nil
|
||||
---@return Book|nil
|
||||
function Mapper.infoBook(works_id, wire)
|
||||
local data = type(wire) == "table" and wire.data or nil
|
||||
local works = type(data) == "table" and (data.universalWorks or data.works) or nil
|
||||
if type(works) ~= "table" or type(works.title) ~= "string" then return nil end
|
||||
return book(works_id, works.title, nil, nil, nil, nil)
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@return BookChapter[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.columnChapters(wire)
|
||||
if type(wire) ~= "table" or type(wire.chapters) ~= "table" then return nil, _("豆瓣阅读目录为空") end
|
||||
local chapters = {}
|
||||
for idx, item in ipairs(wire.chapters) do
|
||||
if type(item) == "table" and item.id ~= nil then
|
||||
local free = item.is_free == true or item.is_paid == true or item.is_allowed_to_read == true
|
||||
chapters[#chapters + 1] = {
|
||||
idx = idx,
|
||||
uid = tostring(item.id),
|
||||
title = chapterTitle(item.title, idx),
|
||||
content_url = tostring(item.id),
|
||||
vip = not free,
|
||||
}
|
||||
end
|
||||
end
|
||||
if not chapters[1] then return nil, _("豆瓣阅读目录为空") end
|
||||
chapters[1].toc_version = Mapper.TOC_VERSION
|
||||
return chapters
|
||||
end
|
||||
|
||||
---@param b64 string
|
||||
---@param user_id string|nil
|
||||
---@return table|nil
|
||||
---@return string|nil
|
||||
function Mapper.decrypt(b64, user_id)
|
||||
local raw = Text.base64Decode(b64)
|
||||
local cipher_len = #raw - 16 - 13
|
||||
if cipher_len < 16 or cipher_len % 16 ~= 0 then return nil, _("正文解密失败") end
|
||||
local material = type(user_id) == "string" and user_id ~= "" and user_id or "anonymous"
|
||||
local sha2 = require("ffi/sha2")
|
||||
local key = sha2.hex_to_bin(sha2.sha256(material))
|
||||
local ok, plain = pcall(Aes.cbc_decrypt, raw:sub(1, cipher_len), key, raw:sub(cipher_len + 1, cipher_len + 16))
|
||||
if not ok or type(plain) ~= "string" then return nil, _("正文解密失败") end
|
||||
local decoded, article = pcall(JSON.decode, plain)
|
||||
if not decoded or type(article) ~= "table" then return nil, _("正文解密失败") end
|
||||
return article
|
||||
end
|
||||
|
||||
---@param data table|nil
|
||||
---@return string
|
||||
local function paragraphText(data)
|
||||
local text = data and data.text
|
||||
if type(text) == "table" then
|
||||
local parts = {}
|
||||
for _idx, run in ipairs(text) do
|
||||
if run.kind == "plaintext" then parts[#parts + 1] = run.content end
|
||||
end
|
||||
text = table.concat(parts)
|
||||
end
|
||||
return type(text) == "string" and Text.trim(text) or ""
|
||||
end
|
||||
|
||||
---@param article table
|
||||
---@param start_pid number|nil
|
||||
---@param end_pid number|nil
|
||||
---@return string
|
||||
function Mapper.blocksText(article, start_pid, end_pid)
|
||||
local lines = {}
|
||||
local posts = type(article.posts) == "table" and article.posts or {}
|
||||
for _pidx, post in ipairs(posts) do
|
||||
local contents = type(post) == "table" and post.contents or nil
|
||||
if type(contents) == "table" then
|
||||
for _bidx, block in ipairs(contents) do
|
||||
local id = type(block) == "table" and tonumber(block.id) or nil
|
||||
local in_range = not start_pid or (id and id >= start_pid and (not end_pid or id < end_pid))
|
||||
local kind = type(block) == "table" and block.type or nil
|
||||
if in_range and (kind == "paragraph" or kind == "headline") then
|
||||
local text = paragraphText(block.data)
|
||||
if text ~= "" then lines[#lines + 1] = text end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return table.concat(lines, "\n")
|
||||
end
|
||||
|
||||
--- 本章非空段的段落编号,顺序和章节 HTML 里的 <p> 一致。
|
||||
---@param article table|nil
|
||||
---@param start_pid number|nil
|
||||
---@param end_pid number|nil
|
||||
---@return string[]
|
||||
function Mapper.paragraphIds(article, start_pid, end_pid)
|
||||
local ids = {}
|
||||
local posts = type(article) == "table" and article.posts or {}
|
||||
for _pidx, post in ipairs(type(posts) == "table" and posts or {}) do
|
||||
local contents = type(post) == "table" and post.contents or nil
|
||||
if type(contents) == "table" then
|
||||
for _bidx, block in ipairs(contents) do
|
||||
local id = type(block) == "table" and tonumber(block.id) or nil
|
||||
local in_range = not start_pid or (id and id >= start_pid and (not end_pid or id < end_pid))
|
||||
local kind = type(block) == "table" and block.type or nil
|
||||
if id and in_range and (kind == "paragraph" or kind == "headline") and paragraphText(block.data) ~= "" then
|
||||
ids[#ids + 1] = tostring(block.id)
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
return ids
|
||||
end
|
||||
|
||||
--- 批注时间。秒级数字;13 位毫秒收成秒。没有数字就给 0。
|
||||
---@param value any
|
||||
---@return integer
|
||||
local function created(value)
|
||||
local n = tonumber(value)
|
||||
if n then
|
||||
if n > 1e12 then n = math.floor(n / 1000) end
|
||||
return math.floor(n)
|
||||
end
|
||||
if type(value) ~= "string" then return 0 end
|
||||
local year, month, day, hour, min, sec = value:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)")
|
||||
if not year then return 0 end
|
||||
local stamp = os.time({
|
||||
year = tonumber(year), month = tonumber(month), day = tonumber(day),
|
||||
hour = tonumber(hour), min = tonumber(min), sec = tonumber(sec),
|
||||
})
|
||||
if not stamp then return 0 end
|
||||
local now = os.time()
|
||||
return stamp + os.difftime(now, os.time(os.date("!*t", now)))
|
||||
end
|
||||
|
||||
--- 一段上的批注条数。没有 note 的划线不是段评。range 是本章第几个非空段。
|
||||
---@param rows table|nil
|
||||
---@param pids string[]
|
||||
---@return { range: string, text: string, total: integer }[]|nil
|
||||
function Mapper.reviewHotspots(rows, pids)
|
||||
if type(rows) ~= "table" then return nil end
|
||||
local index = {}
|
||||
for idx, pid in ipairs(pids) do index[tostring(pid)] = tostring(idx) end
|
||||
local counts = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
local note = type(row) == "table" and type(row.note) == "string" and Text.trim(row.note) or ""
|
||||
local pid = type(row) == "table" and row.startContainerId ~= nil and tostring(row.startContainerId) or nil
|
||||
local range = pid and index[pid]
|
||||
if range and note ~= "" then counts[range] = (counts[range] or 0) + 1 end
|
||||
end
|
||||
local out = {}
|
||||
for range, total in pairs(counts) do
|
||||
out[#out + 1] = { range = range, text = "", total = total }
|
||||
end
|
||||
table.sort(out, function(a, b) return tonumber(a.range) < tonumber(b.range) end)
|
||||
return out
|
||||
end
|
||||
|
||||
--- 某一段的批注。作者是 owner.name,赞是 n_favorites。
|
||||
---@param rows table|nil
|
||||
---@param pids string[]
|
||||
---@param range string|number
|
||||
---@return { items: table[], total: integer, max_idx: integer, more: boolean }|nil
|
||||
function Mapper.reviewPage(rows, pids, range)
|
||||
if type(rows) ~= "table" then return nil end
|
||||
local pid = pids[tonumber(range)]
|
||||
local items = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
if type(row) == "table" and pid and tostring(row.startContainerId) == tostring(pid) then
|
||||
local note = type(row.note) == "string" and Text.trim(row.note) or ""
|
||||
local owner = type(row.owner) == "table" and row.owner or nil
|
||||
local name = owner and type(owner.name) == "string" and owner.name or ""
|
||||
if note ~= "" then
|
||||
items[#items + 1] = {
|
||||
id = tostring(row.id or ""),
|
||||
author = name,
|
||||
content = note,
|
||||
likes = tonumber(row.n_favorites) or 0,
|
||||
images = {},
|
||||
time = created(row.create_time),
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
return { items = items, total = #items, max_idx = 1, more = false }
|
||||
end
|
||||
|
||||
---@param article table
|
||||
---@param aid string
|
||||
---@return BookChapter[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.ebookChapters(article, aid)
|
||||
local toc = type(article.toc) == "table" and article.toc or {}
|
||||
local chapters = {}
|
||||
for idx, item in ipairs(toc) do
|
||||
if type(item) == "table" and item.paragraph_id ~= nil then
|
||||
local pid = tonumber(item.paragraph_id)
|
||||
local next_item = toc[idx + 1]
|
||||
local next_pid = type(next_item) == "table" and tonumber(next_item.paragraph_id) or nil
|
||||
chapters[#chapters + 1] = {
|
||||
idx = idx,
|
||||
uid = tostring(item.paragraph_id),
|
||||
title = chapterTitle(item.title, idx),
|
||||
content_url = tostring(aid),
|
||||
end_pid = next_pid and tostring(next_pid) or nil,
|
||||
slice = true,
|
||||
vip = Mapper.blocksText(article, pid, next_pid) == "",
|
||||
depth = (tonumber(item.level) or 0) + 1,
|
||||
}
|
||||
end
|
||||
end
|
||||
if not chapters[1] then
|
||||
local text = Mapper.blocksText(article, nil, nil)
|
||||
local title = type(article.posts) == "table" and type(article.posts[1]) == "table" and article.posts[1].title or nil
|
||||
if text == "" then return nil, _("豆瓣阅读目录为空") end
|
||||
chapters[1] = {
|
||||
idx = 1,
|
||||
uid = tostring(aid),
|
||||
title = chapterTitle(title, 1),
|
||||
content_url = tostring(aid),
|
||||
vip = false,
|
||||
}
|
||||
end
|
||||
chapters[1].toc_version = Mapper.TOC_VERSION
|
||||
return chapters
|
||||
end
|
||||
|
||||
--- 首页脚本里的写请求令牌。没有它,登录后的 POST 会被拒。
|
||||
---@param html string|nil
|
||||
---@return string|nil
|
||||
function Mapper.readCsrf(html)
|
||||
if type(html) ~= "string" then return nil end
|
||||
return html:match("CSRF_TOKEN%s*=%s*'([^']+)'")
|
||||
or html:match('CSRF_TOKEN%s*=%s*"([^"]+)"')
|
||||
end
|
||||
|
||||
--- `/j/bookshelf/` 只有编号。书架页 GraphQL 的 `libraryList.list[].worksId` 同形。
|
||||
---@param wire table|nil
|
||||
---@return string[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.shelfIds(wire)
|
||||
if type(wire) ~= "table" or wire.errors then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
local rows = wire.worksIds
|
||||
if type(rows) ~= "table" then
|
||||
local user = type(wire.data) == "table" and wire.data.user or nil
|
||||
local shelf = type(user) == "table" and type(user.bookshelf) == "table" and user.bookshelf or nil
|
||||
local library = type(shelf) == "table" and shelf.libraryList or nil
|
||||
rows = type(library) == "table" and library.list or nil
|
||||
end
|
||||
if type(rows) ~= "table" or (next(rows) ~= nil and rows[1] == nil) then
|
||||
return nil, _("豆瓣阅读书架数据无法识别")
|
||||
end
|
||||
local ids = {}
|
||||
for _idx, item in ipairs(rows) do
|
||||
local id = item
|
||||
if type(item) == "table" then id = item.worksId or item.id or item.works_id end
|
||||
if type(id) == "number" then id = tostring(id) end
|
||||
if type(id) ~= "string" or id == "" then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
ids[#ids + 1] = id
|
||||
end
|
||||
|
||||
return ids
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@return (string|number)[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.folderIds(wire)
|
||||
local ids = type(wire) == "table" and wire.folderIds
|
||||
if type(ids) ~= "table" or (next(ids) ~= nil and ids[1] == nil) then return nil, _("响应无效") end
|
||||
for _idx, id in ipairs(ids) do
|
||||
if (type(id) ~= "string" and type(id) ~= "number") or id == "" then return nil, _("响应无效") end
|
||||
end
|
||||
return ids
|
||||
end
|
||||
|
||||
--- 与微信相同:多组成员按官网分组顺序取第一个,响应顺序不决定分类。
|
||||
---@param wire table|nil
|
||||
---@param ids (string|number)[]
|
||||
---@return table<string, string>|nil
|
||||
---@return string|nil
|
||||
function Mapper.shelfGroups(wire, ids)
|
||||
if type(wire) ~= "table" or wire.errors then return nil, _("响应无效") end
|
||||
local user = type(wire.data) == "table" and wire.data.user
|
||||
local shelf = type(user) == "table" and user.bookshelf
|
||||
local folders = type(shelf) == "table" and shelf.folders
|
||||
local list = type(folders) == "table" and folders.list
|
||||
if type(list) ~= "table" or (next(list) ~= nil and list[1] == nil) then return nil, _("响应无效") end
|
||||
local by_id = {}
|
||||
for _idx, folder in ipairs(list) do
|
||||
if type(folder) ~= "table" or (type(folder.id) ~= "string" and type(folder.id) ~= "number")
|
||||
or folder.id == "" or type(folder.name) ~= "string" or folder.name == ""
|
||||
or type(folder.libraryList) ~= "table" or by_id[tostring(folder.id)] then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
local members, err = Mapper.shelfIds({ worksIds = folder.libraryList.list })
|
||||
if not members then return nil, err end
|
||||
by_id[tostring(folder.id)] = { name = folder.name, members = members }
|
||||
end
|
||||
local groups = {}
|
||||
for _idx, id in ipairs(ids) do
|
||||
local folder = by_id[tostring(id)]
|
||||
if not folder then return nil, _("响应无效") end
|
||||
for _member_idx, works_id in ipairs(folder.members) do
|
||||
groups[works_id] = groups[works_id] or folder.name
|
||||
end
|
||||
end
|
||||
return groups
|
||||
end
|
||||
|
||||
---@param ids string[]
|
||||
---@return table
|
||||
function Mapper.shelfWorksBody(ids)
|
||||
return {
|
||||
variables = { worksIds = ids },
|
||||
extensions = { persistedQuery = { version = 1, sha256Hash = Mapper.SHELF_WORKS_HASH } },
|
||||
}
|
||||
end
|
||||
|
||||
--- 编号查回来的作品。有声书不进书架。
|
||||
---@param wire table|nil
|
||||
---@param groups table<string, string>|nil
|
||||
---@param ids string[]|nil
|
||||
---@return Book[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.shelfWorks(wire, groups, ids)
|
||||
if type(wire) ~= "table" or wire.errors then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
local data = type(wire) == "table" and wire.data or nil
|
||||
local list = type(data) == "table" and data.worksList or nil
|
||||
if type(list) ~= "table" or (next(list) ~= nil and list[1] == nil) then
|
||||
return nil, _("豆瓣阅读书架数据无法识别")
|
||||
end
|
||||
local books, seen = {}, {}
|
||||
for _idx, item in ipairs(list) do
|
||||
if type(item) ~= "table" or item.id == nil then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
seen[tostring(item.id)] = true
|
||||
local row = worksBook(item)
|
||||
if row then
|
||||
local genre = row.category
|
||||
if not genre and type(item.isOrigin) == "boolean" then
|
||||
genre = item.isOrigin and _("原创") or _("出版")
|
||||
end
|
||||
row.category = CategorySetting.apply(SOURCE_ID, genre, groups and groups[row.stable_id])
|
||||
row.category_authoritative = true
|
||||
books[#books + 1] = row
|
||||
elseif item.isAudio ~= true and item.isBundle ~= true then
|
||||
return nil, _("豆瓣阅读书架数据无法识别")
|
||||
end
|
||||
end
|
||||
for _idx, id in ipairs(ids or {}) do
|
||||
if not seen[id] then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
end
|
||||
if #books == 0 and #list > 0 then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
return books
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@return Book[]|nil
|
||||
---@return string|nil
|
||||
function Mapper.shelf(wire)
|
||||
local rows = wire
|
||||
if type(wire) == "table" and wire[1] == nil then
|
||||
rows = wire.worksIds or wire.list or wire.works or wire.items
|
||||
if rows == nil then
|
||||
if wire.error or wire.message or next(wire) ~= nil then
|
||||
return nil, _("豆瓣阅读书架数据无法识别")
|
||||
end
|
||||
rows = {}
|
||||
end
|
||||
end
|
||||
if type(rows) ~= "table" then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
local books = {}
|
||||
for _idx, item in ipairs(rows) do
|
||||
local row = worksBook(item)
|
||||
if row then books[#books + 1] = row end
|
||||
end
|
||||
if #books == 0 and #rows > 0 then return nil, _("豆瓣阅读书架数据无法识别") end
|
||||
return books
|
||||
end
|
||||
|
||||
---@param html string
|
||||
---@return string|nil
|
||||
function Mapper.csrf(html)
|
||||
if type(html) ~= "string" then return nil end
|
||||
return html:match('name="csrf%-token"%s+content="([^"]+)"')
|
||||
or html:match('content="([^"]+)"%s+name="csrf%-token"')
|
||||
end
|
||||
|
||||
---@param html string
|
||||
---@return { id: string, name: string }|nil
|
||||
function Mapper.user(html)
|
||||
if type(html) ~= "string" then return nil end
|
||||
local raw = html:match("Ark%.user%s*=%s*(%b{})")
|
||||
if not raw then return nil end
|
||||
local ok, user = pcall(JSON.decode, raw)
|
||||
if not ok or type(user) ~= "table" or user.isAnonymous == true
|
||||
or (type(user.id) ~= "string" and type(user.id) ~= "number") or tostring(user.id) == "" then return nil end
|
||||
local name = user.name or user.nickname or user.screenName or ""
|
||||
return { id = tostring(user.id), name = type(name) == "string" and name or "" }
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@param origin string
|
||||
---@return { qr: string, code: string, expires_in: number }|nil
|
||||
function Mapper.qr(wire, origin)
|
||||
if type(wire) ~= "table" or type(wire.url) ~= "string" or wire.url == "" then return nil end
|
||||
local code = wire.url:match("[?&]code=([^&]+)")
|
||||
if not code or code == "" then return nil end
|
||||
if wire.url:sub(1, 1) ~= "/" or wire.url:sub(1, 2) == "//" then return nil end
|
||||
return { qr = origin .. wire.url, code = code, expires_in = tonumber(wire.expires_in) or 300 }
|
||||
end
|
||||
|
||||
---@param wire table|nil
|
||||
---@return string|nil
|
||||
function Mapper.qrStatus(wire)
|
||||
if type(wire) ~= "table" or type(wire.confirmed) ~= "boolean" then return nil end
|
||||
if wire.confirmed then return "ok" end
|
||||
return "wait"
|
||||
end
|
||||
|
||||
--- 进度回包。`r` 为真或没有 progress 是云端无位置,不是请求失败。
|
||||
---@param wire table|nil
|
||||
---@return { paragraph_id: string }|nil
|
||||
---@return boolean empty
|
||||
function Mapper.progress(wire)
|
||||
if type(wire) ~= "table" then return nil, false end
|
||||
local item = wire.progress
|
||||
-- 网页把 r 当布尔用:0 是成功。Lua 里 0 为真,不能直接 if wire.r。
|
||||
local failed = wire.r ~= nil and wire.r ~= false and wire.r ~= 0
|
||||
if failed then return nil, false end
|
||||
if item == nil or item == JSON.null then return nil, true end
|
||||
if type(item) ~= "table" or item.paragraph_id == nil or tostring(item.paragraph_id) == "" then
|
||||
return nil, false
|
||||
end
|
||||
return { paragraph_id = tostring(item.paragraph_id) }, false
|
||||
end
|
||||
|
||||
--- 章节正文里第一个能定位的段落。专栏进度记在这一章的 article 上。
|
||||
---@param article table|nil
|
||||
---@return string|nil
|
||||
function Mapper.firstParagraphId(article)
|
||||
local posts = type(article) == "table" and article.posts or nil
|
||||
if type(posts) ~= "table" then return nil end
|
||||
for _pidx, post in ipairs(posts) do
|
||||
local contents = type(post) == "table" and post.contents or nil
|
||||
if type(contents) == "table" then
|
||||
for _bidx, block in ipairs(contents) do
|
||||
local kind = type(block) == "table" and block.type or nil
|
||||
if block.id ~= nil and kind == "paragraph" and paragraphText(block.data) ~= "" then
|
||||
return tostring(block.id)
|
||||
end
|
||||
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
--- 官网分段索引来自 posts[].contents[],不是月读章节号。
|
||||
---@param article table
|
||||
---@param pid string
|
||||
---@param end_pid string|nil
|
||||
---@return table|nil
|
||||
function Mapper.progressPosition(article, pid, end_pid)
|
||||
local reached = false
|
||||
for part_idx, post in ipairs(article.posts or {}) do
|
||||
for paragraph_idx, block in ipairs(post.contents or {}) do
|
||||
local id = block.id ~= nil and tostring(block.id) or nil
|
||||
if id == pid then reached = true end
|
||||
if reached and end_pid and id == end_pid then return nil end
|
||||
if reached and id and block.type == "paragraph" and paragraphText(block.data) ~= "" then
|
||||
return {
|
||||
paragraph_id = id,
|
||||
part_sequence = part_idx - 1,
|
||||
part_paragraph_sequence = paragraph_idx - 1,
|
||||
}
|
||||
end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
---@param wire table
|
||||
---@param begin_date string
|
||||
---@param fetched_at number
|
||||
---@return BookStatsPullResult|nil
|
||||
---@return string|nil
|
||||
function Mapper.readingStats(wire, begin_date, fetched_at)
|
||||
if type(wire) ~= "table" or wire.errors then return nil, _("响应无效") end
|
||||
local user = type(wire) == "table" and type(wire.data) == "table" and wire.data.user
|
||||
local total = type(user) == "table" and user.readingTimeTotal
|
||||
local history = type(user) == "table" and user.readingTimeHistory
|
||||
local function seconds(value)
|
||||
return type(value) == "number" and value >= 0 and value < math.huge and value or nil
|
||||
end
|
||||
if type(total) ~= "table" or not seconds(total.duration) or type(history) ~= "table"
|
||||
or (next(history) ~= nil and history[1] == nil) then return nil, _("响应无效") end
|
||||
local function midnight(date)
|
||||
if type(date) ~= "string" then return nil end
|
||||
local year, month, day = date:match("^(%d%d%d%d)%-(%d%d)%-(%d%d)$")
|
||||
if not year then return nil end
|
||||
local time = os.time({ year = tonumber(year), month = tonumber(month), day = tonumber(day), hour = 0 })
|
||||
return time and os.date("%Y-%m-%d", time) == date and time or nil
|
||||
end
|
||||
local from = midnight(begin_date)
|
||||
if not from then return nil, _("响应无效") end
|
||||
local rows, seen = {}, {}
|
||||
local function row(id, kind, start_time, duration)
|
||||
if duration > 0 then
|
||||
rows[#rows + 1] = {
|
||||
source_id = SOURCE_ID, stable_id = id, record_type = kind,
|
||||
start_time = start_time, duration = duration, last_time = fetched_at,
|
||||
page = 0, total_pages = 0, event_count = 0,
|
||||
}
|
||||
end
|
||||
end
|
||||
row("__douban:total", "total", fetched_at, total.duration)
|
||||
for _idx, item in ipairs(history) do
|
||||
local date = type(item) == "table" and item.date
|
||||
local time = midnight(date)
|
||||
local reading = type(item) == "table" and item.readingTime
|
||||
local duration = type(reading) == "table" and seconds(reading.duration)
|
||||
if not time or not duration or time < from or time > fetched_at or seen[date] then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
seen[date] = true
|
||||
row("__douban:day:" .. date, "day", time, duration)
|
||||
end
|
||||
return {
|
||||
rows = rows,
|
||||
replace = { mode = "ranges", ranges = {
|
||||
{ stable_prefix = "__douban:day:", from_ts = from, to_ts = fetched_at },
|
||||
{ stable_prefix = "__douban:total", from_ts = 0, to_ts = fetched_at },
|
||||
} },
|
||||
}
|
||||
end
|
||||
|
||||
---@param wire table
|
||||
---@param offset integer
|
||||
---@param chapter_id string|nil
|
||||
---@return table|nil, string|nil
|
||||
function Mapper.communityPage(wire, offset, chapter_id)
|
||||
if type(wire) == "table" and type(wire.errors) == "table" then
|
||||
for _idx, err in ipairs(wire.errors) do
|
||||
if type(err) == "table" and err.message == "AnonymousError" then
|
||||
return nil, _("请先登录豆瓣阅读")
|
||||
end
|
||||
end
|
||||
end
|
||||
local works = type(wire) == "table" and type(wire.data) == "table" and wire.data.works
|
||||
local comments = type(works) == "table" and works.comments
|
||||
local rows = type(comments) == "table" and comments.list
|
||||
local total = type(comments) == "table" and tonumber(comments.total)
|
||||
if type(wire) ~= "table" or wire.errors ~= nil and (type(wire.errors) ~= "table" or #wire.errors > 0)
|
||||
or type(rows) ~= "table"
|
||||
or not total or total < 0 or #rows == 0 and offset < total then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
local items = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
local scope = type(row) == "table" and row.works
|
||||
local stamp = type(row) == "table" and type(row.createTime) == "string"
|
||||
and row.createTime:match("^%d%d%d%d%-%d%d%-%d%d")
|
||||
if type(row) ~= "table" or (type(row.id) ~= "string" and type(row.id) ~= "number")
|
||||
or row.id == "" or type(row.content) ~= "string"
|
||||
or not stamp or type(scope) ~= "table"
|
||||
or row.commentType ~= (chapter_id and "Discussion" or "Review")
|
||||
or chapter_id and (scope.isChapter ~= true or tostring(scope.id) ~= chapter_id)
|
||||
or not chapter_id and scope.isChapter ~= false then
|
||||
return nil, _("响应无效")
|
||||
end
|
||||
local content = Text.stripHtml(row.content)
|
||||
if type(row.title) == "string" and row.title ~= "" then
|
||||
content = row.title .. "\n" .. content
|
||||
end
|
||||
local user = type(row.user) == "table" and row.user or {}
|
||||
items[#items + 1] = {
|
||||
id = tostring(row.id), author = type(user.name) == "string" and user.name or "",
|
||||
text = content, content = content, time = stamp,
|
||||
likes = tonumber(row.upvoteCount), grade = tonumber(row.rating),
|
||||
replies = 0,
|
||||
}
|
||||
end
|
||||
local next_idx = offset + #rows
|
||||
return { items = items, total = total, max_idx = next_idx, more = next_idx < total,
|
||||
pages = math.max(1, math.ceil(total / 20)),
|
||||
title = not chapter_id and (#items < total and _("书评预览") or _("书评")) or nil }
|
||||
end
|
||||
|
||||
return Mapper
|
||||
@@ -0,0 +1,131 @@
|
||||
--[[--
|
||||
豆瓣阅读短信登录。手机号、验证码和候选会话只属于当前输入窗口。
|
||||
|
||||
@module moonsource_douban.phone_login
|
||||
--]]
|
||||
|
||||
local Client = require("moonsource_douban.client")
|
||||
local Text = require("utils.text")
|
||||
local _ = require("l10n").get("moonsource_douban")
|
||||
|
||||
local PhoneLogin = {}
|
||||
PhoneLogin.__index = PhoneLogin
|
||||
|
||||
function PhoneLogin:new(on_user)
|
||||
return setmetatable({ on_user = on_user, session = Client.newLogin(), generation = 0 }, PhoneLogin)
|
||||
end
|
||||
|
||||
function PhoneLogin:cancel()
|
||||
self.generation = self.generation + 1
|
||||
if self.job then self.job.cancel() end
|
||||
self.job, self.busy = nil, false
|
||||
self.session:cancel()
|
||||
end
|
||||
|
||||
function PhoneLogin:_request(method, callback, ...)
|
||||
local args = { ... }
|
||||
local count, pending, gen = select("#", ...) + 1, true, self.generation
|
||||
self.busy = true
|
||||
args[count] = function(...)
|
||||
pending = false
|
||||
if gen ~= self.generation then return end
|
||||
self.job, self.busy = nil, false
|
||||
callback(...)
|
||||
end
|
||||
local job = self.session[method](self.session, unpack(args, 1, count))
|
||||
if pending then self.job = job end
|
||||
end
|
||||
|
||||
function PhoneLogin:send(country, number)
|
||||
if not require("ui/network/manager"):isConnected() then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
if self.busy then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("正在处理,请稍候"), timeout = 2 }:show()
|
||||
return
|
||||
end
|
||||
country, number = Text.trim(country), Text.trim(number)
|
||||
if not country:match("^%+%d+$") or not number:match("^%d+$") then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("请输入有效的手机号和国际区号"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
local phone = country .. number
|
||||
if self.retry_at and os.time() < self.retry_at then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("请稍后再获取验证码"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
if not self.session.authorize then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("正在获取验证码…"), timeout = 2 }:show()
|
||||
self:_request("beginAsync", function(authorize, err)
|
||||
if not authorize then
|
||||
require("ui.themes.widgets.toast"):new{ text = err or _("登录失败"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
self:send(country, number)
|
||||
end)
|
||||
return
|
||||
end
|
||||
self:_request("sendPhoneCodeAsync", function(wait, err)
|
||||
if wait == nil then
|
||||
require("ui.themes.widgets.toast"):new{ text = err or _("请求失败"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
self.phone, self.retry_at = phone, os.time() + wait
|
||||
require("ui.themes.widgets.toast"):new{ text = _("验证码已发送"), timeout = 3 }:show()
|
||||
end, phone)
|
||||
end
|
||||
|
||||
function PhoneLogin:verify(country, number, code)
|
||||
if self.busy then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("正在处理,请稍候"), timeout = 2 }:show()
|
||||
return
|
||||
end
|
||||
if not require("ui/network/manager"):isConnected() then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
local phone = Text.trim(country) .. Text.trim(number)
|
||||
code = Text.trim(code)
|
||||
if phone ~= self.phone or not code:match("^%d+$") then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("请先获取该手机号的验证码,再填写验证码登录"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
require("ui.themes.widgets.toast"):new{ text = _("正在登录…"), timeout = 2 }:show()
|
||||
self:_request("verifyPhoneAsync", function(user, err)
|
||||
if not user then
|
||||
require("ui.themes.widgets.toast"):new{ text = err or _("登录失败"), timeout = 4 }:show()
|
||||
return
|
||||
end
|
||||
self:cancel()
|
||||
self.dialog:close()
|
||||
self.on_user(user)
|
||||
end, phone, code)
|
||||
end
|
||||
|
||||
function PhoneLogin:start()
|
||||
self.dialog = require("ui.themes.widgets.input"):new{
|
||||
title = _("豆瓣阅读手机号登录"),
|
||||
fields = {
|
||||
{ label = _("国际区号"), text = "+86", hint = "+86" },
|
||||
{ label = _("手机号"), input_type = "number" },
|
||||
{ label = _("验证码"), input_type = "number" },
|
||||
},
|
||||
keep_open = true,
|
||||
ok_text = _("登录"),
|
||||
actions = { { text = _("获取验证码"), callback = function(country, number) self:send(country, number) end } },
|
||||
callback = function(country, number, code)
|
||||
require("ui.themes.widgets.confirm"):new{
|
||||
text = _("登录前请阅读并同意豆瓣阅读使用协议、隐私政策和社区指导原则")
|
||||
.. "\nhttps://read.douban.com/about/agreement\nhttps://read.douban.com/privacy"
|
||||
.. "\nhttps://read.douban.com/faq?type=guideline",
|
||||
ok_text = _("同意并登录"),
|
||||
ok_callback = function() self:verify(country, number, code) end,
|
||||
}:show()
|
||||
end,
|
||||
cancel_callback = function() self:cancel() end,
|
||||
}
|
||||
self.dialog:show()
|
||||
end
|
||||
|
||||
return PhoneLogin
|
||||
@@ -0,0 +1,137 @@
|
||||
--[[--
|
||||
豆瓣阅读 App 扫码登录。
|
||||
|
||||
二维码内容是 https://accounts.arkread.com/oidc/qrcode/confirm?code= 。
|
||||
每 1.5 秒轮询状态,确认后重新打开授权页,跟跳转直到读到登录用户。
|
||||
|
||||
@module moonsource_douban.qrlogin
|
||||
--]]
|
||||
|
||||
local Client = require("moonsource_douban.client")
|
||||
local _ = require("l10n").get("moonsource_douban")
|
||||
|
||||
local QRLogin = {}
|
||||
QRLogin.__index = QRLogin
|
||||
|
||||
local POLL_INTERVAL = 1.5
|
||||
local POLL_LIMIT = 200
|
||||
|
||||
---@param on_user fun(user: { id: string, name: string })
|
||||
---@return table
|
||||
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.job and self.job.cancel then self.job.cancel() end
|
||||
self.job = nil
|
||||
if self.session then self.session:cancel() end
|
||||
end
|
||||
|
||||
function QRLogin:_request(method, callback, ...)
|
||||
local args = { ... }
|
||||
local count, pending, gen = select("#", ...) + 1, true, self.generation
|
||||
args[count] = function(...)
|
||||
pending = false
|
||||
if gen ~= self.generation then return end
|
||||
self.job = nil
|
||||
callback(...)
|
||||
end
|
||||
local job = self.session[method](self.session, unpack(args, 1, count))
|
||||
if pending then self.job = job end
|
||||
end
|
||||
|
||||
---@param text string
|
||||
function QRLogin:toast(text)
|
||||
require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show()
|
||||
end
|
||||
|
||||
---@param text string
|
||||
function QRLogin:_retry(text)
|
||||
self:cancel()
|
||||
if self.dialog then
|
||||
local dialog = self.dialog
|
||||
self.dialog = nil
|
||||
dialog:close()
|
||||
end
|
||||
require("ui.themes.widgets.confirm"):new{
|
||||
text = text,
|
||||
ok_text = _("重新获取"),
|
||||
ok_callback = function() self:start() end,
|
||||
}:show()
|
||||
end
|
||||
|
||||
---@param gen integer
|
||||
---@param code string
|
||||
---@param authorize string
|
||||
---@param polls integer
|
||||
function QRLogin:_poll(gen, code, authorize, polls)
|
||||
if gen ~= self.generation then return end
|
||||
if polls > POLL_LIMIT or os.time() >= self.deadline then
|
||||
self:_retry(_("二维码已过期"))
|
||||
return
|
||||
end
|
||||
self:_request("qrStatusAsync", function(kind, err)
|
||||
if gen ~= self.generation then return end
|
||||
self.job = nil
|
||||
if kind == "ok" then
|
||||
self:_request("finishQrAsync", function(user, reason)
|
||||
if gen ~= self.generation then return end
|
||||
self.job = nil
|
||||
if not user then
|
||||
self:_retry(reason or _("登录失败"))
|
||||
return
|
||||
end
|
||||
self:cancel()
|
||||
if self.dialog then
|
||||
local dialog = self.dialog
|
||||
self.dialog = nil
|
||||
dialog:close()
|
||||
end
|
||||
self.on_user(user)
|
||||
end, authorize)
|
||||
return
|
||||
end
|
||||
if kind ~= "wait" then
|
||||
self:_retry(err or _("登录失败"))
|
||||
return
|
||||
end
|
||||
require("ui/uimanager"):scheduleIn(POLL_INTERVAL, function()
|
||||
if gen == self.generation then self:_poll(gen, code, authorize, polls + 1) end
|
||||
end)
|
||||
end, code)
|
||||
end
|
||||
|
||||
function QRLogin:start()
|
||||
self:cancel()
|
||||
self.session = Client.newLogin()
|
||||
local gen = self.generation
|
||||
self:_request("beginQrAsync", function(ticket, err)
|
||||
if gen ~= self.generation then return end
|
||||
self.job = nil
|
||||
if not ticket then
|
||||
self:toast(err or _("获取二维码失败"))
|
||||
return
|
||||
end
|
||||
local dialog
|
||||
dialog = require("ui.themes.widgets.qr"):new{
|
||||
title = _("豆瓣阅读扫码登录"),
|
||||
text = ticket.qr,
|
||||
caption = _("用豆瓣阅读 App 扫一扫"),
|
||||
close_callback = function()
|
||||
if self.dialog == dialog then
|
||||
self.dialog = nil
|
||||
self:cancel()
|
||||
self:toast(_("已取消登录"))
|
||||
end
|
||||
end,
|
||||
}
|
||||
self.dialog = dialog
|
||||
self.deadline = os.time() + ticket.expires_in
|
||||
dialog:show()
|
||||
self:_poll(gen, ticket.code, ticket.authorize, 1)
|
||||
end)
|
||||
end
|
||||
|
||||
return QRLogin
|
||||
@@ -0,0 +1,62 @@
|
||||
--[[--
|
||||
豆瓣阅读段评。
|
||||
|
||||
他人批注走 POST `/j/article_v2/<article>/annotations_by_paragraphs`。
|
||||
有 `note` 的才是段评,纯划线丢掉。段落序号按本章非空段,和章节 HTML 的 `<p>` 一致。
|
||||
|
||||
@module moonsource_douban.reviews
|
||||
--]]
|
||||
|
||||
local Client = require("moonsource_douban.client")
|
||||
local Mapper = require("moonsource_douban.mapper")
|
||||
|
||||
local Reviews = {}
|
||||
|
||||
---@param chapter BookChapter
|
||||
---@param cb fun(rows: table|nil, pids: string[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
local function load(chapter, cb)
|
||||
local handle = {}
|
||||
local start_pid = chapter.slice and tonumber(chapter.uid) or nil
|
||||
local end_pid = chapter.slice and tonumber(chapter.end_pid) or nil
|
||||
local pending = true
|
||||
local first = Client.articleAsync(chapter.content_url, function(article, err)
|
||||
pending = false
|
||||
if handle.cancelled then return end
|
||||
if not article then cb(nil, nil, err); return end
|
||||
local pids = Mapper.paragraphIds(article, start_pid, end_pid)
|
||||
handle.job = Client.annotationsAsync(chapter.content_url, pids, function(rows, reason)
|
||||
if handle.cancelled then return end
|
||||
if not rows then cb(nil, nil, reason); return end
|
||||
cb(rows, pids)
|
||||
end)
|
||||
end)
|
||||
if pending then handle.job = first end
|
||||
return { cancel = function()
|
||||
handle.cancelled = true
|
||||
if handle.job and handle.job.cancel then handle.job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param chapter BookChapter
|
||||
---@param cb fun(hotspots: table[]|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Reviews.hotspotsAsync(chapter, cb)
|
||||
return load(chapter, function(rows, pids, err)
|
||||
if not rows then cb(nil, err); return end
|
||||
cb(Mapper.reviewHotspots(rows, pids))
|
||||
end)
|
||||
end
|
||||
|
||||
---@param chapter BookChapter
|
||||
---@param range string|number
|
||||
---@param cb fun(page: table|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
function Reviews.pageAsync(chapter, range, cb)
|
||||
return load(chapter, function(rows, pids, err)
|
||||
if not rows then cb(nil, err); return end
|
||||
cb(Mapper.reviewPage(rows, pids, range))
|
||||
end)
|
||||
end
|
||||
|
||||
return Reviews
|
||||
@@ -0,0 +1,122 @@
|
||||
--[[--
|
||||
豆瓣阅读账号:App 扫码或电脑浏览器 Cookie。登录态是 read.douban.com 的 Cookie 和用户编号。
|
||||
|
||||
@module moonsource_douban.setting
|
||||
--]]
|
||||
|
||||
local _ = require("l10n").get("moonsource_douban")
|
||||
local CookieLogin = require("source.cookie_login")
|
||||
|
||||
local SOURCE_ID = "ext.douban"
|
||||
local Setting = {}
|
||||
local LOGIN_URL = "https://read.douban.com/oidc/login"
|
||||
|
||||
---@return boolean
|
||||
local function loggedIn()
|
||||
return require("moonsource_douban.client").loggedIn()
|
||||
end
|
||||
|
||||
---@param user { id: string, name: string }
|
||||
local function save(user)
|
||||
require("source.auth").ok(SOURCE_ID)
|
||||
require("source.registry").reload()
|
||||
local name = user.name ~= "" and user.name or _("已登录")
|
||||
require("ui.themes.widgets.toast"):new{ text = name, timeout = 2 }:show()
|
||||
end
|
||||
|
||||
local SPEC = {
|
||||
id = SOURCE_ID,
|
||||
title = _("豆瓣阅读账号"),
|
||||
cookie_title = _("豆瓣阅读登录 Cookie"),
|
||||
cookie_hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"),
|
||||
logout_text = _("确定退出豆瓣阅读账号?"),
|
||||
loggedIn = loggedIn,
|
||||
checkAsync = function(cookie, cb)
|
||||
local login = require("moonsource_douban.client").newLogin(cookie)
|
||||
return login:checkCookieAsync(function(ok, err, user)
|
||||
cb(ok, err, user and { user = user, login = login })
|
||||
end)
|
||||
end,
|
||||
commit = function(_cookie, candidate, cb)
|
||||
local ok, err = candidate.login:commit(candidate.user)
|
||||
if ok then
|
||||
require("source.auth").ok(SOURCE_ID)
|
||||
require("source.registry").reload()
|
||||
end
|
||||
cb(ok == true, err)
|
||||
end,
|
||||
}
|
||||
|
||||
Setting.browser = {
|
||||
domain = "read.douban.com",
|
||||
scope = "cookie",
|
||||
login = LOGIN_URL,
|
||||
check = "https://read.douban.com/",
|
||||
icon = "https://static.arkread.com/ark/pics/favicon/v6/favicon.10c09c23.ico",
|
||||
isAuthorized = function() return CookieLogin.authorized(SPEC) end,
|
||||
apply = function(payload, cb)
|
||||
local cookies = {}
|
||||
for _idx, cookie in ipairs(type(payload.cookies) == "table" and payload.cookies or {}) do
|
||||
local domain = type(cookie.domain) == "string" and cookie.domain:gsub("^%.", ""):lower()
|
||||
if domain == "douban.com" or domain == "read.douban.com" then cookies[#cookies + 1] = cookie end
|
||||
end
|
||||
return CookieLogin.save(SPEC, CookieLogin.fromPayload({ cookies = cookies }, "douban.com"), cb)
|
||||
end,
|
||||
}
|
||||
|
||||
---@return string, boolean
|
||||
function Setting.rowStatus()
|
||||
local on = loggedIn()
|
||||
return on and _("已登录") or _("未登录 · 点此扫码"), on
|
||||
end
|
||||
|
||||
function Setting.open()
|
||||
if not require("ui/network/manager"):isConnected() then
|
||||
require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show()
|
||||
return
|
||||
end
|
||||
require("moonsource_douban.qrlogin"):new(save):start()
|
||||
end
|
||||
|
||||
---@param plugin table|nil
|
||||
---@return table[]
|
||||
function Setting.rows(plugin)
|
||||
local Row = require("ui.themes.widgets.row")
|
||||
local rows = {
|
||||
function(iw)
|
||||
local status, status_on = Setting.rowStatus()
|
||||
return Row.widget({
|
||||
width = iw, chevron = true, kind = "nav", icon = "account_circle",
|
||||
title = SPEC.title,
|
||||
subtitle = _("打开豆瓣阅读 App,扫屏幕上的二维码"),
|
||||
status = status, status_on = status_on,
|
||||
callback = function() Setting.open() end,
|
||||
})
|
||||
end,
|
||||
}
|
||||
rows[#rows + 1] = function(iw)
|
||||
return Row.widget({
|
||||
width = iw, chevron = true, kind = "nav", icon = "sms",
|
||||
title = _("手机号验证码登录"),
|
||||
callback = function() require("moonsource_douban.phone_login"):new(save):start() end,
|
||||
})
|
||||
end
|
||||
rows[#rows + 1] = CookieLogin.browserRow()
|
||||
rows[#rows + 1] = CookieLogin.pasteRow(SPEC)
|
||||
rows[#rows + 1] = require("source.category_setting").row(SOURCE_ID, plugin)
|
||||
rows[#rows + 1] = require("source.review_setting").row(SOURCE_ID, plugin)
|
||||
if loggedIn() then
|
||||
rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出豆瓣阅读账号?"), function()
|
||||
local settings = require("utils.settings")
|
||||
local cfg = settings.getSource(SOURCE_ID)
|
||||
cfg.cookie, cfg.user_id, cfg.name, cfg.logged_in = nil, nil, nil, nil
|
||||
settings.saveSource(SOURCE_ID)
|
||||
require("moonsource_douban.client").reset()
|
||||
end)
|
||||
end
|
||||
return rows
|
||||
end
|
||||
|
||||
Setting.login = Setting.open
|
||||
|
||||
return Setting
|
||||
@@ -0,0 +1,456 @@
|
||||
--[[--
|
||||
豆瓣阅读数据源。
|
||||
|
||||
搜索和免费章节不需要登录。书架在 App 扫码后同步。
|
||||
进度按作品拉取;专栏再按章节 article 记一条,网站打开该章才能续上。
|
||||
阅读时长走 /j/reading_time。未购买的章节给一页提示,不当成缓存。
|
||||
|
||||
@module moonsource_douban
|
||||
--]]
|
||||
|
||||
local Client = require("moonsource_douban.client")
|
||||
local Browse = require("source.browse")
|
||||
local Mapper = require("moonsource_douban.mapper")
|
||||
local Shelf = require("source.shelf")
|
||||
local SourceBase = require("source.base")
|
||||
local Text = require("utils.text")
|
||||
local Toc = require("source.toc")
|
||||
local _ = require("l10n").get("moonsource_douban")
|
||||
|
||||
local Douban = {}
|
||||
|
||||
---@return BookSourceMeta
|
||||
function Douban.meta()
|
||||
return require("moonsource_douban.loadmeta")()
|
||||
end
|
||||
|
||||
---@class DoubanSource : SourceBase
|
||||
local Source = setmetatable({ shelf_add = true }, { __index = SourceBase })
|
||||
Source.__index = Source
|
||||
|
||||
---@return DoubanSource
|
||||
function Douban.new()
|
||||
local meta = Douban.meta()
|
||||
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
|
||||
end
|
||||
|
||||
---@return boolean
|
||||
function Source:configured()
|
||||
return Client.loggedIn()
|
||||
end
|
||||
|
||||
function Source:capabilities()
|
||||
local caps = SourceBase.capabilities(self)
|
||||
caps.stats_pull = true
|
||||
return caps
|
||||
end
|
||||
|
||||
local Remote = {}
|
||||
|
||||
function Remote:shelfSyncAsync(cb) return Client.shelfAsync(cb) end
|
||||
|
||||
---@param stable_id string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
function Remote:addToShelfAsync(stable_id, cb)
|
||||
return Client.addAsync(stable_id, cb)
|
||||
end
|
||||
|
||||
---@param stable_id string
|
||||
---@param cb fun(ok: boolean|nil, err: string|nil)
|
||||
function Remote:removeFromShelfAsync(stable_id, cb)
|
||||
return Client.removeAsync(stable_id, cb)
|
||||
end
|
||||
|
||||
function Source:syncBooksAsync(opts, cb)
|
||||
if not self:configured() then return SourceBase.skipped(cb, "douban not logged in") end
|
||||
return Shelf.syncAsync(self.id, Remote, function(books) return books end, opts, cb)
|
||||
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 { node?: string, limit?: integer }|nil
|
||||
---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil)
|
||||
function Source:browseAsync(opts, cb)
|
||||
local limit = opts and opts.limit or 60
|
||||
local channel, category, sort, pay, state = (opts and opts.node or ""):match(
|
||||
"^(%a+):(%d+):([%a_]+):(%a+):(%a+)$")
|
||||
if channel ~= "publish" then channel = "original" end
|
||||
local root = channel == "original" and "0" or "1"
|
||||
category, sort, pay, state = category or root, sort or "hot", pay or "all", state or "all"
|
||||
local sorts = {
|
||||
{ id = "hot", title = _("热门") }, { id = "new", title = _("最新") },
|
||||
{ id = "sales", title = _("销量") }, { id = "rating", title = _("好评") },
|
||||
}
|
||||
if channel == "publish" then
|
||||
state = "all"
|
||||
sorts[#sorts + 1] = { id = "price_asc", title = _("价格最低") }
|
||||
sorts[#sorts + 1] = { id = "book_rating", title = _("豆瓣高分") }
|
||||
end
|
||||
local valid_sort = false
|
||||
for _idx, row in ipairs(sorts) do if row.id == sort then valid_sort = true end end
|
||||
if not valid_sort then sort = "hot" end
|
||||
if pay ~= "free" and (pay ~= "paid" or channel ~= "publish") then pay = "all" end
|
||||
if state ~= "serial" and state ~= "complete" then state = "all" end
|
||||
local handle, pending = {}, true
|
||||
local initial = Client.categoriesAsync(function(categories, err)
|
||||
pending = false
|
||||
if handle.cancelled then return end
|
||||
if not categories then cb(nil, err); return end
|
||||
local valid_category = category == root
|
||||
for _idx, row in ipairs(categories[channel]) do if row.id == category then valid_category = true end end
|
||||
if not valid_category then category = root end
|
||||
local values = { channel, category, sort, pay, state }
|
||||
local function chips(title, rows, position)
|
||||
local list = {}
|
||||
for _idx, row in ipairs(rows) do
|
||||
local node = { unpack(values) }
|
||||
node[position] = row.id
|
||||
if position == 1 then node[2], node[3], node[4], node[5] = row.id == "publish" and "1" or "0", "hot", "all", "all" end
|
||||
list[#list + 1] = { id = table.concat(node, ":"), title = row.title }
|
||||
end
|
||||
local current = { unpack(values) }
|
||||
if position == 1 then current[2], current[3], current[4], current[5] = root, "hot", "all", "all" end
|
||||
local group = Browse.group(list, table.concat(current, ":"))
|
||||
group.title = title
|
||||
return group
|
||||
end
|
||||
local cats = { { id = root, title = _("全部") } }
|
||||
for _idx, row in ipairs(categories[channel]) do cats[#cats + 1] = row end
|
||||
local prices = { { id = "all", title = _("全部") }, { id = "free", title = _("免费") } }
|
||||
if channel == "publish" then prices[#prices + 1] = { id = "paid", title = _("付费") } end
|
||||
local groups = {
|
||||
chips(nil, { { id = "original", title = _("原创") }, { id = "publish", title = _("出版") } }, 1),
|
||||
chips(_("分类"), cats, 2),
|
||||
chips(_("排序"), sorts, 3),
|
||||
chips(_("价格"), prices, 4),
|
||||
}
|
||||
if channel == "original" then
|
||||
groups[#groups + 1] = chips(_("状态"), {
|
||||
{ id = "all", title = _("全部") }, { id = "serial", title = _("连载中") },
|
||||
{ id = "complete", title = _("已完结") },
|
||||
}, 5)
|
||||
end
|
||||
handle.job = Browse.pages(function(page, done)
|
||||
return Client.catalogAsync({ category = category, sort = sort, pay = pay, state = state }, page, done)
|
||||
end, limit, groups, function(result, reason)
|
||||
if result then
|
||||
for idx = #result.data, limit + 1, -1 do result.data[idx] = nil end
|
||||
end
|
||||
if not handle.cancelled then cb(result, reason) end
|
||||
end)
|
||||
end)
|
||||
if pending then handle.job = initial end
|
||||
function handle.cancel()
|
||||
handle.cancelled = true
|
||||
if handle.job then handle.job.cancel() end
|
||||
end
|
||||
return handle
|
||||
end
|
||||
|
||||
function Source:getDetailAsync(identity, cb)
|
||||
return Client.detailAsync(identity.stable_id, function(book, err)
|
||||
if book then cb(require("book.store").rememberDetail(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
|
||||
|
||||
---@param self DoubanSource
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
|
||||
local function fetchTocAsync(self, identity, cb)
|
||||
return Client.tocAsync(identity.stable_id, function(toc, err)
|
||||
if not toc then cb(nil, err); return end
|
||||
if #toc == 0 then cb(nil, _("豆瓣阅读目录为空")); return end
|
||||
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
|
||||
cb(toc)
|
||||
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
|
||||
or not require("ui/network/manager"):isConnected()) then
|
||||
return SourceBase.defer(cb, cached)
|
||||
end
|
||||
end
|
||||
return fetchTocAsync(self, identity, cb)
|
||||
end
|
||||
|
||||
Source.refreshTocAsync = fetchTocAsync
|
||||
|
||||
---@param self DoubanSource
|
||||
---@param open boolean
|
||||
---@return ChapterFetchContent
|
||||
local function fetcher(self, open)
|
||||
return function(_identity, chapter, done)
|
||||
if chapter.vip then
|
||||
if not open then done(nil, _("本章未购买")); return end
|
||||
local notice = string.format(_("这是 VIP 章节,你还没有购买。\n请先在%s购买本章,再回来阅读。"), self.name)
|
||||
done({ title = chapter.title, html = Text.chapterHtml(chapter.title, notice), temporary = true })
|
||||
return
|
||||
end
|
||||
local start_pid = chapter.slice and tonumber(chapter.uid) or nil
|
||||
local end_pid = chapter.slice and tonumber(chapter.end_pid) or nil
|
||||
return Client.textAsync(chapter.content_url, start_pid, end_pid, function(text, err)
|
||||
if text then
|
||||
local html = Text.chapterHtml(chapter.title, text)
|
||||
if not chapter.slice and self:paragraphReviewsEnabled() then
|
||||
html = require("book.review_locate").prepareChapterEnd(html)
|
||||
end
|
||||
done({ title = chapter.title, html = html })
|
||||
return
|
||||
end
|
||||
done(nil, err)
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
local function reuseChapterEnd(self, identity)
|
||||
if not self:paragraphReviewsEnabled() then return nil end
|
||||
return function(path)
|
||||
local toc = Toc.read(self.id, identity.stable_id)
|
||||
if toc and toc[1] and not toc[1].slice then
|
||||
return require("book.review_locate").reuseChapterEnd(path)
|
||||
end
|
||||
return true
|
||||
end
|
||||
end
|
||||
|
||||
function Source:openBookAsync(identity, opts, cb)
|
||||
local Chapter = require("source.chapter")
|
||||
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
|
||||
return open(self, identity, identity.book, opts, {
|
||||
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
|
||||
fetchContent = fetcher(self, true),
|
||||
reuse = reuseChapterEnd(self, identity),
|
||||
}, cb)
|
||||
end
|
||||
|
||||
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
|
||||
local Chapter = require("source.chapter")
|
||||
return Chapter.prefetchAsync(identity, identity.book, toc, from_idx, count, {
|
||||
fetchContent = fetcher(self, false),
|
||||
reuse = reuseChapterEnd(self, identity),
|
||||
}, cb)
|
||||
end
|
||||
|
||||
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
|
||||
local Chapter = require("source.chapter")
|
||||
return Chapter.cacheAllAsync(self, identity, fetcher(self, false), on_progress, cb, nil, range,
|
||||
reuseChapterEnd(self, identity))
|
||||
end
|
||||
|
||||
---@param toc BookChapter[]
|
||||
---@param paragraph_id string
|
||||
---@return integer|nil
|
||||
local function chapterAt(toc, paragraph_id)
|
||||
local pid = tonumber(paragraph_id)
|
||||
for idx, chapter in ipairs(toc) do
|
||||
if chapter.uid == paragraph_id then return idx end
|
||||
if chapter.slice and pid then
|
||||
local start_pid = tonumber(chapter.uid)
|
||||
local end_pid = tonumber(chapter.end_pid)
|
||||
if start_pid and pid >= start_pid and (not end_pid or pid < end_pid) then return idx end
|
||||
end
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function Source:getProgressAsync(identity, cb)
|
||||
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
local cancelled, progress_job, toc_job = false, nil, nil
|
||||
progress_job = Client.progressAsync(identity.stable_id, function(mark, err)
|
||||
if cancelled then return end
|
||||
if err then cb(nil, err); return end
|
||||
if not mark then cb(nil, nil, { empty = true }); return end
|
||||
toc_job = self:loadTocAsync(identity, function(toc, reason)
|
||||
if cancelled then return end
|
||||
if not toc or #toc == 0 then cb(nil, reason or _("豆瓣阅读目录为空")); return end
|
||||
local idx = chapterAt(toc, mark.paragraph_id)
|
||||
if not idx then cb(nil, nil, { empty = true }); return end
|
||||
cb({
|
||||
chapter_idx = idx,
|
||||
chapter_title = toc[idx].title,
|
||||
fraction = (idx - 1) / #toc,
|
||||
extra = { chapter_uid = toc[idx].uid, chapter_idx = idx },
|
||||
})
|
||||
end)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if progress_job then progress_job.cancel() end
|
||||
if toc_job then toc_job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
function Source:putProgressAsync(identity, pos, cb)
|
||||
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
local cancelled = false
|
||||
local toc_job, works_job, article_job
|
||||
toc_job = self:loadTocAsync(identity, function(toc, err)
|
||||
if cancelled then return end
|
||||
if not toc then cb(nil, err); return end
|
||||
local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
|
||||
local chapter = idx and toc[idx]
|
||||
if not chapter then cb(nil, _("缺少豆瓣阅读章节位置")); return end
|
||||
local function posted(ok, perr)
|
||||
if cancelled then return end
|
||||
cb(ok and true or nil, perr)
|
||||
end
|
||||
article_job = Client.articleAsync(chapter.content_url, function(article, article_err)
|
||||
if cancelled then return end
|
||||
if not article then cb(nil, article_err); return end
|
||||
local pid = chapter.slice and chapter.uid or Mapper.firstParagraphId(article)
|
||||
local position = pid and Mapper.progressPosition(article, pid, chapter.end_pid)
|
||||
if not position then cb(nil, _("缺少豆瓣阅读章节位置")); return end
|
||||
local works_id = chapter.slice and identity.stable_id or chapter.content_url
|
||||
works_job = Client.putProgressAsync(works_id, position.paragraph_id, idx, #toc, chapter.slice == true, posted, position)
|
||||
end)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
for _idx, job in pairs({ toc_job, works_job, article_job }) do
|
||||
job.cancel()
|
||||
end
|
||||
end }
|
||||
end
|
||||
|
||||
---@param seconds integer
|
||||
---@return string
|
||||
local function iso(seconds)
|
||||
return os.date("!%Y-%m-%dT%H:%M:%S", seconds) .. ".000Z"
|
||||
end
|
||||
|
||||
function Source:pushStatsAsync(rows, cb)
|
||||
if not self:configured() then return SourceBase.defer(cb, nil, _("未登录豆瓣阅读")) end
|
||||
local sessions, ids = {}, {}
|
||||
for _idx, row in ipairs(rows or {}) do
|
||||
local start_time = tonumber(row.start_time)
|
||||
local duration = tonumber(row.duration)
|
||||
if row.id and start_time and duration and duration > 0 and type(row.stable_id) == "string" and row.stable_id ~= "" then
|
||||
sessions[#sessions + 1] = {
|
||||
worksId = tonumber(row.stable_id) or row.stable_id,
|
||||
beginTime = iso(start_time),
|
||||
endTime = iso(start_time + duration),
|
||||
}
|
||||
ids[#ids + 1] = row.id
|
||||
elseif row.id then
|
||||
ids[#ids + 1] = row.id
|
||||
end
|
||||
end
|
||||
if #sessions == 0 then return SourceBase.defer(cb, { synced_ids = ids }) end
|
||||
return Client.pushReadingAsync(sessions, function(ok, err)
|
||||
if not ok then cb(nil, err); return end
|
||||
cb({ synced_ids = ids })
|
||||
end)
|
||||
end
|
||||
|
||||
function Source:pullStatsAsync(cb)
|
||||
local fetched_at = os.time()
|
||||
local date = os.date("*t", fetched_at)
|
||||
date.day, date.hour, date.min, date.sec = date.day - 29, 0, 0, 0
|
||||
date.isdst = nil
|
||||
local begin_date = os.date("%Y-%m-%d", os.time(date))
|
||||
return Client.readingStatsAsync(begin_date, function(wire, err)
|
||||
if not wire then cb(nil, err); return end
|
||||
cb(Mapper.readingStats(wire, begin_date, fetched_at))
|
||||
end)
|
||||
end
|
||||
|
||||
function Source:paragraphReviewsEnabled()
|
||||
return require("source.review_setting").enabled(self.id)
|
||||
end
|
||||
|
||||
---@param identity BookIdentity
|
||||
---@param cb fun(chapter: BookChapter|nil, err: string|nil)
|
||||
---@return { cancel: fun() }
|
||||
local function chapterOf(self, identity, cb)
|
||||
local cancelled, job = false, nil
|
||||
job = self:loadTocAsync(identity, function(toc, err)
|
||||
if cancelled then return end
|
||||
local chapter = toc and toc[tonumber(identity.chapter_idx)]
|
||||
if not chapter or type(chapter.content_url) ~= "string" or chapter.content_url == "" then
|
||||
cb(nil, err or _("豆瓣阅读目录为空"))
|
||||
return
|
||||
end
|
||||
cb(chapter)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if job and job.cancel then job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
function Source:paragraphHotspotsAsync(identity, cb)
|
||||
local cancelled, chapter_job, review_job = false, nil, nil
|
||||
chapter_job = chapterOf(self, identity, function(chapter, err)
|
||||
if cancelled then return end
|
||||
if not chapter then cb(nil, err); return end
|
||||
review_job = require("moonsource_douban.reviews").hotspotsAsync(chapter, function(rows, reason)
|
||||
if not cancelled then cb(rows, reason) end
|
||||
end)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if chapter_job then chapter_job.cancel() end
|
||||
if review_job then review_job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
function Source:locateHotspots(hotspots, html)
|
||||
local ReviewLocate = require("book.review_locate")
|
||||
return ReviewLocate.locate(ReviewLocate.paragraphs(html), hotspots, html)
|
||||
end
|
||||
|
||||
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
|
||||
if range == "chapter" then
|
||||
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.communityAsync(identity.stable_id, uid, max_idx, finish)
|
||||
end, done)
|
||||
end, cb)
|
||||
end
|
||||
local cancelled, chapter_job, review_job = false, nil, nil
|
||||
chapter_job = chapterOf(self, identity, function(chapter, err)
|
||||
if cancelled then return end
|
||||
if not chapter then cb(nil, err); return end
|
||||
review_job = require("moonsource_douban.reviews").pageAsync(chapter, range, function(page, reason)
|
||||
if not cancelled then cb(page, reason) end
|
||||
end)
|
||||
end)
|
||||
return { cancel = function()
|
||||
cancelled = true
|
||||
if chapter_job then chapter_job.cancel() end
|
||||
if review_job then review_job.cancel() end
|
||||
end }
|
||||
end
|
||||
|
||||
function Source:bookReviewsAsync(identity, cb)
|
||||
local ref = { source_id = self.id, stable_id = identity.stable_id }
|
||||
return require("book.review_cache").pageAsync(ref, "book", 0, function(done)
|
||||
return Client.communityAsync(identity.stable_id, nil, 0, 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
|
||||
if page.unsupported then cb({}); return end
|
||||
cb({ { range = "chapter", text = identity.book and identity.book.title or "",
|
||||
total = page.total, badge = tostring(page.total), heading = _("章节评论"),
|
||||
anchor = require("book.review_locate").CHAPTER_ANCHOR } })
|
||||
end)
|
||||
end
|
||||
|
||||
return Douban
|
||||
Reference in new issue
Block a user