✨ (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
@@ -0,0 +1,56 @@
return {
["LinguoLand"] = "LinguoLand",
["LinguoLand 英文原版阅读"] = "LinguoLand English reading",
["邮箱密码登录"] = "Email and password",
["邮箱验证码登录"] = "Email code",
["手机验证码登录"] = "SMS code",
["浏览器登录"] = "Browser sign-in",
["书架同步"] = "Shelf sync",
["书城浏览"] = "Catalog",
["进度拉取"] = "Progress download",
["进度上传"] = "Progress upload",
["请求失败"] = "Request failed",
["响应无效"] = "Invalid response",
["目录为空"] = "Empty table of contents",
["目录保存失败"] = "Could not save the table of contents",
["书籍文件地址无效"] = "Invalid book file URL",
["暂无书籍详情"] = "No book details",
["登录已失效"] = "Sign-in expired",
["未登录"] = "Not signed in",
["登录失败"] = "Sign-in failed",
["登录成功"] = "Signed in",
["正在登录…"] = "Signing in…",
["正在校验登录…"] = "Checking sign-in…",
["验证码已发送"] = "Code sent",
["LinguoLand 账号"] = "LinguoLand account",
["邮箱"] = "Email",
["密码"] = "Password",
["验证码"] = "Code",
["手机号"] = "Phone",
["发送验证码"] = "Send code",
["登录"] = "Sign in",
["请填写邮箱"] = "Enter an email",
["请填写密码"] = "Enter a password",
["请填写正确的手机号"] = "Enter a valid phone number",
["请先填写验证码"] = "Enter the code",
["网络不可用,请先连接 Wi-Fi"] = "No network. Connect to Wi-Fi first",
["已登录"] = "Signed in",
["未登录 · 点此登录"] = "Not signed in · tap to sign in",
["确定退出 LinguoLand 账号?"] = "Sign out of LinguoLand?",
["没有读到登录令牌"] = "No sign-in token",
["粘贴登录令牌"] = "Paste sign-in token",
["按 F12,点「应用」里的本地存储,复制 linguoland.access_token"] = "Press F12, open Application → Local storage, and copy linguoland.access_token",
["linguoland.refresh_token,没有就留空"] = "linguoland.refresh_token, or leave empty",
["账号已变化,请重新登录"] = "Account changed. Sign in again",
["准备本地同步失败"] = "Could not prepare local sync",
["这是游客会话,请先在官网登录"] = "This is a guest session. Sign in on the website first",
["缺少书架条目 ID"] = "Missing shelf entry",
["书籍标识无效"] = "Invalid book id",
["未知书名"] = "Unknown title",
["未知作者"] = "Unknown author",
["合集无书籍列表"] = "This collection has no books",
["没有可换算的阅读位置"] = "No reading position to convert",
["书籍文件还没下载"] = "The book file is not downloaded yet",
["这个格式没有 CFI"] = "This format has no CFI",
["位置换算失败"] = "Could not convert the reading position",
}
@@ -0,0 +1,56 @@
return {
["LinguoLand"] = "LinguoLand",
["LinguoLand 英文原版阅读"] = "LinguoLand 英文原版閱讀",
["邮箱密码登录"] = "郵箱密碼登入",
["邮箱验证码登录"] = "郵箱驗證碼登入",
["手机验证码登录"] = "手機驗證碼登入",
["浏览器登录"] = "瀏覽器登入",
["书架同步"] = "書架同步",
["书城浏览"] = "書城瀏覽",
["进度拉取"] = "進度拉取",
["进度上传"] = "進度上傳",
["请求失败"] = "請求失敗",
["响应无效"] = "響應無效",
["目录为空"] = "目錄為空",
["目录保存失败"] = "目錄保存失敗",
["书籍文件地址无效"] = "書籍檔案地址無效",
["暂无书籍详情"] = "暫無書籍詳情",
["登录已失效"] = "登入已失效",
["未登录"] = "未登入",
["登录失败"] = "登入失敗",
["登录成功"] = "登入成功",
["正在登录…"] = "正在登入…",
["正在校验登录…"] = "正在校驗登入…",
["验证码已发送"] = "驗證碼已發送",
["LinguoLand 账号"] = "LinguoLand 帳號",
["邮箱"] = "郵箱",
["密码"] = "密碼",
["验证码"] = "驗證碼",
["手机号"] = "手機號",
["发送验证码"] = "發送驗證碼",
["登录"] = "登入",
["请填写邮箱"] = "請填寫郵箱",
["请填写密码"] = "請填寫密碼",
["请填写正确的手机号"] = "請填寫正確的手機號",
["请先填写验证码"] = "請先填寫驗證碼",
["网络不可用,请先连接 Wi-Fi"] = "網路不可用,請先連線 Wi-Fi",
["已登录"] = "已登入",
["未登录 · 点此登录"] = "未登入 · 點此登入",
["确定退出 LinguoLand 账号?"] = "確定退出 LinguoLand 帳號?",
["没有读到登录令牌"] = "沒有讀到登入令牌",
["粘贴登录令牌"] = "貼上登入令牌",
["按 F12,点「应用」里的本地存储,复制 linguoland.access_token"] = "按 F12,點「應用程式」裡的本地儲存,複製 linguoland.access_token",
["linguoland.refresh_token,没有就留空"] = "linguoland.refresh_token,沒有就留空",
["账号已变化,请重新登录"] = "帳號已變化,請重新登入",
["准备本地同步失败"] = "準備本地同步失敗",
["这是游客会话,请先在官网登录"] = "這是遊客工作階段,請先在官網登入",
["缺少书架条目 ID"] = "缺少書架條目 ID",
["书籍标识无效"] = "書籍標識無效",
["未知书名"] = "未知書名",
["未知作者"] = "未知作者",
["合集无书籍列表"] = "合集無書籍列表",
["没有可换算的阅读位置"] = "沒有可換算的閱讀位置",
["书籍文件还没下载"] = "書籍檔案還沒下載",
["这个格式没有 CFI"] = "這個格式沒有 CFI",
["位置换算失败"] = "位置換算失敗",
}
@@ -0,0 +1,92 @@
--[[--
LinguoLand 数据映射。将 API 响应转换为月读书源标准数据结构。
@module moonsource_linguoland.mapper
--]]
local Mapper = {}
local _ = require("l10n").get("moonsource_linguoland")
--- 只要字符串。JSON null 在没洗过的回包里是函数,不能进书名和简介。
local function str(value)
if type(value) == "string" and value ~= "" then return value end
end
--- 书架条目 → Book[]
---@param entries table[]
---@return table[]
function Mapper.shelfBooks(entries)
local books = {}
for _idx, entry in ipairs(entries) do
local catalog = entry.catalog
if catalog then
local storage_ref = str(catalog.storageRef) or ""
local book = {
source_id = "linguoland",
stable_id = tostring(catalog.id),
title = str(entry.titleOverride) or str(catalog.title) or _("未知书名"),
authors = str(entry.authorOverride) or str(catalog.author) or _("未知作者"),
cover = str(catalog.coverUrl) or "",
intro = str(catalog.description) or "",
category = str(catalog.level) or "",
meta = {
language = str(catalog.language),
source = {
shelf_entry_id = entry.id,
storage_ref = storage_ref,
origin = str(entry.origin),
format = str(catalog.format),
},
},
}
if storage_ref ~= "" then book._epub_url = storage_ref end
books[#books + 1] = book
end
end
return books
end
--- 书城目录条目 → Book[]
---@param items table[]
---@return table[]
function Mapper.catalogBooks(items)
local books = {}
for _idx, item in ipairs(items) do
local storage_ref = str(item.storageRef) or ""
local book = {
source_id = "linguoland",
stable_id = tostring(item.id),
title = str(item.title) or _("未知书名"),
authors = str(item.author) or _("未知作者"),
cover = str(item.coverUrl) or "",
intro = str(item.description) or "",
category = str(item.level) or "",
meta = {
language = str(item.language),
source = {
storage_ref = storage_ref,
format = str(item.format),
},
},
}
if storage_ref ~= "" then book._epub_url = storage_ref end
books[#books + 1] = book
end
return books
end
--- 合集列表 → BrowseChipGroup[]
---@param collections table[]
---@return table[]
function Mapper.collectionsToGroups(collections)
local groups = {}
for _idx, col in ipairs(collections) do
groups[#groups + 1] = {
id = tostring(col.id),
title = col.title or col.titleI18n and col.titleI18n["zh-CN"] or "",
}
end
return groups
end
return Mapper
@@ -0,0 +1,303 @@
--[[--
LinguoLand 账号。邮箱密码、邮箱验证码、手机短信在设备上填写。
浏览器扩展读 read.linguoland.com 的 localStorage,不读 Cookie。
@module moonsource_linguoland.setting
--]]
local _ = require("l10n").get("moonsource_linguoland")
local CookieLogin = require("source.cookie_login")
local SOURCE_ID = "linguoland"
local Setting = {}
local LOGIN_URL = "https://read.linguoland.com/login"
local function client()
return require("moonsource_linguoland.client")
end
local function loggedIn()
return client().isLoggedIn()
end
local function clearAccount(cfg)
cfg.token, cfg.refresh_token, cfg.account_id = nil, nil, nil
end
--- 浏览器扩展登录:令牌在 localStorage,不在 Cookie。
Setting.browser = {
domain = "read.linguoland.com",
scope = "local",
login = LOGIN_URL,
check = "https://read.linguoland.com/shelf",
icon = "https://read.linguoland.com/icon.png",
isAuthorized = function()
return loggedIn() and not require("source.auth").expired(SOURCE_ID)
end,
apply = function(payload, cb)
local storage = payload["local"]
local access = type(storage) == "table" and storage["linguoland.access_token"] or nil
local refresh = type(storage) == "table" and storage["linguoland.refresh_token"] or nil
if type(access) ~= "string" or access == "" then
cb(false, _("没有读到登录令牌"))
return
end
if type(refresh) ~= "string" or refresh == "" then refresh = nil end
client().commitSession(access, refresh, cb)
end,
}
local function connected()
if require("ui/network/manager"):isConnected() then return true end
require("ui.themes.widgets.toast"):new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show()
return false
end
---@param access string|nil
---@param refresh string|nil
---@param err string|nil
---@param waiting table|nil
---@param dialog table|nil
---@param closed fun(): boolean
local function finishLogin(access, refresh, err, waiting, dialog, closed)
local Toast = require("ui.themes.widgets.toast")
if not access then
if waiting then waiting:close() end
if not closed() then Toast:new{ text = err or _("登录失败"), timeout = 3 }:show() end
return
end
client().commitSession(access, refresh, function(ok, message)
if waiting then waiting:close() end
if closed() then return end
if not ok then Toast:new{ text = message or _("登录失败"), timeout = 3 }:show(); return end
if dialog then dialog:close() end
Toast:new{ text = _("登录成功"), timeout = 2 }:show()
end)
end
---@param title string
---@param text string
---@return table
local function waitingDialog(title, text)
return require("ui.themes.widgets.progress_dialog"):new{
title = title, text = text, dismissable = false,
}
end
local function showPasswordLogin()
local Toast = require("ui.themes.widgets.toast")
local closed, job, waiting, dialog = false, nil, nil, nil
dialog = require("ui.themes.widgets.input"):new{
title = _("LinguoLand 账号"),
keep_open = true,
fields = {
{ label = _("邮箱"), text = "" },
{ label = _("密码"), text = "", text_type = "password" },
},
ok_text = _("登录"),
close_callback = function()
closed = true
if job and job.cancel then job:cancel() end
if waiting then waiting:close(); waiting = nil end
end,
callback = function(email, password)
email = require("utils.text").trim(email)
if email == "" then Toast:new{ text = _("请填写邮箱"), timeout = 3 }:show(); return end
if password == "" then Toast:new{ text = _("请填写密码"), timeout = 3 }:show(); return end
if not connected() then return end
waiting = waitingDialog(_("LinguoLand 账号"), _("正在登录…"))
waiting:show()
job = client().loginAsync(email, password, function(access, refresh, err)
job = nil
finishLogin(access, refresh, err, waiting, dialog, function() return closed end)
waiting = nil
end)
end,
}
dialog:show()
end
local function showEmailCodeLogin()
local Toast = require("ui.themes.widgets.toast")
local closed, job, waiting, dialog = false, nil, nil, nil
dialog = require("ui.themes.widgets.input"):new{
title = _("邮箱验证码登录"),
keep_open = true,
fields = {
{ label = _("邮箱"), text = "" },
{ label = _("验证码"), text = "", input_type = "number" },
},
ok_text = _("登录"),
close_callback = function()
closed = true
if job and job.cancel then job:cancel() end
if waiting then waiting:close(); waiting = nil end
end,
actions = {
{ text = _("发送验证码"), callback = function(email)
email = require("utils.text").trim(email)
if email == "" then Toast:new{ text = _("请填写邮箱"), timeout = 3 }:show(); return end
if not connected() then return end
if job and job.cancel then job:cancel() end
job = client().sendEmailCodeAsync(email, function(ok, err)
job = nil
if closed then return end
Toast:new{ text = ok and _("验证码已发送") or (err or _("登录失败")), timeout = 3 }:show()
end)
end },
},
callback = function(email, code)
email = require("utils.text").trim(email)
code = require("utils.text").trim(code)
if email == "" then Toast:new{ text = _("请填写邮箱"), timeout = 3 }:show(); return end
if code == "" then Toast:new{ text = _("请先填写验证码"), timeout = 3 }:show(); return end
if not connected() then return end
waiting = waitingDialog(_("LinguoLand 账号"), _("正在登录…"))
waiting:show()
if job and job.cancel then job:cancel() end
job = client().loginWithEmailCodeAsync(email, code, function(access, refresh, err)
job = nil
finishLogin(access, refresh, err, waiting, dialog, function() return closed end)
waiting = nil
end)
end,
}
dialog:show()
end
local function validPhone(phone)
return phone:match("^1[3-9]%d%d%d%d%d%d%d%d%d$") ~= nil
end
local function showSmsLogin()
local Toast = require("ui.themes.widgets.toast")
local closed, job, waiting, dialog = false, nil, nil, nil
dialog = require("ui.themes.widgets.input"):new{
title = _("手机验证码登录"),
keep_open = true,
fields = {
{ label = _("手机号"), text = "", input_type = "number" },
{ label = _("验证码"), text = "", input_type = "number" },
},
ok_text = _("登录"),
close_callback = function()
closed = true
if job and job.cancel then job:cancel() end
if waiting then waiting:close(); waiting = nil end
end,
actions = {
{ text = _("发送验证码"), callback = function(phone)
phone = phone:gsub("%D", "")
if not validPhone(phone) then
Toast:new{ text = _("请填写正确的手机号"), timeout = 3 }:show()
return
end
if not connected() then return end
if job and job.cancel then job:cancel() end
job = client().sendSmsCodeAsync(phone, function(ok, err)
job = nil
if closed then return end
Toast:new{ text = ok and _("验证码已发送") or (err or _("登录失败")), timeout = 3 }:show()
end)
end },
},
callback = function(phone, code)
phone = phone:gsub("%D", "")
code = require("utils.text").trim(code)
if not validPhone(phone) then
Toast:new{ text = _("请填写正确的手机号"), timeout = 3 }:show()
return
end
if code == "" then Toast:new{ text = _("请先填写验证码"), timeout = 3 }:show(); return end
if not connected() then return end
waiting = waitingDialog(_("LinguoLand 账号"), _("正在登录…"))
waiting:show()
if job and job.cancel then job:cancel() end
job = client().loginWithSmsCodeAsync(phone, code, function(access, refresh, err)
job = nil
finishLogin(access, refresh, err, waiting, dialog, function() return closed end)
waiting = nil
end)
end,
}
dialog:show()
end
local function showTokenLogin()
require("ui.themes.widgets.input"):new{
title = _("粘贴登录令牌"),
fields = {
{ text = "", hint = _("按 F12,点「应用」里的本地存储,复制 linguoland.access_token") },
{ text = "", hint = _("linguoland.refresh_token,没有就留空") },
},
ok_text = _("登录"),
callback = function(access, refresh)
access = require("utils.text").trim(access or "")
refresh = require("utils.text").trim(refresh or "")
if access == "" then
require("ui.themes.widgets.toast"):new{ text = _("没有读到登录令牌"), timeout = 3 }:show()
return
end
if not connected() then return end
local waiting = waitingDialog(_("LinguoLand 账号"), _("正在校验登录…"))
waiting:show()
client().commitSession(access, refresh ~= "" and refresh or nil, function(ok, err)
waiting:close()
require("ui.themes.widgets.toast"):new{
text = ok and _("登录成功") or (err or _("登录失败")), timeout = ok and 2 or 3,
}:show()
end)
end,
}:show()
end
function Setting.rowStatus()
local on = loggedIn()
return on and _("已登录") or _("未登录 · 点此登录"), on
end
function Setting.rows()
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 = _("LinguoLand 账号"), subtitle = _("邮箱密码登录"),
status = status, status_on = status_on, callback = showPasswordLogin,
})
end,
function(iw)
return Row.widget({
width = iw, chevron = true, kind = "nav", icon = "mail",
title = _("邮箱验证码登录"), callback = showEmailCodeLogin,
})
end,
function(iw)
return Row.widget({
width = iw, chevron = true, kind = "nav", icon = "sms",
title = _("手机验证码登录"), callback = showSmsLogin,
})
end,
CookieLogin.browserRow(),
function(iw)
return Row.widget({
width = iw, chevron = true, kind = "nav", icon = "key",
title = _("粘贴登录令牌"), callback = showTokenLogin,
})
end,
}
if loggedIn() then
rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出 LinguoLand 账号?"), function()
local settings = require("utils.settings")
local cfg = settings.getSource(SOURCE_ID)
clearAccount(cfg)
settings.saveSource(SOURCE_ID, cfg)
end)
end
return rows
end
Setting.login = showPasswordLogin
return Setting