✨ (auth): 接上登录和书架协议

邮箱、验证码和浏览器本地令牌登录。书架只收书城书,加入和删除都走官网接口。
This commit is contained in:
Garfield committed 2026-11-27 00:51:41 +08:00
1 parent 8ff04cee9b
commit 285d4cc487
5 files changed
+1117

No files matched your search

@@ -0,0 +1,610 @@
--[[--
LinguoLand HTTP 客户端。
API:https://api.linguoland.com 。登录态是 Bearer JWT,不在 Cookie 里。
官网把 access / refresh 放在 read.linguoland.com 的 localStorage
(linguoland.access_token、linguoland.refresh_token)。
access 过期用 refresh_token 换一次;换不回来才算登录失效。
未登录时书城走游客会话(guest-init),只放在 guest_token,不当成账号。
书架、进度只走已登录用户的 token。
进度百分比是 0..1 的全书比例。上传的 locator 必须是已经换算好的 EPUB CFI。
@module moonsource_linguoland.client
--]]
local JSON = require("json")
local Mapper = require("moonsource_linguoland.mapper")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_linguoland")
local Client = {}
local API = "https://api.linguoland.com"
local SOURCE_ID = "linguoland"
local function settings()
return require("utils.settings").getSource(SOURCE_ID)
end
local function saveSettings()
require("utils.settings").saveSource(SOURCE_ID, settings())
end
--- LuaJSON 把 null 解成函数。函数在 Lua 里为真,`or` 会拿它盖住后面的真书名。
local function denull(value)
if type(value) == "function" then return nil end
if type(value) ~= "table" then return value end
local holes = {}
for key, item in pairs(value) do
local next_item = denull(item)
if next_item == nil then
holes[#holes + 1] = key
else
value[key] = next_item
end
end
for _idx, key in ipairs(holes) do
value[key] = nil
end
return value
end
local function decode(raw)
if type(raw) ~= "string" or raw == "" then return nil end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then return nil end
return denull(wire)
end
local function bare(token)
if type(token) ~= "string" then return "" end
if token:sub(1, 7) == "Bearer " then return token:sub(8) end
return token
end
function Client.token()
return bare(settings().token)
end
function Client.isLoggedIn()
return Client.token() ~= "" and not require("source.auth").expired(SOURCE_ID)
end
local function deviceId()
local cfg = settings()
local id = cfg.device_id
if type(id) == "string" and #id >= 16 then return id end
id = string.format("moon-%08x%08x", os.time(), math.random(0, 0x7fffffff))
cfg.device_id = id
saveSettings()
return id
end
--- 服务端中文 message 优先;否则用调用方给的兜底。
---@param res table|nil
---@param fallback string
---@return string
local function failText(res, fallback)
local wire = decode(res and res.body)
local message = wire and wire.message
if type(message) == "string" and message ~= "" and message:find("[\128-\255]") then
return message
end
return fallback
end
local function timeout(kind)
return require("http.timeout").net(kind)
end
local function http(method, path, payload, token, cb)
local headers = { Accept = "application/json" }
if token ~= "" then headers.Authorization = "Bearer " .. token end
if method == "GET" then
return Request.get(API .. path, { timeout = timeout(1), headers = headers }, function(raw, err, res)
cb(raw, err, res)
end)
end
if method == "POST" then
return Request.post(API .. path, payload and JSON.encode(payload) or "{}", {
timeout = timeout(2),
content_type = "application/json; charset=utf-8",
headers = headers,
}, function(raw, err, res)
cb(raw, err, res)
end)
end
return Request.request({
url = API .. path, method = method,
timeout = timeout(1), headers = headers,
}, function(res, err)
local code = res and tonumber(res.code)
if err or not res or not Request.ok(code) then
cb(nil, err or failText(res, _("请求失败")), res)
return
end
cb(res.body or "", nil, res)
end)
end
local refresh_wait
local function finishRefresh(ok)
local waiters = refresh_wait
refresh_wait = nil
for _idx, waiter in ipairs(waiters) do waiter(ok) end
end
--- 同一个 refresh_token 只能换一次,并发 401 共用这一次。
local function refreshUser(cb)
if refresh_wait then
refresh_wait[#refresh_wait + 1] = cb
return
end
refresh_wait = { cb }
local cfg = settings()
local refresh = type(cfg.refresh_token) == "string" and cfg.refresh_token or ""
local previous = bare(cfg.token)
if refresh == "" or previous == "" then return finishRefresh(false) end
http("POST", "/api/v1/auth/refresh", { refresh_token = refresh }, "", function(raw, err, _res)
local wire = decode(raw)
local access = wire and bare(wire.access_token)
if err or not access or access == "" then return finishRefresh(false) end
cfg = settings()
if bare(cfg.token) ~= previous then return finishRefresh(false) end
cfg.token = access
if type(wire.refresh_token) == "string" and wire.refresh_token ~= "" then
cfg.refresh_token = wire.refresh_token
end
saveSettings()
require("source.auth").ok(SOURCE_ID)
finishRefresh(true)
end)
end
--- 带用户 token 的请求。401 且有 refresh_token 时换票重试一次。
---@param method string
---@param path string
---@param payload table|nil
---@param cb fun(raw: string|nil, err: string|nil)
---@return { cancel: fun() }
local function authed(method, path, payload, cb)
local cancelled, job = false, nil
local function run(retried)
if cancelled then return end
local token = Client.token()
if token == "" then
cb(nil, _("未登录"))
return
end
job = http(method, path, payload, token, function(raw, err, res)
if cancelled then return end
local code = res and tonumber(res.code)
if code == 401 and not retried and type(settings().refresh_token) == "string"
and settings().refresh_token ~= "" then
refreshUser(function(ok)
if cancelled then return end
if ok then run(true); return end
cb(nil, require("source.auth").expire(SOURCE_ID, _("登录已失效")))
end)
return
end
if code == 401 then
cb(nil, require("source.auth").expire(SOURCE_ID, failText(res, _("登录已失效"))))
return
end
if err or raw == nil then
cb(nil, failText(res, err and tostring(err) or _("请求失败")))
return
end
require("source.auth").ok(SOURCE_ID)
cb(raw)
end)
end
run(false)
return { cancel = function()
cancelled = true
if job and job.cancel then job:cancel() end
end }
end
local function guestToken()
return bare(settings().guest_token)
end
--- 书城在未登录时用游客 token。已登录(含未过期)走用户 token。
---@param cb fun(token: string|nil, err: string|nil)
---@return { cancel: fun() }
local function ensureReadToken(cb)
if Client.isLoggedIn() then
cb(Client.token())
return { cancel = function() end }
end
local existing = guestToken()
if existing ~= "" then
cb(existing)
return { cancel = function() end }
end
local pending = true
local job = http("POST", "/api/v1/auth/guest-init", { deviceId = deviceId() }, "", function(raw, err, res)
pending = false
local wire = decode(raw)
local access = wire and bare(wire.access_token)
if not access or access == "" then
cb(nil, failText(res, err and tostring(err) or _("请求失败")))
return
end
local cfg = settings()
cfg.guest_token = access
if type(wire.refresh_token) == "string" and wire.refresh_token ~= "" then
cfg.guest_refresh = wire.refresh_token
end
saveSettings()
cb(access)
end)
if not pending then return { cancel = function() end } end
return job
end
---@param path string
---@param cb fun(wire: table|nil, err: string|nil)
---@return { cancel: fun() }
local function readJson(path, cb)
local function parsed(raw, err)
if not raw then cb(nil, err); return end
local wire = decode(raw)
if not wire then cb(nil, _("响应无效")); return end
cb(wire)
end
if Client.isLoggedIn() then
return authed("GET", path, nil, parsed)
end
local cancelled, job, retried = false, nil, false
local function fetch()
if cancelled then return end
job = ensureReadToken(function(token, err)
if cancelled then return end
if not token then cb(nil, err); return end
job = http("GET", path, nil, token, function(raw, req_err, res)
if cancelled then return end
if res and tonumber(res.code) == 401 and not retried then
retried = true
local cfg = settings()
cfg.guest_token, cfg.guest_refresh = nil, nil
saveSettings()
fetch()
return
end
if req_err or raw == nil then
cb(nil, failText(res, req_err and tostring(req_err) or _("请求失败")))
return
end
parsed(raw)
end)
end)
end
fetch()
return { cancel = function()
cancelled = true
if job and job.cancel then job:cancel() end
end }
end
local function tokensFrom(wire)
local access = wire and bare(wire.access_token)
if not access or access == "" then return nil end
local refresh = type(wire.refresh_token) == "string" and wire.refresh_token or nil
return access, refresh
end
--- 用这次登录拿到的 token 查 profile。通过且不是游客才写入。
--- 账号 id 变了走换号:保留本地书,不把旧墓碑推到新账号。
---@param access string
---@param refresh string|nil
---@param cb fun(ok: boolean, err: string|nil)
---@return { cancel: fun() }
function Client.commitSession(access, refresh, cb)
access = bare(access)
if access == "" then
cb(false, _("没有读到登录令牌"))
return { cancel = function() end }
end
local current = require("source.auth").beginLogin(SOURCE_ID)
local pending = true
local job = http("GET", "/api/v1/auth/profile", nil, access, function(raw, err, res)
pending = false
if not current() then cb(false, _("账号已变化,请重新登录")); return end
local wire = decode(raw)
if err or not wire or wire.id == nil then
cb(false, failText(res, err and tostring(err) or _("登录失败")))
return
end
if wire.tier == "GUEST" then
cb(false, _("这是游客会话,请先在官网登录"))
return
end
local account_id = tostring(wire.id)
local cfg = settings()
local switching = (type(cfg.account_id) == "string" and cfg.account_id ~= account_id)
or (cfg.account_id == nil and type(cfg.token) == "string" and cfg.token ~= "" and bare(cfg.token) ~= access)
local function write()
cfg.token = access
cfg.refresh_token = refresh
cfg.account_id = account_id
saveSettings()
end
if switching then
if not require("source.logout").replaceLibrary(SOURCE_ID, write) then
cb(false, _("准备本地同步失败"))
return
end
else
write()
require("source.registry").reload()
end
require("source.auth").ok(SOURCE_ID)
cb(true)
end)
if not pending then return { cancel = function() end } end
return job
end
---@param email string
---@param password string
---@param cb fun(access: string|nil, refresh: string|nil, err: string|nil)
function Client.loginAsync(email, password, cb)
return http("POST", "/api/v1/auth/login", { email = email, password = password }, "", function(raw, err, res)
local wire = decode(raw)
local access, refresh = tokensFrom(wire)
if not access then
cb(nil, nil, failText(res, wire and wire.message or err and tostring(err) or _("登录失败")))
return
end
cb(access, refresh)
end)
end
---@param email string
---@param cb fun(ok: boolean, err: string|nil)
function Client.sendEmailCodeAsync(email, cb)
return http("POST", "/api/v1/auth/email-code", { email = email, purpose = "LOGIN" }, "", function(raw, err, res)
if err or not decode(raw) then cb(false, failText(res, err and tostring(err) or _("请求失败"))); return end
cb(true)
end)
end
---@param email string
---@param code string
---@param cb fun(access: string|nil, refresh: string|nil, err: string|nil)
function Client.loginWithEmailCodeAsync(email, code, cb)
return http("POST", "/api/v1/auth/email-code/login", { email = email, code = code }, "", function(raw, err, res)
local wire = decode(raw)
local access, refresh = tokensFrom(wire)
if not access then
cb(nil, nil, failText(res, wire and wire.message or err and tostring(err) or _("登录失败")))
return
end
cb(access, refresh)
end)
end
---@param phone string
---@param cb fun(ok: boolean, err: string|nil)
function Client.sendSmsCodeAsync(phone, cb)
return http("POST", "/api/v1/auth/sms-code", { phone = phone, purpose = "LOGIN" }, "", function(raw, err, res)
if err or not decode(raw) then cb(false, failText(res, err and tostring(err) or _("请求失败"))); return end
cb(true)
end)
end
---@param phone string
---@param code string
---@param cb fun(access: string|nil, refresh: string|nil, err: string|nil)
function Client.loginWithSmsCodeAsync(phone, code, cb)
return http("POST", "/api/v1/auth/sms-code/login", {
phone = phone, code = code, deviceId = deviceId(),
}, "", function(raw, err, res)
local wire = decode(raw)
local access, refresh = tokensFrom(wire)
if not access then
cb(nil, nil, failText(res, wire and wire.message or err and tostring(err) or _("登录失败")))
return
end
cb(access, refresh)
end)
end
---@param cb fun(books: table[]|nil, err: string|nil)
function Client.getShelfAsync(cb)
if not Client.isLoggedIn() then
cb(nil, _("未登录"))
return { cancel = function() end }
end
return authed("GET", "/api/v1/shelf", nil, function(raw, err)
if not raw then cb(nil, err); return end
local wire = decode(raw)
if not wire or type(wire.entries) ~= "table" then cb(nil, _("响应无效")); return end
cb(Mapper.shelfBooks(wire.entries))
end)
end
function Client:shelfSyncAsync(cb)
return Client.getShelfAsync(cb)
end
---@param stable_id string
---@param cb fun(wire: table|nil, err: string|nil)
function Client:addToShelfAsync(stable_id, cb)
local catalog_id = tonumber(stable_id)
if not catalog_id then
cb(nil, _("书籍标识无效"))
return { cancel = function() end }
end
return authed("POST", "/api/v1/shelf/from-catalog", { catalogId = catalog_id }, function(raw, err)
if not raw then cb(nil, err); return end
local wire = decode(raw)
if not wire then cb(nil, _("响应无效")); return end
local entry_id = tonumber(wire.id)
if entry_id then
local BookDB = require("book.books_db")
local row = BookDB.get(SOURCE_ID, stable_id)
local source = row and row.meta and row.meta.source or {}
source.shelf_entry_id = entry_id
BookDB.setMeta({ source_id = SOURCE_ID, stable_id = stable_id, meta = { source = source } }, true)
end
cb(wire)
end)
end
---@param stable_id string
---@param cb fun(ok: boolean|nil, err: string|nil)
function Client:removeFromShelfAsync(stable_id, cb)
local BookDB = require("book.books_db")
local row = BookDB.get(SOURCE_ID, stable_id)
local source = row and row.meta and row.meta.source
local entry_id = source and tonumber(source.shelf_entry_id)
if not entry_id then
cb(nil, _("缺少书架条目 ID"))
return { cancel = function() end }
end
return authed("DELETE", "/api/v1/shelf/" .. string.format("%d", entry_id), nil, function(raw, err)
if err then cb(nil, err); return end
cb(true)
end)
end
---@param cb fun(books: table[]|nil, err: string|nil)
function Client.getCatalogAsync(cb)
return readJson("/api/v1/catalog", function(wire, err)
if not wire then cb(nil, err); return end
if type(wire.items) ~= "table" then cb(nil, _("响应无效")); return end
cb(Mapper.catalogBooks(wire.items))
end)
end
---@param cb fun(collections: table[]|nil, err: string|nil)
function Client.getCollectionsAsync(cb)
return readJson("/api/v1/catalog/collections", function(wire, err)
if not wire then cb(nil, err); return end
if type(wire.collections) ~= "table" then cb(nil, _("响应无效")); return end
cb(wire.collections)
end)
end
---@param collectionId integer
---@param cb fun(books: table[]|nil, err: string|nil)
function Client.getCollectionBooksAsync(collectionId, cb)
local id = tonumber(collectionId)
if not id then cb(nil, _("响应无效")); return { cancel = function() end } end
return readJson("/api/v1/catalog/collections/" .. string.format("%d", id), function(wire, err)
if not wire then cb(nil, err); return end
if type(wire.items) ~= "table" then cb(nil, _("合集无书籍列表")); return end
cb(Mapper.catalogBooks(wire.items))
end)
end
---@param keyword string
---@param cb fun(books: table[]|nil, err: string|nil)
function Client.searchAsync(keyword, cb)
if keyword == "" then
cb({})
return { cancel = function() end }
end
return readJson("/api/v1/catalog?q=" .. Text.urlEncode(keyword), function(wire, err)
if not wire then cb(nil, err); return end
if type(wire.items) ~= "table" then cb(nil, _("响应无效")); return end
cb(Mapper.catalogBooks(wire.items))
end)
end
--- 全书比例 0..1。大于 1 的旧数据按百分数折回来。
---@param value any
---@return number|nil
local function fractionOf(value)
local n = tonumber(value)
if not n then return nil end
if n > 1 then n = n / 100 end
if n < 0 then return 0 end
if n > 1 then return 1 end
return n
end
---@param shelfEntryId integer
---@param cb fun(progress: { locator: string|nil, percent: number }|nil, err: string|nil)
function Client.getProgressAsync(shelfEntryId, cb)
local id = tonumber(shelfEntryId)
if not id then cb(nil, _("缺少书架条目 ID")); return { cancel = function() end } end
return authed("GET", "/api/v1/reading-progress/by-shelf-entry/" .. string.format("%d", id), nil, function(raw, err)
if not raw then cb(nil, err); return end
local wire = decode(raw)
local progress = wire and wire.progress
if type(progress) ~= "table" then cb(nil); return end
local row = progress
if progress.percent == nil and progress.locator == nil then row = progress[1] end
if type(row) ~= "table" then cb(nil); return end
local percent = fractionOf(row.percent)
if percent == nil and type(row.locator) ~= "string" then cb(nil); return end
cb({ locator = row.locator, percent = percent or 0 })
end)
end
local ACCEPTED = {
accepted = true,
["preserved-anti-rollback"] = true,
["preserved-stale-base"] = true,
}
--- 先读服务端 updatedAt,再按官网的 flush 体上传。三种收下都算成功,避免回滚保护把同一版反复重推。
---@param shelfEntryId integer
---@param locator string
---@param percent number|nil
---@param cb fun(ok: true|nil, err: string|nil)
---@return { cancel: fun() }
function Client.putProgressAsync(shelfEntryId, locator, percent, cb)
local id = tonumber(shelfEntryId)
if not id or type(locator) ~= "string" or locator:sub(1, 8) ~= "epubcfi(" then
cb(nil, _("位置换算失败"))
return { cancel = function() end }
end
local fraction = fractionOf(percent)
local cancelled, job = false, nil
job = authed("GET", "/api/v1/reading-progress/by-shelf-entry/" .. string.format("%d", id), nil, function(raw, err)
if cancelled then return end
if not raw then cb(nil, err); return end
local wire = decode(raw)
local progress = wire and wire.progress
local base
if type(progress) == "table" then
local row = progress
if progress.percent == nil and progress.locator == nil and progress.updatedAt == nil then
row = progress[1]
end
if type(row) == "table" and type(row.updatedAt) == "string" and row.updatedAt ~= "" then
base = row.updatedAt
end
end
local payload = { shelfEntryId = id, locator = locator }
if fraction ~= nil then payload.percent = fraction end
if base then payload.baseUpdatedAt = base end
job = authed("POST", "/api/v1/reading-progress", payload, function(posted, post_err)
if cancelled then return end
local body = decode(posted)
local disposition = body and body.disposition
local updated = body and type(body.progress) == "table" and body.progress.updatedAt
if type(updated) == "string" and updated ~= "" and ACCEPTED[disposition] then
cb(true)
return
end
cb(nil, post_err or _("请求失败"))
end)
end)
return { cancel = function()
cancelled = true
if job and job.cancel then job:cancel() end
end }
end
return Client