12 Commits
Author SHA1 Message Date
GarfieldandCopilot c9ecc00861 🔖 (release): 发布 0.4.1
Release / release (push) Successful in 13s
Co-authored-by: Copilot <[email protected]>
2026-12-03 14:55:00 +08:00
GarfieldandCopilot b4ff3791f1 🐛 (shelf): 微信书架待导入快照只弹一次导入页,普通刷新不再重复弹窗
Co-authored-by: Copilot <[email protected]>
2026-12-03 14:55:00 +08:00
Garfield d77606c6f8 ✅ (tests): 跟进月读会话接口,修复过期的笔记用例 2026-12-02 10:54:18 +08:00
Garfield 3c2d1e7b95 🔖 (release): 发布 0.4.0
Release / release (push) Successful in 13s
2026-12-02 09:20:37 +08:00
Garfield 338e2d2d3c 🔒 (notes): 新想法默认私有,设置里可改可见范围
公开和仅关注只对新想法生效。已有想法沿用原来记下的范围。
2026-12-01 15:37:10 +08:00
Garfield 352ee1bd99 🐛 (notes): 想法按私密阅读设置发表并回读
新想法跟这本书的私密阅读走,修改已有想法沿用原来的可见范围。
回读对不上就当这轮失败,不把 HTTP 成功当成已经私密。
2026-12-01 12:47:12 +08:00
Garfield 69a72f63c0 ✨ (search): 搜索书目带上译者 2026-11-30 21:07:54 +08:00
Garfield fb35a0560d 🔖 (release): 发布 0.3.0
Release / release (push) Successful in 10s
2026-11-27 09:08:52 +08:00
Garfield f1dba1ae51 💄 (setting): 账号页使用书源自己的图标 2026-11-27 08:46:38 +08:00
Garfield 7b3eeb8fe6 🐛 (reviews): 评论配图带上微信阅读来源
空地址丢掉。没有图时不给出图片列表。

关联 #148
2026-11-26 16:55:31 +08:00
Garfield a890c230ac ✨ (search): 书目搜索带上作者参数
/store/search 的 author 不再写死为空。不传时仍是空串。
2026-11-26 15:52:52 +08:00
Garfield f4f8386a61 🔥 去掉书源自己的在线更新 2026-11-25 21:22:51 +08:00
26 changed files with 616 additions and 579 deletions

No files matched your search

+17
View File
@@ -1,5 +1,22 @@
# 更新日志
## 0.4.1
- :bug: (shelf): 微信书架待导入快照只弹一次导入页,普通刷新不再重复弹窗
## 0.4.0
- :lock: (notes): 新想法默认私有,设置里可改可见范围
- :bug: (notes): 想法按私密阅读设置发表并回读
- :sparkles: (search): 搜索书目带上译者
## 0.3.0
- :lipstick: (setting): 账号页使用书源自己的图标
- :bug: (reviews): 评论配图带上微信阅读来源
- :sparkles: (search): 书目搜索带上作者参数
- 🔥 去掉书源自己的在线更新
## 0.0.1
- 「微信读书」书源拆成独立仓库,独立发版、独立更新;原来所有书源同版本一起更新的做法取消。
+1 -1
View File
@@ -11,7 +11,7 @@
| 阅读进度同步 | 支持 | 开书比较云端位置;本地先落盘,阅读中合并推送,离线保留待同步数据 |
| 阅读时长同步 | 支持 | 上传本地采集时长及补报数据 |
| 维持官网「在读」状态 | 已实现,未实测 | 零时长 Web 心跳,不重复增加阅读时长 |
| 划线与想法同步 | 支持 | 走属主书籍的注解接口 |
| 划线与想法同步 | 支持 | 新想法默认私有,设置里可改成公开或仅关注。修改已有想法沿用原来的范围,并回读确认 |
| 整书书评与独立章评 | 不支持 | 未接入可验证接口,不能把其他书籍的想法当作属主书评 |
| 段评与回复 | 支持 | 按章节及文本范围定位,使用公共评论标记和列表 |
| 离线阅读 | 支持 | 已下载内容和本地记录可用;联网后再同步 |
@@ -9,13 +9,10 @@ local function lazy(module)
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
end
require("moonsource_weread.update").register()
return {
api = 1,
provides = {
source = true,
features = { setting = { entries = function(desktop) return require("moonsource_weread.update").entries(desktop) end } },
},
meta = function() return require("moonsource_weread.source").meta() end,
new = function() require("moonsource_weread.legacy").run() return require("moonsource_weread.source").new() end,
@@ -22,7 +22,6 @@ local Toc = require("moonsource_weread.toc")
local Client = require("moonsource_weread.client")
local Mem = require("utils.mem")
local Context = require("moonsource_weread.context")
local Mapper = require("moonsource_weread.mapper")
local _ = require("l10n").get("moonsource_weread")
local Chapter = {}
@@ -74,12 +73,12 @@ local function downloadPackageAsync(bookId, chapters, book_type, pick, cb, opts)
fail(err)
return
end
local version = Mapper.bookVersion(wire)
Context.rememberBook(bookId, wire)
local version = Context.bookVersion(bookId)
if not version then
fail(_("缺少书籍版本"))
return
end
Context.rememberBookVersion(bookId, version)
download(attempt, version)
end)
if not fired then call = next_call end
@@ -72,11 +72,12 @@ end
--- 书城搜索(App ``GET /store/search``)。回包书在 ``data[]``,每条 ``bookInfo``;补成 ``books[]`` 交给 mapper。
---@param keyword string
---@param cb fun(data: table|nil, err: string|nil)
---@param author string|nil 作者过滤;旧调用不传,查询里仍是空串
---@return { cancel: fun() }|nil
function Client:searchAsync(keyword, cb)
function Client:searchAsync(keyword, cb, author)
return Eink.callAsync("GET", "/store/search", {
query = {
keyword = keyword, author = "", authorVids = "", categoryId = "",
keyword = keyword, author = type(author) == "string" and author or "", authorVids = "", categoryId = "",
count = 20, maxIdx = 0, type = 0, v = 2, outer = 0, fromBookId = "",
scope = 0, scene = 0, filterType = 0, filterField = "", queryUid = "", isQueryWord = 0,
},
@@ -137,6 +138,7 @@ function Client:shelfSyncAsync(cb, spill, open_import)
local ok, werr = ShelfImport.stash(data.body)
Awake.hold("wechat_shelf", false)
if ok and open_import then
ShelfImport.prompted = true
require("utils.extension").call("web.open_page", ShelfImport.PAGE, _("微信书架导入"), ShelfImport.TOO_LARGE)
end
cb(nil, ok and ShelfImport.TOO_LARGE or werr)
@@ -7,6 +7,7 @@ App 进度与时长走 App ``POST /book/read``;Web 在读状态用独立的网
--]]
local Protocol = require("moonsource_weread.protocol")
local Mapper = require("moonsource_weread.mapper")
local Context = {}
@@ -24,6 +25,8 @@ local readers = {}
local sessions = {}
---@type table<string, number>
local book_version_by_id = {}
---@type table<string, integer>
local book_secret_by_id = {}
---@class WechatReportSession
---@field psvts string
@@ -88,17 +91,34 @@ function Context.rememberBookVersion(book_id, version)
end
end
--- 从书籍详情记下版本号和私密阅读。认不出的字段不覆盖已有值。
---@param book_id string
---@param wire table|nil
function Context.rememberBook(book_id, wire)
Context.rememberBookVersion(book_id, Mapper.bookVersion(wire))
local secret = Mapper.bookSecret(wire)
if secret ~= nil then book_secret_by_id[book_id] = secret end
end
---@param book_id string
---@return number|nil
function Context.bookVersion(book_id)
return book_version_by_id[book_id]
end
--- 这本书是否私密阅读。没读过详情是 nil,不是公开。
---@param book_id string
---@return integer|nil
function Context.bookSecret(book_id)
return book_secret_by_id[book_id]
end
--- 清空进程内缓存的 reader 状态与书籍版本号(换账号或登出后必须调)。
function Context.clear()
readers = {}
sessions = {}
book_version_by_id = {}
book_secret_by_id = {}
end
return Context
@@ -24,6 +24,13 @@ return {
["试读结束"] = "Trial ended",
["想法上传失败"] = "Failed to upload note",
["想法上传成功但缺少 reviewId"] = "Note upload succeeded without a reviewId",
["想法默认可见"] = "Default note visibility",
["公开"] = "Public",
["仅关注"] = "Mutuals only",
["私有"] = "Private",
["点按切换。仅关注是互相关注可见,只影响新想法"] = "Tap to change. Mutuals only means visible to people you follow each other. New notes only",
["无法确认想法是否私密"] = "Cannot confirm whether the note is private",
["想法的可见范围没有按设置保存"] = "The note visibility was not saved as requested",
["按章书籍请打开章节后同步划线"] = "Open a chapter first to sync highlights",
["无法定位划线范围"] = "Cannot locate highlight range",
["无法开始登录"] = "Cannot start login",
@@ -24,6 +24,13 @@ return {
["试读结束"] = "試讀結束",
["想法上传失败"] = "想法上傳失敗",
["想法上传成功但缺少 reviewId"] = "想法上傳成功但缺少 reviewId",
["想法默认可见"] = "想法預設可見",
["公开"] = "公開",
["仅关注"] = "僅關注",
["私有"] = "私有",
["点按切换。仅关注是互相关注可见,只影响新想法"] = "點按切換。僅關注是互相關注可見,只影響新想法",
["无法确认想法是否私密"] = "無法確認想法是否私密",
["想法的可见范围没有按设置保存"] = "想法的可見範圍沒有按設定保存",
["按章书籍请打开章节后同步划线"] = "分章書籍請開啟章節後再同步劃線",
["无法定位划线范围"] = "無法定位劃線範圍",
["无法开始登录"] = "無法開始登入",
@@ -126,6 +126,19 @@ function Mapper.bookVersion(wire)
return tonumber(book.version or book.bookVersion or wire.version or wire.bookVersion)
end
--- 书籍详情 wire → 私密阅读。``secret==1`` 为 1,明确不是私密阅读为 0,认不出书就 nil。
---@param wire table|nil
---@return integer|nil
function Mapper.bookSecret(wire)
if type(wire) ~= "table" then return nil end
local book = type(wire.book) == "table" and wire.book or wire
if book.secret == nil and book.bookId == nil and book.version == nil and book.bookVersion == nil then
return nil
end
if book.secret == 1 or book.secret == true then return 1 end
return 0
end
--- 微信专辑 → Book(及封面 URL)。
---@param album table
---@return Book|nil, string|nil
@@ -355,6 +368,7 @@ end
---@field book_id string
---@field title string
---@field author string
---@field translator string 空串表示接口没给译者
---@field publisher string
--- 搜索 wire → 书目(只留带 bookId 的书,公众号等其它条目没有 bookInfo)。
@@ -369,6 +383,7 @@ function Mapper.searchBooks(data)
book_id = tostring(info.bookId),
title = info.title or "",
author = info.author or "",
translator = type(info.translator) == "string" and info.translator or "",
publisher = info.publisher or "",
}
end
@@ -33,7 +33,7 @@ local LOCAL_COLOR = {
}
local WR_FIELDS = {
"wr_range", "wr_bookmark_id", "wr_review_id", "wr_review_only",
"wr_range", "wr_bookmark_id", "wr_review_id", "wr_review_only", "wr_private", "wr_friendship",
"wr_delete_review", "wr_update_review", "wr_update_bookmark",
}
@@ -47,6 +47,8 @@ local WR_FIELDS = {
---@field wr_bookmark_id string|number|nil
---@field wr_range string|nil
---@field wr_review_id string|number|nil
---@field wr_private integer|nil 0 公开,1 仅自己可见
---@field wr_friendship integer|nil 1 仅互相关注可见
---@field wr_deleted boolean|nil
---@field chapter_idx number|nil
---@field datetime string|nil
@@ -76,6 +78,51 @@ local function unwrapReview(entry)
return type(review) == "table" and review or nil
end
--- 想法上的 ``isPrivate``:1 仅自己可见,0 公开。没有这个字段就返回 nil,不能当成公开。
---@param review table|nil
---@return integer|nil
function Notes.privateOf(review)
if type(review) ~= "table" then return nil end
local body = type(review.review) == "table" and review.review or review
local flag = body.isPrivate
if flag == 1 or flag == true then return 1 end
if flag == 0 or flag == false then return 0 end
return nil
end
--- 想法上的 ``friendship``:1 仅互相关注可见。没有这个字段就返回 nil。
---@param review table|nil
---@return integer|nil
function Notes.friendshipOf(review)
if type(review) ~= "table" then return nil end
local body = type(review.review) == "table" and review.review or review
local flag = body.friendship
if flag == 1 or flag == true then return 1 end
if flag == 0 or flag == false then return 0 end
return nil
end
--- 发表/修改要带的可见范围。已有想法没记过时两个都是 nil,请求里就不带。
--- choice 为设置项:public / follow。没设过或 private 都是私有。
---@param annotation table
---@param book_secret integer|boolean|nil 保留参数,新想法不再看私密阅读
---@param choice string|nil
---@return integer|nil is_private
---@return integer|nil friendship
function Notes.reviewFlags(annotation, book_secret, choice)
local function known(value)
if value == 1 or value == true then return 1 end
if value == 0 or value == false then return 0 end
return nil
end
local private, friendship = known(annotation.wr_private), known(annotation.wr_friendship)
if private ~= nil or friendship ~= nil then return private, friendship end
if annotation.wr_review_id ~= nil then return nil, nil end
if choice == "public" then return 0, 0 end
if choice == "follow" then return 0, 1 end
return 1, 0
end
---@param items table[]|nil
---@param total_pages integer|nil
---@return table[]
@@ -452,6 +499,14 @@ function Notes.reconcileReviews(annotations, wire)
end
if review then
item.wr_review_id = review.reviewId
if item.wr_private ~= 0 and item.wr_private ~= 1 then
local private = Notes.privateOf(review)
if private ~= nil then item.wr_private = private end
end
if item.wr_friendship ~= 0 and item.wr_friendship ~= 1 then
local friendship = Notes.friendshipOf(review)
if friendship ~= nil then item.wr_friendship = friendship end
end
confirmed[item] = true
end
end
@@ -517,6 +572,10 @@ function Notes.toAnnotations(wire, chapter_uid, reviews, source_id, stable_id)
ann.wr_range = range ~= "" and range or nil
ann.wr_bookmark_id = row.bookmarkId or row.id
ann.wr_review_id = review and review.reviewId or nil
local private = review and Notes.privateOf(review) or nil
if private ~= nil then ann.wr_private = private end
local friendship = review and Notes.friendshipOf(review) or nil
if friendship ~= nil then ann.wr_friendship = friendship end
out[#out + 1] = ann
end
end
@@ -538,6 +597,10 @@ function Notes.toAnnotations(wire, chapter_uid, reviews, source_id, stable_id)
ann.note = content
ann.wr_range = range
ann.wr_review_id = review.reviewId or entry.reviewId
local private = Notes.privateOf(review)
if private ~= nil then ann.wr_private = private end
local friendship = Notes.friendshipOf(review)
if friendship ~= nil then ann.wr_friendship = friendship end
ann.wr_review_only = true
out[#out + 1] = ann
end
@@ -562,6 +625,7 @@ function Notes.keepLocalReviews(annotations, local_items)
local ann = old.wr_bookmark_id and by_bookmark[tostring(old.wr_bookmark_id)] or nil
if ann then
ann.note, ann.wr_review_id = old.note, old.wr_review_id
ann.wr_private, ann.wr_friendship = old.wr_private, old.wr_friendship
elseif old.wr_review_only then
annotations[#annotations + 1] = old
end
@@ -672,13 +736,16 @@ function Notes.toBookmarkUpdateBody(annotation)
}
end
--- KOReader 注解 → ``/web/review/add`` 请求体。
--- KOReader 注解 → ``/review/add`` 请求体。
--- 新想法按设置项;没设过时私有。已有想法沿用记下来的范围。
---@param book_id string
---@param chapter_uid string|number
---@param annotation table
---@param book_secret integer|boolean|nil
---@param choice string|nil public / private / follow
---@return table|nil body
---@return string|nil err
function Notes.toReviewBody(book_id, chapter_uid, annotation)
function Notes.toReviewBody(book_id, chapter_uid, annotation, book_secret, choice)
local content = annotation.note
if type(content) ~= "string" or content == "" then
return nil, "empty note"
@@ -691,28 +758,34 @@ function Notes.toReviewBody(book_id, chapter_uid, annotation)
if type(abstract) ~= "string" or abstract == "" then
return nil, "missing highlight text"
end
return {
local body = {
bookId = tostring(book_id),
content = content,
type = 1,
range = range,
abstract = abstract,
chapterUid = tonumber(chapter_uid) or chapter_uid,
}, nil
}
local private, friendship = Notes.reviewFlags(annotation, book_secret, choice)
if private ~= nil then body.isPrivate = private end
if friendship ~= nil then body.friendship = friendship end
return body, nil
end
--- KOReader 注解 → ``/web/review/edit`` 请求体。
--- KOReader 注解 → ``/review/useredit`` 请求体。
---@param book_id string
---@param chapter_uid string|number
---@param annotation table
---@param book_secret integer|boolean|nil
---@param choice string|nil
---@return table|nil body
---@return string|nil err
function Notes.toReviewEditBody(book_id, chapter_uid, annotation)
function Notes.toReviewEditBody(book_id, chapter_uid, annotation, book_secret, choice)
local review_id = annotation.wr_review_id
if type(review_id) ~= "string" and type(review_id) ~= "number" then
return nil, "missing review id"
end
local body, err = Notes.toReviewBody(book_id, chapter_uid, annotation)
local body, err = Notes.toReviewBody(book_id, chapter_uid, annotation, book_secret, choice)
if not body then return nil, err end
body.reviewId = tostring(review_id)
return body, nil
@@ -13,7 +13,6 @@ local Annotations = require("book.annotations")
local Toc = require("moonsource_weread.toc")
local Position = require("moonsource_weread.progress")
local Context = require("moonsource_weread.context")
local Mapper = require("moonsource_weread.mapper")
local _ = require("l10n").get("moonsource_weread")
---@class WechatNotesPush
@@ -263,12 +262,12 @@ function Push:withBookVersion(candidates)
self:call(function(done)
return self.client:bookInfoAsync(self.book_id, done)
end, nil, function(wire)
version = Mapper.bookVersion(wire)
Context.rememberBook(self.book_id, wire)
version = Context.bookVersion(self.book_id)
if not version then
self:finish(nil, _("缺少书籍版本"))
return
end
Context.rememberBookVersion(self.book_id, version)
self:bookmarks(version, candidates)
end)
end
@@ -329,9 +328,53 @@ function Push:updates()
end, function() self:reviews() end)
end
--- 发表或修改之后读回可见范围。对不上就停,不把 HTTP 成功当成已经按设置生效。
---@param item table
---@param wanted_private integer|nil
---@param wanted_friendship integer|nil
---@param next fun()
function Push:confirmPrivate(item, wanted_private, wanted_friendship, next)
if wanted_private ~= nil then item.wr_private = wanted_private end
if wanted_friendship ~= nil then item.wr_friendship = wanted_friendship end
item.wr_update_review = true
self:call(function(done)
return self.client:reviewSingleAsync(item.wr_review_id, 0, 1, done)
end, _("无法确认想法是否私密"), function(wire)
local got = Notes.privateOf(wire)
local got_friendship = Notes.friendshipOf(wire)
if wanted_private ~= nil and got == nil then
self:finish(nil, _("无法确认想法是否私密"))
return
end
if wanted_friendship ~= nil and got_friendship == nil then got_friendship = 0 end
local mismatch = (wanted_private ~= nil and got ~= wanted_private)
or (wanted_friendship ~= nil and got_friendship ~= wanted_friendship)
if got ~= nil then item.wr_private = got end
if Notes.friendshipOf(wire) ~= nil then item.wr_friendship = Notes.friendshipOf(wire) end
if mismatch then
item.wr_update_review = nil
self:finish(nil, _("想法的可见范围没有按设置保存"))
return
end
item.wr_update_review = nil
next()
end)
end
--- 设置里的想法默认范围。没设过或值不对就是私有。
---@return string
function Push:noteVisibility()
local choice = require("utils.settings").getSource("weread").note_visibility
if choice == "public" or choice == "follow" then return choice end
return "private"
end
--- 串行推想法:已有 reviewId 走 edit,否则 add。
function Push:reviews()
local function submit()
local deferred = false
local secret = Context.bookSecret(self.book_id)
local choice = self:noteVisibility()
self:each(Notes.notePushCandidates(self.annotations), function(item, next)
if not item.wr_review_id and self.reviews_unknown then
deferred = true
@@ -342,35 +385,34 @@ function Push:reviews()
self:finish(nil, _("远端划线未确认,不能上传想法"))
return
end
local body, body_err
local send
if item.wr_review_id then
local body, body_err = Notes.toReviewEditBody(self.book_id, self.chapter_uid, item)
body, body_err = Notes.toReviewEditBody(self.book_id, self.chapter_uid, item, secret, choice)
send = function(done) return self.client:editReviewAsync(body, done) end
else
body, body_err = Notes.toReviewBody(self.book_id, self.chapter_uid, item, secret, choice)
send = function(done) return self.client:addReviewAsync(body, done) end
end
if not body then
self:finish(nil, body_err)
return
end
self:call(function(done)
return self.client:editReviewAsync(body, done)
end, _("想法上传失败"), function()
item.wr_update_review = nil
next()
end)
return
end
local body, body_err = Notes.toReviewBody(self.book_id, self.chapter_uid, item)
if not body then
self:finish(nil, body_err)
return
end
self:call(function(done)
return self.client:addReviewAsync(body, done)
end, _("想法上传失败"), function(wire)
self:call(send, _("想法上传失败"), function(wire)
if not item.wr_review_id then
local review_id = wire.reviewId or (type(wire.data) == "table" and wire.data.reviewId)
if not review_id then
self:finish(nil, _("想法上传成功但缺少 reviewId"))
return
end
item.wr_review_id = review_id
end
if body.isPrivate == nil and body.friendship == nil then
item.wr_update_review = nil
next()
return
end
self:confirmPrivate(item, body.isPrivate, body.friendship, next)
end)
end, function()
if deferred then
@@ -379,6 +421,8 @@ function Push:reviews()
self:finish(true)
end
end)
end
submit()
end
--- 推送一章注解。
@@ -87,6 +87,30 @@ function Reviews.locate(hotspots, html)
return out
end
local PICTURE_HEADERS = { Referer = "https://weread.qq.com/" }
--- 评论配图。没有图时 nil,空数组不当成有图。
---@param review table|nil
---@return { url: string, width: integer|nil, height: integer|nil, headers: table }[]|nil
local function imagesOf(review)
local pics = type(review) == "table" and review.pictures or nil
if type(pics) ~= "table" then return nil end
local images = {}
for _idx, pic in ipairs(pics) do
local url = type(pic) == "table" and pic.url or nil
if type(url) == "string" and url ~= "" then
images[#images + 1] = {
url = url,
width = tonumber(pic.width),
height = tonumber(pic.height),
headers = PICTURE_HEADERS,
}
end
end
if #images == 0 then return nil end
return images
end
--- 单条 pageReviews → 展示项。
---@param entry table
---@return WechatReview
@@ -96,6 +120,7 @@ function Reviews.item(entry)
id = entry.reviewId,
author = type(review.author) == "table" and review.author.name or "",
content = review.content,
images = imagesOf(review) or imagesOf(entry),
likes = tonumber(entry.likesCount) or 0,
replies = tonumber(entry.commentsCount) or tonumber(review.commentsCount) or 0,
time = tonumber(review.createTime) or 0,
@@ -114,6 +139,7 @@ function Reviews.commentItem(entry)
id = tostring(entry.commentId or comment.commentId or ""),
author = type(author) == "table" and author.name or "",
content = tostring(comment.content or entry.content or ""),
images = imagesOf(comment) or imagesOf(entry),
likes = tonumber(entry.likesCount or comment.likesCount) or 0,
replies = 0,
reply_to = type(reply_user) == "table" and reply_user.name or nil,
@@ -12,6 +12,11 @@ local SOURCE_ID = "weread"
local Setting = {}
function Setting.rowIcon()
return "menu_book"
end
--- 设置行状态文案与高亮开关。
---@return string status, boolean status_on
function Setting.rowStatus()
@@ -154,6 +159,31 @@ function Setting.rows(plugin)
toggle("merge_local_stats", false, "history", _("合并本地阅读时长"),
_("关闭时以云端为准;打开后每天取云端与本地中较大的,补上离线阅读。只影响月读里的统计"))
toggle("show_paragraph_reviews", false, "forum", _("显示段评"), _("阅读时给有他人段评的句子画线,点按查看;需联网"))
local visibility = {
{ value = "private", label = _("私有") },
{ value = "public", label = _("公开") },
{ value = "follow", label = _("仅关注") },
}
rows[#rows + 1] = function(iw)
local cfg = Settings.getSource(SOURCE_ID)
local current = cfg.note_visibility
if current ~= "public" and current ~= "follow" then current = "private" end
local index = 1
for i, item in ipairs(visibility) do
if item.value == current then index = i end
end
return Row.widget({ width = iw, chevron = false, kind = "action", icon = "lock",
title = _("想法默认可见"),
subtitle = _("点按切换。仅关注是互相关注可见,只影响新想法"),
status = visibility[index].label,
status_on = current ~= "public",
callback = function()
local next_item = visibility[index % #visibility + 1]
cfg.note_visibility = next_item.value
Settings.saveSource(SOURCE_ID, cfg)
if plugin and plugin.desktop then plugin.desktop:updateView() end
end })
end
rows[#rows + 1] = require("source.category_setting").row(SOURCE_ID, plugin)
if not Auth.hasSession() then return rows end
rows[#rows + 1] = function(iw)
@@ -55,7 +55,11 @@ function ShelfImport.size()
return size
end
--- 当前待导入快照是否已弹过导入页(进程内);快照没了就清零。
ShelfImport.prompted = false
function ShelfImport.discard()
ShelfImport.prompted = false
os.remove(ShelfImport.path())
end
@@ -512,7 +512,7 @@ function Source:syncBooksAsync(opts, cb)
local client = self._client
local remote = {
shelfSyncAsync = function(_, done)
return client:shelfSyncAsync(done, true, opts.force == true)
return client:shelfSyncAsync(done, true, opts.force == true or opts.manual == true)
end,
addToShelfAsync = function(_, id, done) return client:addToShelfAsync(id, done) end,
removeFromShelfAsync = function(_, id, done) return client:removeFromShelfAsync(id, done) end,
@@ -536,6 +536,11 @@ function Source:syncBooksAsync(opts, cb)
if opts.force then return fullPull() end
local pending_import = require("moonsource_weread.shelf_import")
if pending_import.size() then
-- 后台先存盘的快照用户没见过导入页:普通手动刷新补弹一次,之后不再打扰。
if opts.manual and not pending_import.prompted then
pending_import.prompted = true
require("utils.extension").call("web.open_page", pending_import.PAGE, _("微信书架导入"), pending_import.TOO_LARGE)
end
return SourceBase.defer(cb, {
pulled = 0, pushed = 0, hidden = 0, conflicts = 0,
skipped = true, reason = "pending_import",
@@ -1520,18 +1525,19 @@ function Source:paragraphReviewsEnabled()
return require("source.review_setting").enabled(self.id)
end
--- 按书名搜索微信读书书目(关联本地书看段评用)。
--- 按书名搜索微信读书书目(关联本地书看段评用)。author 写入 /store/search 的作者参数。
---@param keyword string
---@param cb fun(books: WechatSearchBook[]|nil, err: string|nil)
---@param author string|nil
---@return { cancel: fun() }|nil
function Source:searchBooksAsync(keyword, cb)
function Source:searchBooksAsync(keyword, cb, author)
return self._client:searchAsync(keyword, function(wire, err)
if not wire then
cb(nil, err)
return
end
cb(Mapper.searchBooks(wire))
end)
end, author)
end
--- 书城搜索:回包形状同 listStoreAsync。
@@ -1,435 +0,0 @@
--[[--
书源插件在线更新(Forgejo Release)。
本文件是 moonsource-template 仓库 common/update.lua 的副本,由 tools/sync.sh 同步到每个插件仓库的
<包名>/update.lua,请改模板仓库,不要手改副本。
每个插件在自己的仓库(moon-source/moonsource-<名字>)独立发版,只检查并更新它自己:
仓库名和目录名都由包名(require 时的模块名)推出,包体校验值取自同一 Release 的 SHA256SUMS。
@module moonsource.update
--]]
local PKG = (...):match("^(.-)%.update$")
local NAME = PKG:gsub("_", "-")
local DIR = NAME .. ".koplugin"
local REPO = "moon-source/" .. NAME
local SITE = "https://git.garfieldho.me"
local API = SITE .. "/api/v1/repos/" .. REPO .. "/releases/latest"
local CHECK_INTERVAL = 24 * 60 * 60
local MAX_ARCHIVE_BYTES = 50 * 1024 * 1024
local GetText = require("gettext")
local T = require("ffi/util").template
-- 源文是简体中文;这点文案不值得单开 l10n 目录,翻译内联在这里。
local CATALOG = {
en = {
["下载并安装"] = "Download and install",
["「%1」已是最新(%2)。重新下载并替换已安装的版本?"] = "%1 is up to date (%2). Download again and replace the installed version?",
["书源插件更新"] = "Source plugin update",
["书源插件更新失败:%1"] = "Source plugin update failed: %1",
["关"] = "Off",
["发现「%1」新版本 %2(当前 %3),更新后重启 KOReader。"] = "%1 %2 is available (current %3). KOReader restarts after the update.",
["已是最新版本(%1)"] = "Already up to date (%1)",
["开"] = "On",
["只更新本书源,其它书源各自独立更新"] = "Updates this source only; other sources update on their own",
["新版本缺少插件包,请稍后再试"] = "The new release is missing plugin packages. Try again later.",
["更新书源插件"] = "Updating source plugins",
["更新信息无效,请稍后再试"] = "Invalid update information. Try again later.",
["更新包校验失败,请稍后再试"] = "Update package checksum failed. Try again later.",
["更新包过大,已中止下载"] = "The update package is too large. Download aborted.",
["更新完成,正在重启 KOReader…"] = "Update complete. Restarting KOReader…",
["检查书源插件更新"] = "Check source plugin updates",
["检查更新"] = "Check for updates",
["检查更新失败:%1"] = "Update check failed: %1",
["正在下载…"] = "Downloading…",
["正在检查书源插件更新…"] = "Checking for source plugin updates…",
["正在检查或安装更新,请稍候"] = "An update check or install is in progress. Please wait.",
["稍后"] = "Later",
["自动检查书源插件更新"] = "Check source plugin updates automatically",
["%1 更新"] = "%1 updates",
["书源插件检查更新与自动更新"] = "Source plugin update checks and auto-update",
["书源插件"] = "Source plugins",
},
zh_TW = {
["下载并安装"] = "下載並安裝",
["「%1」已是最新(%2)。重新下载并替换已安装的版本?"] = "「%1」已是最新(%2)。重新下載並替換已安裝的版本?",
["书源插件更新"] = "書源外掛更新",
["书源插件更新失败:%1"] = "書源外掛更新失敗:%1",
["关"] = "關",
["发现「%1」新版本 %2(当前 %3),更新后重启 KOReader。"] = "發現「%1」新版本 %2(目前 %3),更新後重新啟動 KOReader。",
["已是最新版本(%1)"] = "已是最新版本(%1)",
["开"] = "開",
["只更新本书源,其它书源各自独立更新"] = "只更新本書源,其它書源各自獨立更新",
["新版本缺少插件包,请稍后再试"] = "新版本缺少外掛包,請稍後再試",
["更新书源插件"] = "更新書源外掛",
["更新信息无效,请稍后再试"] = "更新資訊無效,請稍後再試",
["更新包校验失败,请稍后再试"] = "更新包校驗失敗,請稍後再試",
["更新包过大,已中止下载"] = "更新包過大,已中止下載",
["更新完成,正在重启 KOReader…"] = "更新完成,正在重新啟動 KOReader…",
["检查书源插件更新"] = "檢查書源外掛更新",
["检查更新"] = "檢查更新",
["检查更新失败:%1"] = "檢查更新失敗:%1",
["正在下载…"] = "正在下載…",
["正在检查书源插件更新…"] = "正在檢查書源外掛更新…",
["正在检查或安装更新,请稍候"] = "正在檢查或安裝更新,請稍候",
["稍后"] = "稍後",
["自动检查书源插件更新"] = "自動檢查書源外掛更新",
["%1 更新"] = "%1 更新",
["书源插件检查更新与自动更新"] = "書源外掛檢查更新與自動更新",
["书源插件"] = "書源外掛",
},
}
local function _(msgid)
local lang = tostring(GetText.current_lang or ""):gsub("%.[%w%-]+$", "")
local catalog
if lang:match("^zh_TW") or lang:match("^zh_HK") then
catalog = CATALOG.zh_TW
elseif not lang:match("^zh") then
catalog = CATALOG.en
end
return catalog and catalog[msgid] or GetText(msgid)
end
local Update = {}
-- 按包名分状态:各书源互不影响,各自只自动检查一次、同一版本只弹一次
local function shared()
local all = rawget(_G, "__moonsource_update")
if not all then
all = {}
rawset(_G, "__moonsource_update", all)
end
all[PKG] = all[PKG] or {}
return all[PKG]
end
local function pluginsDir()
local root = debug.getinfo(1, "S").source:match("^@(.*)/[^/]+/[^/]+$")
return root and root:match("^(.*)/[^/]+$")
end
---@return string
function Update.version()
return require(PKG .. ".version")
end
local function sourceId()
return require(PKG .. "._meta").id
end
--- 数字段依次比较;同数字时预发布比正式版旧;已装版本解析不出(开发版)一律视为更旧。
---@param candidate string
---@param installed string
---@return boolean
function Update.newer(candidate, installed)
local function parts(version)
local out = {}
for n in version:gmatch("%d+") do out[#out + 1] = tonumber(n) end
return out
end
local left, right = parts(candidate), parts(installed)
if #right == 0 or installed:find("dev", 1, true) then return true end
for i = 1, 3 do
local l, r = left[i] or 0, right[i] or 0
if l ~= r then return l > r end
end
return installed:find("%-") ~= nil and candidate:find("%-") == nil
end
local function parseSums(body)
local sums = {}
for hash, name in tostring(body):gmatch("(%x+)%s+%*?(%S+)") do
if #hash == 64 then sums[name] = hash:lower() end
end
return sums
end
---@return table|nil release, string|nil err
local function parse(body)
local ok, data = pcall(require("json").decode, body)
if not ok or type(data) ~= "table" or data.draft or data.prerelease then
return nil, "invalid release response"
end
local tag = data.tag_name
local version = type(tag) == "string" and tag:match("^v?(%d+%.%d+%.%d+[%w%.%+%-]*)$")
if not version then return nil, "invalid release version" end
local base = SITE .. "/" .. REPO .. "/releases/download/" .. tag .. "/"
local assets, sums_url = {}, nil
for _idx, asset in ipairs(type(data.assets) == "table" and data.assets or {}) do
if type(asset) == "table" and type(asset.name) == "string" and asset.browser_download_url == base .. asset.name then
if asset.name == "SHA256SUMS" then
sums_url = asset.browser_download_url
else
assets[asset.name] = { url = asset.browser_download_url, size = tonumber(asset.size) }
end
end
end
if not sums_url then return nil, "release has no plugin checksum" end
local notes = type(data.body) == "string" and require("utils.text").trim(data.body) or ""
return { version = version, assets = assets, sums_url = sums_url, notes = notes ~= "" and notes or nil }
end
local job
--- 发起一个异步请求并登记为在途;回调若同步触发,不会把已结束的请求挂回去占着「忙」。
---@param start fun(wrap: fun(cb: function): function): any
local function launch(start)
local settled = false
local function wrap(cb)
return function(...)
settled = true
job = nil
return cb(...)
end
end
local handle = start(wrap)
if not settled then job = handle end
end
--- 查询最新稳定版,并配好本插件的安装包 release.target = { dir, file, url, size, sha256 }。
---@param cb fun(release: table|nil, err: any)
function Update.check(cb)
if job then return cb(nil, "busy") end
local Request = require("http.request")
local timeout = require("http.timeout").net(1)
local function finish(release, sums_body)
local sums = parseSums(sums_body)
local file = DIR .. "-" .. release.version .. ".zip"
local asset = release.assets[file]
if not (asset and sums[file]) then return cb(nil, "release has no plugin archive") end
release.target = { dir = DIR, file = file, url = asset.url, size = asset.size, sha256 = sums[file] }
release.installed = Update.version()
release.available = Update.newer(release.version, release.installed)
local settings = require("utils.settings")
local cfg = settings.getSource(sourceId())
cfg.update_last_checked_at = os.time()
settings.saveSource(sourceId(), cfg)
cb(release)
end
launch(function(wrap)
return Request.get(API, { timeout = timeout, headers = { Accept = "application/json" } }, wrap(function(body, err)
if err then return cb(nil, err) end
local release, perr = parse(body)
if not release then return cb(nil, perr) end
launch(function(wrap_sums)
return Request.get(release.sums_url, { timeout = timeout }, wrap_sums(function(sums_body, sums_err)
if sums_err then return cb(nil, sums_err) end
finish(release, sums_body)
end))
end)
end))
end)
end
--- 下载、校验并换掉已装的本插件目录。
---@param release table Update.check 的结果
---@param cb fun(ok: boolean, err: any)
---@param on_progress fun(bytes: integer|nil, target: table)|nil
function Update.install(release, cb, on_progress)
if job then return cb(false, "busy") end
local Request, Job = require("http.request"), require("workers.job")
local Paths, Install = require("utils.paths"), require("utils.plugin_install")
local target = release.target
Paths.ensureDir(Paths.root())
local archive = Paths.root() .. "/" .. target.dir .. ".update.zip"
os.remove(archive)
launch(function(wrap)
return Request.download({
url = target.url,
timeout = require("http.timeout").net(10),
allow_redirects = true,
max_bytes = MAX_ARCHIVE_BYTES,
on_progress = function(bytes)
if on_progress then on_progress(bytes, target) end
end,
}, archive, wrap(function(ok, err)
if not ok then
os.remove(archive)
return cb(false, err)
end
launch(function(wrap_job)
local function settle(failure)
return wrap_job(function()
os.remove(archive)
if failure then return cb(false, failure) end
cb(true)
end)
end
return Job.run(function()
local installed, detail = Install.run(archive, pluginsDir(), target.sha256, { name = target.dir })
if not installed then error(detail, 0) end
end, {
name = "moonsource.update",
kind = "heavy",
timeout = 120,
on_done = settle(),
on_failed = function(install_err) settle(install_err)() end,
})
end)
end))
end)
end
local function errorText(err)
local text = tostring(err)
local known = {
{ "^busy$", _("正在检查或安装更新,请稍候") },
{ "^invalid release", _("更新信息无效,请稍后再试") },
{ "^release has no", _("新版本缺少插件包,请稍后再试") },
{ "update checksum mismatch", _("更新包校验失败,请稍后再试") },
{ "download too large", _("更新包过大,已中止下载") },
}
for _idx, entry in ipairs(known) do
if text:find(entry[1]) then return entry[2] end
end
return text:match("[^\n]*")
end
local function startInstall(release)
local ProgressDialog = require("ui.themes.widgets.progress_dialog")
local dialog = ProgressDialog:new{ title = _("更新书源插件"), text = _("正在下载…"), dismissable = false }
dialog:show()
Update.install(release, function(ok, err)
if ok then
dialog:set(_("更新完成,正在重启 KOReader…"), 100)
local UIManager = require("ui/uimanager")
UIManager:nextTick(function()
UIManager:broadcastEvent(require("ui/event"):new("Restart"))
end)
return
end
dialog:close()
require("ui.themes.widgets.toast"):new{ text = T(_("书源插件更新失败:%1"), errorText(err)), timeout = 5 }:show()
end, function(bytes, target)
local fraction = target.size and target.size > 0 and bytes and math.min(1, bytes / target.size) or 0
dialog:set(_("正在下载…"), math.floor(fraction * 100))
end)
end
--- 弹更新说明与安装确认。同版本只提示一次,force 跳过这层记忆。
---@param release table
---@param force boolean|nil
function Update.prompt(release, force)
local state = shared()
if not force and state.offered == release.version then return end
state.offered = release.version
local name = require(PKG .. "._meta").name
local header = T(_("发现「%1」新版本 %2(当前 %3),更新后重启 KOReader。"), name, release.version, release.installed)
if force and not release.available then
header = T(_("「%1」已是最新(%2)。重新下载并替换已安装的版本?"), name, release.version)
end
local dialog
dialog = require("ui.themes.widgets.text_viewer"):new{
title = _("书源插件更新"),
text = release.notes and (header .. "\n\n" .. release.notes) or header,
buttons = {
{ text = _("稍后"), callback = function() dialog:close() end },
{
text = _("下载并安装"),
variant = "primary",
callback = function()
dialog:close()
startInstall(release)
end,
},
},
}
dialog:show()
end
--- 用户主动检查,始终给结果。
---@param force boolean|nil 为真时已是最新也提示重装
function Update.manualCheck(force)
local Toast = require("ui.themes.widgets.toast")
local loading = require("ui.themes.widgets.progress_dialog"):new{
title = _("检查更新"), text = _("正在检查书源插件更新…"), dismissable = false,
}
loading:show()
Update.check(function(release, err)
loading:close()
if err then
Toast:new{ text = T(_("检查更新失败:%1"), errorText(err)), timeout = 4 }:show()
elseif force or release.available then
shared().offered = nil
Update.prompt(release, force)
else
Toast:new{ text = T(_("已是最新版本(%1)"), release.installed), timeout = 3 }:show()
end
end)
end
local function autoEnabled()
return require("utils.settings").getSource(sourceId()).update_auto_check ~= false
end
--- 按 24 小时间隔静默检查;只提示,不自动安装。
function Update.autoCheck()
local state = shared()
if state.checked or not autoEnabled() then return end
local last = tonumber(require("utils.settings").getSource(sourceId()).update_last_checked_at) or 0
if os.time() - last < CHECK_INTERVAL then return end
if not require("ui/network/manager"):isConnected() then return end
state.checked = true
Update.check(function(release)
if release and release.available and autoEnabled() then Update.prompt(release) end
end)
end
--- 桌面回到前台时自动检查。
function Update.register()
require("utils.extension").add("desktop.activated", function() Update.autoCheck() end)
end
--- 设置页「书库 → 更新」:每个书源各登记一项,只管自己。
---@param desktop table
---@return table[]
function Update.entries(desktop)
local name = require(PKG .. "._meta").name
local Row = require("ui.themes.widgets.row")
return {
{
group = "library", order = 40, id = "moonsource_update_" .. sourceId(), icon = "system_update",
title = T(_("%1 更新"), name),
subtitle = _("书源插件检查更新与自动更新"),
status = Update.version(),
page = {
title = T(_("%1 更新"), name),
sections = function()
return {{
title = _("书源插件"),
rows = {
function(iw)
return Row.widget({
width = iw, chevron = true, kind = "nav", icon = "system_update",
title = _("检查书源插件更新"),
subtitle = _("只更新本书源,其它书源各自独立更新"),
status = Update.version(),
callback = function() Update.manualCheck() end,
})
end,
function(iw)
local on = autoEnabled()
return Row.widget({
width = iw, chevron = false, kind = "toggle", icon = "autorenew",
title = _("自动检查书源插件更新"),
status = on and _("开") or _("关"), status_on = on,
callback = function()
local settings = require("utils.settings")
local cfg = settings.getSource(sourceId())
cfg.update_auto_check = not on
settings.saveSource(sourceId(), cfg)
desktop:updateView()
end,
})
end,
},
}}
end,
},
},
}
end
return Update
-84
View File
@@ -1,84 +0,0 @@
--[[-- 书源插件在线更新:版本比较、只配本插件的包、校验下载地址、设置页追加更新行。本文件由模板仓库同步,勿手改。 @module tests.update.update_spec --]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
package.preload["json"] = function() return require("support.json_stub") end
local Assert = require("support.assert")
local Json = require("support.json_stub")
local PKG = "moonsource_weread"
local DIR = "moonsource-weread.koplugin"
local REPO = "moon-source/" .. DIR:gsub("%.koplugin$", "")
local cfg = {}
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, saveSource = function() end }
end
package.preload["utils.text"] = function()
return { trim = function(s) return (s:gsub("^%s+", ""):gsub("%s+$", "")) end }
end
package.preload["http.timeout"] = function() return { net = function() return 5 end } end
local BASE = "https://git.garfieldho.me/" .. REPO .. "/releases/download/v1.2.3/"
local zip = DIR .. "-1.2.3.zip"
local other = "moonsource-other.koplugin-1.2.3.zip"
local release = {
tag_name = "v1.2.3", draft = false, prerelease = false, body = " 更新说明 ",
assets = {
{ name = "SHA256SUMS", size = 10, browser_download_url = BASE .. "SHA256SUMS" },
{ name = zip, size = 100, browser_download_url = BASE .. zip },
{ name = other, size = 200, browser_download_url = "https://evil.example/x.zip" },
},
}
local sums = ("a"):rep(64) .. " " .. zip .. "\n" .. ("b"):rep(64) .. " " .. other .. "\n"
local requested = {}
package.preload["http.request"] = function()
return {
get = function(url, _opts, cb)
requested[#requested + 1] = url
if url:find("/releases/latest", 1, true) then cb(Json.encode(release)) else cb(sums) end
return { cancel = function() end }
end,
}
end
local Update = require(PKG .. ".update")
-- 版本比较
Assert.is_true(Update.newer("0.6.1", "0.6.0"))
Assert.is_false(Update.newer("0.6.0", "0.6.0"))
Assert.is_false(Update.newer("0.5.9", "0.6.0"))
Assert.is_true(Update.newer("1.0.0", "1.0.0-rc.1"))
Assert.is_true(Update.newer("0.0.1", "0.0.0-dev"))
-- 只查自己仓库的 Release,只配自己的包
local got, err
Update.check(function(r, e) got, err = r, e end)
Assert.is_nil(err)
Assert.eq(requested[1], "https://git.garfieldho.me/api/v1/repos/" .. REPO .. "/releases/latest")
Assert.eq(got.version, "1.2.3")
Assert.eq(got.notes, "更新说明")
Assert.is_true(got.available)
Assert.eq(got.target.dir, DIR)
Assert.eq(got.target.sha256, ("a"):rep(64))
Assert.is_true(cfg.update_last_checked_at ~= nil)
-- 下载地址不在本仓库 Release 下的资产被拒
release.assets[2].browser_download_url = "https://evil.example/x.zip"
local rejected
Update.check(function(_r, e) rejected = e end)
Assert.matches(rejected, "no plugin archive")
release.assets[2].browser_download_url = BASE .. zip
-- 没有 SHA256SUMS 的 Release 无效
release.assets[1] = nil
local bad_err
Update.check(function(_r, e) bad_err = e end)
Assert.matches(bad_err, "no plugin checksum")
-- 设置页「书库 → 更新」每个书源登记自己的一项
package.preload["ui.themes.widgets.row"] = function() return { widget = function(spec) return spec end } end
local entries = Update.entries({ updateView = function() end })
Assert.len(entries, 1)
Assert.eq(entries[1].group, "library")
Assert.matches(entries[1].id, "^moonsource_update_")
Assert.len(entries[1].page.sections()[1].rows, 2)
+4
View File
@@ -214,7 +214,11 @@ do
req = call(client.searchAsync, client, "三体", function(d) wire = d end)
Assert.eq(req.path, "/store/search")
Assert.eq(req.query.keyword, "三体")
Assert.eq(req.query.author, "")
Assert.eq(req.query.v, 2)
req = call(client.searchAsync, client, "三体", function() end, "刘慈欣")
Assert.eq(req.query.keyword, "三体")
Assert.eq(req.query.author, "刘慈欣")
Assert.eq(req.query.type, 0)
Assert.eq(wire.books[1].bookInfo.bookId, "9")
end
+3 -1
View File
@@ -47,7 +47,9 @@ live.doc_settings = {
}
package.loaded["apps/reader/readerui"] = { instance = live }
package.loaded["reader.session"] = {
_snapshot = { identity = { source_id = "local", stable_id = "open-book", chapter_idx = 2 } },
current = function()
return { identity = { source_id = "local", stable_id = "open-book", chapter_idx = 2 } }
end,
}
local wechat_notes = require("moonsource_weread.notes")
-4
View File
@@ -438,10 +438,6 @@ do
source_id = "authoritative", stable_id = "book.epub", chapter_idx = 3,
source = authoritative,
}), 0)
Assert.eq(SessionNote.applyLocal({ doc_settings = ui3.doc_settings }, {
source_id = "authoritative", stable_id = "book.epub", chapter_idx = 2,
source = authoritative,
}), 0, "没有打开文档时不应用")
end
-- 上传窗口内用户又划了线:不能用上传时那份快照 + 旧修订号覆盖回去。
+13
View File
@@ -14,6 +14,19 @@ package.preload["source.contract"] = nil
local Mapper = require("moonsource_weread.mapper")
-- 搜索书目带译者。没有 translator 的书给空串,公众号条目丢掉。
do
local books = Mapper.searchBooks({ books = {
{ type = 0, bookInfo = { bookId = 31503072, title = "地下室手记(果麦经典)", author = "[俄]陀思妥耶夫斯基", translator = "曾思艺" } },
{ type = 0, bookInfo = { bookId = 3300154232, title = "地下室手记(经典译本无删减)", author = "[俄]陀思妥耶夫斯基著" } },
{ type = 3, mpInfo = { title = "公众号" } },
} })
Assert.len(books, 2)
Assert.eq(books[1].translator, "曾思艺")
Assert.eq(books[1].author, "[俄]陀思妥耶夫斯基")
Assert.eq(books[2].translator, "", "接口没给译者")
end
do
local _b, cover = Mapper.book({ bookId = "wx-2", cover = "https://cdn.weread.qq.com/weread/cover/80/y_1/s_y_1.jpg" })
Assert.eq(cover, "https://cdn.weread.qq.com/weread/cover/80/y_1/t7_y_1.jpg")
+166 -2
View File
@@ -13,12 +13,13 @@ local NotesPush = require("moonsource_weread.notes_push")
local function fakeClient(replies)
local calls = {}
---@type { calls: string[], [string]: any }
local client = { calls = calls }
local client = { calls = calls, sent = {} }
local function method(name)
return function(_self, ...)
local args = { ... }
local cb = args[#args]
calls[#calls + 1] = name
client.sent[name] = args
local reply = replies[name]
require("ui/uimanager"):nextTick(function()
if type(reply) == "function" then reply = reply() end
@@ -29,7 +30,7 @@ local function fakeClient(replies)
end
for _idx, name in ipairs({ "removeBookmarkAsync", "deleteReviewAsync", "bookmarkListAsync",
"myReviewsAsync", "addBookmarkAsync", "updateBookmarkAsync", "editReviewAsync",
"addReviewAsync", "bookInfoAsync" }) do
"addReviewAsync", "bookInfoAsync", "reviewSingleAsync" }) do
client[name] = method(name)
end
return client
@@ -166,3 +167,166 @@ do -- 想法清单拿不到:新想法不推(认不回上轮已成功的会
Assert.is_nil(item.wr_review_id)
for _, name in ipairs(client.calls) do Assert.is_true(name ~= "addReviewAsync", "不得重复新增想法") end
end
do -- 私密阅读的新想法带 isPrivate=1,回读确认后才算成功
require("moonsource_weread.context").clear()
local Toc = require("moonsource_weread.toc")
local Position = require("moonsource_weread.progress")
local old_read, old_load = Toc.read, Position.loadAsync
Toc.read = function() return { { uid = "c1" } } end
Position.loadAsync = function(_identity, _chapter, cb)
cb("<html><body><p>原文</p></body></html>", "html")
return nil
end
local item = {
drawer = "lighten", text = "原文", note = "只给自己看",
wr_range = "1-2", wr_review_only = true,
pos0 = "/html/body/p/text().0", pos1 = "/html/body/p/text().2",
}
local client = fakeClient({
bookmarkListAsync = { updated = {} },
myReviewsAsync = { reviews = {}, hasMore = 0, totalCount = 0 },
bookInfoAsync = { book = { bookId = "b1", version = 1, secret = 1 } },
addReviewAsync = { reviewId = "rv-priv" },
reviewSingleAsync = { review = { reviewId = "rv-priv", isPrivate = 1 } },
})
local ok, err
NotesPush.run(client, identity, "c1",
"<html><body><p>原文</p></body></html>", { item }, function(o, e) ok, err = o, e end)
Stubs.flush()
Toc.read, Position.loadAsync = old_read, old_load
Assert.is_true(ok, tostring(err))
Assert.eq(client.sent.addReviewAsync[1].isPrivate, 1)
Assert.eq(item.wr_review_id, "rv-priv")
Assert.eq(item.wr_private, 1)
Assert.is_nil(item.wr_update_review)
end
do -- 回读不是私密:留下 reviewId,整轮失败,不再当成成功
require("moonsource_weread.context").clear()
local Toc = require("moonsource_weread.toc")
local Position = require("moonsource_weread.progress")
local old_read, old_load = Toc.read, Position.loadAsync
Toc.read = function() return { { uid = "c1" } } end
Position.loadAsync = function(_identity, _chapter, cb)
cb("<html><body><p>原文</p></body></html>", "html")
return nil
end
local item = {
drawer = "lighten", text = "原文", note = "只给自己看",
wr_range = "1-2", wr_review_only = true,
pos0 = "/html/body/p/text().0", pos1 = "/html/body/p/text().2",
}
local client = fakeClient({
bookmarkListAsync = { updated = {} },
myReviewsAsync = { reviews = {}, hasMore = 0, totalCount = 0 },
bookInfoAsync = { book = { bookId = "b1", version = 1, secret = 1 } },
addReviewAsync = { reviewId = "rv-pub" },
reviewSingleAsync = { review = { isPrivate = 0 } },
})
local ok, err
NotesPush.run(client, identity, "c1",
"<html><body><p>原文</p></body></html>", { item }, function(o, e) ok, err = o, e end)
Stubs.flush()
Toc.read, Position.loadAsync = old_read, old_load
Assert.is_nil(ok)
Assert.eq(err, "想法的可见范围没有按设置保存")
Assert.eq(item.wr_review_id, "rv-pub")
Assert.eq(item.wr_private, 0)
Assert.is_nil(item.wr_update_review)
end
do -- 改已有想法:沿用拉下来的 isPrivate,不按书籍公开设置改掉
require("moonsource_weread.context").clear()
local item = {
drawer = "lighten", text = "原文", note = "改过",
wr_range = "1-2", wr_bookmark_id = "bm1", wr_review_id = "rv1",
wr_private = 1, wr_update_review = true,
}
local client = fakeClient({
bookmarkListAsync = { updated = { {
chapterUid = "c1", range = "1-2", bookmarkId = "bm1", markText = "原文", type = 1,
} } },
myReviewsAsync = { reviews = { { review = {
reviewId = "rv1", isPrivate = 0, range = "1-2", abstract = "原文", content = "改过",
} } }, hasMore = 0, totalCount = 1 },
editReviewAsync = { succ = 1 },
reviewSingleAsync = { review = { isPrivate = 1 } },
})
local ok, err
NotesPush.run(client, identity, "c1", nil, { item }, function(o, e) ok, err = o, e end)
Stubs.flush()
Assert.is_true(ok, tostring(err))
Assert.eq(client.sent.editReviewAsync[1].isPrivate, 1)
for _, name in ipairs(client.calls) do
Assert.is_true(name ~= "bookInfoAsync", "已有可见范围不必再读私密阅读设置")
end
Assert.is_nil(item.wr_update_review)
end
do -- 没记过可见范围的旧想法:修改不带 isPrivate,也不回读
require("moonsource_weread.context").clear()
local item = {
drawer = "lighten", text = "原文", note = "改过",
wr_range = "1-2", wr_bookmark_id = "bm1", wr_review_id = "rv1",
wr_update_review = true,
}
local client = fakeClient({
bookmarkListAsync = { updated = { {
chapterUid = "c1", range = "1-2", bookmarkId = "bm1", markText = "原文", type = 1,
} } },
myReviewsAsync = { reviews = { { review = { reviewId = "rv1" } } }, hasMore = 0, totalCount = 1 },
editReviewAsync = { succ = 1 },
})
local ok, err
NotesPush.run(client, identity, "c1", nil, { item }, function(o, e) ok, err = o, e end)
Stubs.flush()
Assert.is_true(ok, tostring(err))
Assert.is_nil(client.sent.editReviewAsync[1].isPrivate)
for _, name in ipairs(client.calls) do
Assert.is_true(name ~= "reviewSingleAsync")
end
end
do -- 设置成仅关注:新想法带 friendship,不再读私密阅读
require("moonsource_weread.context").clear()
local Settings = require("utils.settings")
local cfg = Settings.getSource("weread")
local old = cfg.note_visibility
cfg.note_visibility = "follow"
Settings.saveSource("weread", cfg)
local Toc = require("moonsource_weread.toc")
local Position = require("moonsource_weread.progress")
local old_read, old_load = Toc.read, Position.loadAsync
Toc.read = function() return { { uid = "c1" } } end
Position.loadAsync = function(_identity, _chapter, cb)
cb("<html><body><p>原文</p></body></html>", "html")
return nil
end
local item = {
drawer = "lighten", text = "原文", note = "给关注的人",
wr_range = "1-2", wr_review_only = true,
pos0 = "/html/body/p/text().0", pos1 = "/html/body/p/text().2",
}
local client = fakeClient({
bookmarkListAsync = { updated = {} },
myReviewsAsync = { reviews = {}, hasMore = 0, totalCount = 0 },
addReviewAsync = { reviewId = "rv-follow" },
reviewSingleAsync = { review = { isPrivate = 0, friendship = 1 } },
})
local ok, err
NotesPush.run(client, identity, "c1",
"<html><body><p>原文</p></body></html>", { item }, function(o, e) ok, err = o, e end)
Stubs.flush()
Toc.read, Position.loadAsync = old_read, old_load
cfg.note_visibility = old
Settings.saveSource("weread", cfg)
Assert.is_true(ok, tostring(err))
Assert.eq(client.sent.addReviewAsync[1].isPrivate, 0)
Assert.eq(client.sent.addReviewAsync[1].friendship, 1)
Assert.eq(item.wr_friendship, 1)
Assert.eq(item.wr_private, 0)
for _, name in ipairs(client.calls) do
Assert.is_true(name ~= "bookInfoAsync", "设置了范围就不必再读私密阅读")
end
end
+21
View File
@@ -79,6 +79,27 @@ do
review = { content = "点评", createTime = 1, author = { name = "甲" } },
})
Assert.eq(with_replies.replies, 4)
Assert.is_nil(with_replies.images)
local pictured = Reviews.item({
reviewId = "pic", likesCount = 2,
review = {
content = "带图", createTime = 3, author = { name = "甲" },
pictures = {
{ url = "https://weread-picture.example/a.png", width = 800, height = 1067 },
{ url = "", width = 1, height = 1 },
},
},
})
Assert.len(pictured.images, 1)
Assert.eq(pictured.images[1].url, "https://weread-picture.example/a.png")
Assert.eq(pictured.images[1].width, 800)
Assert.eq(pictured.images[1].height, 1067)
Assert.eq(pictured.images[1].headers.Referer, "https://weread.qq.com/")
local reply = Reviews.commentItem({
commentId = "c", content = "回复", createTime = 4, author = { name = "乙" },
pictures = { { url = "https://weread-picture.example/b.png", width = 40, height = 40 } },
})
Assert.eq(reply.images[1].url, "https://weread-picture.example/b.png")
end
do -- 想法下的评论页:楼中楼只记被回复者;空列表但声称有条数是失败;游标不前进就停
+22 -7
View File
@@ -58,9 +58,9 @@ local Setting = require("moonsource_weread.setting")
local updates = 0
local plugin = { desktop = { updateView = function() updates = updates + 1 end } }
-- 未登录:账号、合并本地阅读时长、显示段评、自定义分组代替分类四行。
-- 未登录:账号、合并时长、段评、想法可见范围、自定义分组五行。
local rows = Setting.rows(plugin)
Assert.len(rows, 4)
Assert.len(rows, 5)
Assert.eq(rows[1]().status, "未登录 · 点此扫码")
-- 合并本地阅读时长默认关(云端优先);点按落盘开启并刷新设置页。
@@ -82,23 +82,38 @@ reviews.callback()
Assert.is_true(cfg.show_paragraph_reviews)
Assert.is_true(rows[3]().status_on)
-- 想法默认可见:没设过是私有,点按在公开、仅关注、私有之间循环。
local visibility = rows[4]()
Assert.eq(visibility.title, "想法默认可见")
Assert.eq(visibility.status, "私有")
Assert.is_nil(cfg.note_visibility)
visibility.callback()
Assert.eq(cfg.note_visibility, "public")
Assert.eq(rows[4]().status, "公开")
rows[4]().callback()
Assert.eq(cfg.note_visibility, "follow")
Assert.eq(rows[4]().status, "仅关注")
rows[4]().callback()
Assert.eq(cfg.note_visibility, "private")
Assert.eq(rows[4]().status, "私有")
-- 自定义分组代替分类默认开;点按关闭并清增量游标。
local groups = rows[4]()
local groups = rows[5]()
Assert.eq(groups.title, "使用自定义分组代替分类")
Assert.is_true(groups.status_on)
cfg.shelf_cursor = { vid = "1", synckey = 9 }
groups.callback()
Assert.is_false(cfg.category_as_group)
Assert.is_nil(cfg.shelf_cursor)
Assert.is_false(rows[4]().status_on)
Assert.is_false(rows[5]().status_on)
-- 已登录:追加续期与退出;退出先确认,确认后才清会话。
logged_in = true
rows = Setting.rows(plugin)
Assert.len(rows, 6)
Assert.len(rows, 7)
Assert.eq(rows[1]().status, "tester")
Assert.eq(rows[5]().title, "续期会话")
local logout = rows[6]()
Assert.eq(rows[6]().title, "续期会话")
local logout = rows[7]()
Assert.eq(logout.title, "退出登录")
logout.callback()
Assert.is_false(cleared, "未确认不退出")
+69
View File
@@ -357,6 +357,75 @@ do
Assert.eq(review_body.abstract, "原文")
Assert.eq(review_body.range, "0-5")
Assert.eq(review_body.chapterUid, 9)
Assert.eq(review_body.isPrivate, 1, "没选过时新想法默认私有")
Assert.eq(review_body.friendship, 0)
local secret_body = Notes.toReviewBody("1", 9, {
note = "想法", text = "原文", wr_range = "0-5",
}, 1)
Assert.eq(secret_body.isPrivate, 1)
local kept = Notes.toReviewBody("1", 9, {
note = "想法", text = "原文", wr_range = "0-5", wr_private = 1,
}, 0)
Assert.eq(kept.isPrivate, 1, "条目自己的可见范围优先于书籍设置")
local edit_unknown = Notes.toReviewEditBody("1", 9, {
note = "想法", text = "原文", wr_range = "0-5", wr_review_id = "rv1",
}, 1)
Assert.is_nil(edit_unknown.isPrivate, "没记过可见范围的旧想法不能在修改时改成公开或私密")
local edit_private = Notes.toReviewEditBody("1", 9, {
note = "想法", text = "原文", wr_range = "0-5", wr_review_id = "rv1", wr_private = 1,
}, 0)
Assert.eq(edit_private.isPrivate, 1)
Assert.is_nil(edit_private.friendship, "只记过私有时不改关注范围")
Assert.eq(edit_private.reviewId, "rv1")
local chosen_public = Notes.toReviewBody("1", 9, {
note = "想法", text = "原文", wr_range = "0-5",
}, 1, "public")
Assert.eq(chosen_public.isPrivate, 0)
Assert.eq(chosen_public.friendship, 0)
local chosen_follow = Notes.toReviewBody("1", 9, {
note = "想法", text = "原文", wr_range = "0-5",
}, 0, "follow")
Assert.eq(chosen_follow.isPrivate, 0)
Assert.eq(chosen_follow.friendship, 1)
local kept_follow = Notes.toReviewEditBody("1", 9, {
note = "想法", text = "原文", wr_range = "0-5", wr_review_id = "rv1",
wr_private = 0, wr_friendship = 1,
}, 0, "public")
Assert.eq(kept_follow.friendship, 1, "已有想法的范围不被设置项改掉")
Assert.eq(kept_follow.isPrivate, 0)
local pulled_private = Notes.toAnnotations({ updated = {} }, "9", {
reviews = { { review = {
reviewId = "rv-p", chapterUid = "9", range = "0-1",
abstract = "原文", content = "私密", isPrivate = 1,
} } },
})
Assert.eq(pulled_private[1].wr_private, 1)
local pulled_follow = Notes.toAnnotations({ updated = {} }, "9", {
reviews = { { review = {
reviewId = "rv-f", chapterUid = "9", range = "0-1",
abstract = "原文", content = "关注", isPrivate = 0, friendship = 1,
} } },
})
Assert.eq(pulled_follow[1].wr_friendship, 1)
Assert.eq(pulled_follow[1].wr_private, 0)
local reconciled = { note = "想法", text = "原文", wr_range = "0-5", wr_review_id = "rv1" }
Notes.reconcileReviews({ reconciled }, {
reviews = { { review = { reviewId = "rv1", isPrivate = 1, range = "0-5", abstract = "原文", content = "想法" } } },
})
Assert.eq(reconciled.wr_private, 1)
local pending_private = {
note = "想法", text = "原文", wr_range = "0-5", wr_review_id = "rv1", wr_private = 0,
}
Notes.reconcileReviews({ pending_private }, {
reviews = { { review = { reviewId = "rv1", isPrivate = 1 } } },
})
Assert.eq(pending_private.wr_private, 0, "本地已记下的可见范围不被列表覆盖")
Assert.eq(Mapper.bookSecret({ book = { bookId = "1", secret = 1 } }), 1)
Assert.eq(Mapper.bookSecret({ book = { bookId = "1", version = 3 } }), 0)
Assert.is_nil(Mapper.bookSecret({}))
Assert.eq(Notes.privateOf({ review = { isPrivate = 1 } }), 1)
Assert.eq(Notes.privateOf({ review = { isPrivate = 0 } }), 0)
Assert.is_nil(Notes.privateOf({ review = {} }))
local pending = {
text = "原文", note = "想法", wr_range = "0-5", wr_review_only = true,
}
+30 -5
View File
@@ -76,6 +76,9 @@ stub("book.books_db", function()
local m = remembered_stats_books.marked_deleted
return m and not remembered_stats_books.removed and { m } or {}
end,
hasUnsynced = function()
return remembered_stats_books.marked_deleted ~= nil and not remembered_stats_books.removed
end,
markSynced = function() return true end,
setRead = function(source_id, stable_id, is_read)
remembered_stats_books.set_read = {
@@ -95,6 +98,7 @@ stub("book.progress_db", function()
get = function() return existing_progress end,
upsertRemote = function() return true end,
unsynced = function() return {} end,
hasUnsynced = function() return false end,
}
end)
stub("book.chapters_db", function()
@@ -1076,6 +1080,14 @@ do
cb({ succ = 1 })
return { cancel = function() end }
end
fake_client.bookInfoAsync = function(_, _, cb)
cb({ book = { bookId = "bpush", version = 7 } })
return { cancel = function() end }
end
fake_client.reviewSingleAsync = function(_, _, _, _, cb)
cb({ review = { isPrivate = 1 } })
return { cancel = function() end }
end
fake_client.deleteReviewAsync = function(_, review_id, cb)
calls[#calls + 1] = { api = "deleteReview", review_id = review_id }
cb({ succ = 1 })
@@ -1369,21 +1381,23 @@ do
require("moonsource_weread.toc").clear()
-- 书名搜索:只留带 bookId 的书目。
local keyword
fake_client.searchAsync = function(_self, word, cb)
keyword = word
local keyword, got_author
fake_client.searchAsync = function(_self, word, cb, author)
keyword, got_author = word, author
cb({ books = {
{ type = 0, bookInfo = { bookId = 834464, title = "活着", author = "余华", publisher = "作家" } },
{ type = 0, bookInfo = { bookId = 834464, title = "活着", author = "余华", translator = "曾思艺", publisher = "作家" } },
{ type = 3, mpInfo = { title = "公众号" } },
} })
return { cancel = function() end }
end
local found
src:searchBooksAsync("活着", function(books) found = books end)
src:searchBooksAsync("活着", function(books) found = books end, "余华")
Assert.eq(keyword, "活着")
Assert.eq(got_author, "余华")
Assert.len(found, 1)
Assert.eq(found[1].book_id, "834464")
Assert.eq(found[1].author, "余华")
Assert.eq(found[1].translator, "曾思艺", "搜索书目带译者")
end
-- pushNotesAsync 中途取消:在途请求被取消,迟到回包不回调、不再发后续请求。
@@ -1555,6 +1569,17 @@ do
Assert.is_true(reopen_pending, "手动强制刷新重新打开已有导入页")
Assert.eq(err, "pending import")
-- 后台同步先把快照存盘,之后普通手动刷新(非长按强刷)也必须弹出导入页
local opened = 0
require("utils.extension").add("web.open_page", function() opened = opened + 1 end)
src:syncBooksAsync({ manual = true }, function(r, e) result, err = r, e end)
require("support.stubs").flush()
Assert.eq(opened, 1, "普通手动刷新遇到没弹过的待导入快照要弹一次")
Assert.is_true(result.skipped)
src:syncBooksAsync({ manual = true }, function(r, e) result, err = r, e end)
require("support.stubs").flush()
Assert.eq(opened, 1, "同一份快照只弹一次,之后的普通刷新不再弹")
fake_client.shelfSyncIdsAsync, fake_client.shelfSyncAsync = nil, nil
package.loaded["moonsource_weread.shelf_import"] = saved_import
end