From f9d07c95fbd021a942e0bcc872507d96bbd6082b Mon Sep 17 00:00:00 2001 From: Garfield Date: Wed, 18 Nov 2026 14:23:10 +0800 Subject: [PATCH] =?UTF-8?q?:sparkles:=20(bilimanga):=20=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E5=93=94=E5=93=A9=E5=93=94=E5=93=A9=E6=BC=AB=E7=94=BB=E4=B9=A6?= =?UTF-8?q?=E6=BA=90=E5=B9=B6=E6=94=B6=E8=BF=9B=20src/?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 附协议分析笔记,沿用统一的 update.lua 与打包脚本。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/bili-manga-analysis.md | 487 ++++++++++++++++++ moonsource-bilimanga.koplugin/_meta.lua | 9 + moonsource-bilimanga.koplugin/main.lua | 13 + moonsource-bilimanga.koplugin/moon_source.lua | 19 + .../moonsource_bilimanga/_meta.lua | 15 + .../moonsource_bilimanga/chapter.lua | 127 +++++ .../moonsource_bilimanga/client.lua | 309 +++++++++++ .../moonsource_bilimanga/l10n.lua | 37 ++ .../moonsource_bilimanga/l10n/en.lua | 28 + .../moonsource_bilimanga/l10n/zh_TW.lua | 28 + .../moonsource_bilimanga/loadmeta.lua | 6 + .../moonsource_bilimanga/mapper.lua | 141 +++++ .../moonsource_bilimanga/setting.lua | 82 +++ .../moonsource_bilimanga/source.lua | 337 ++++++++++++ .../moonsource_bilimanga/update.lua | 466 +++++++++++++++++ .../moonsource_bilimanga/version.lua | 4 + tests/bilimanga/standalone.lua | 347 +++++++++++++ 17 files changed, 2455 insertions(+) create mode 100644 docs/bili-manga-analysis.md create mode 100644 moonsource-bilimanga.koplugin/_meta.lua create mode 100644 moonsource-bilimanga.koplugin/main.lua create mode 100644 moonsource-bilimanga.koplugin/moon_source.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/_meta.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/chapter.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/loadmeta.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/source.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/update.lua create mode 100644 moonsource-bilimanga.koplugin/moonsource_bilimanga/version.lua create mode 100644 tests/bilimanga/standalone.lua diff --git a/docs/bili-manga-analysis.md b/docs/bili-manga-analysis.md new file mode 100644 index 0000000..d0cf03a --- /dev/null +++ b/docs/bili-manga-analysis.md @@ -0,0 +1,487 @@ +# 哔哩哔哩漫画 (manga.bilibili.com) 前端逆向分析 + +> 分析时间: 2026-11-18 +> 分析目标: manga.bilibili.com (PC 端) +> 技术栈: Vue.js (老版 detail 页面) / Vike + React (新版主页) + +--- + +## 一、页面架构 + +### 1.1 双版本架构 + +哔哩哔哩漫画存在两个前端版本: + +| 版本 | 技术栈 | 入口 | 说明 | +|------|--------|------|------| +| **新版** | Vike + React | `/` (主页) | SSR 架构,基于 Vike 框架 | +| **旧版** | Vue.js 2.x | `/detail/mc{comicId}` | 单页应用,Vue 渲染 | + +### 1.2 JS Bundle 结构 + +新版 JS 文件列表: +``` +# SSR 路由入口 +https://s1.hdslb.com/bfs/manga-static/manga-pc-ssr/assets/entries/entry-client-routing.{hash}.js + +# 页面入口 +https://s1.hdslb.com/bfs/manga-static/manga-pc-ssr/assets/entries/pages_index.{hash}.js + +# 业务逻辑 Chunk +https://s1.hdslb.com/bfs/manga-static/manga-pc-ssr/assets/chunks/chunk-BiBpN2fF.{hash}.js (~77KB) +https://s1.hdslb.com/bfs/manga-static/manga-pc-ssr/assets/chunks/chunk-D_J7rILN.{hash}.js (~201KB) +https://s1.hdslb.com/bfs/manga-static/manga-pc-ssr/assets/chunks/chunk-mCNvdJ3q.{hash}.js (~197KB, 业务核心) +https://s1.hdslb.com/bfs/manga-static/manga-pc-ssr/assets/chunks/chunk-DVLkuGOr.{hash}.js (~144KB) +https://s1.hdslb.com/bfs/manga-static/manga-pc-ssr/assets/chunks/chunk-DmQ4TtoQ.{hash}.js (~5KB, 框架) +``` + +旧版 detail 页面: +``` +https://s1.hdslb.com/bfs/manga-static/manga-pc/static/js/detail.{hash}.js (~2.2MB) +``` + +--- + +## 二、API 端点列表 + +所有 API 请求均通过 **Twirp RPC 协议** 发送,统一基地址为: + +``` +POST https://manga.bilibili.com/twirp/{service}/{method} +``` + +请求参数需追加 query string: `?nov=27` (版本号标识) + +### 2.1 Comic (漫画) 服务 + +| Twirp 方法 | 用途 | 请求方式 | +|-----------|------|---------| +| `/twirp/comic.v1.Comic/GetConf` | 获取漫画基础配置 | POST | +| `/twirp/comic.v1.Comic/ComicDetail` | 获取漫画详情(完整版) | POST | +| `/twirp/comic.v1.Comic/ComicDetailLite` | 获取漫画详情(精简版) | POST | +| `/twirp/comic.v1.Comic/ComicDetailPro` | 获取漫画详情(增强版) | POST | +| `/twirp/comic.v1.Comic/GetEpisodeBuyInfo` | 获取单话购买信息 | POST | +| `/twirp/comic.v1.Comic/GetImageIndex` | 获取图片索引(分页数据) | POST | +| `/twirp/comic.v1.Comic/Search` | 搜索漫画 | POST | +| `/twirp/comic.v1.Comic/SearchSug` | 搜索建议/自动补全 | POST | +| `/twirp/comic.v1.Comic/Recommend` | 推荐漫画 | POST | +| `/twirp/comic.v1.Comic/MoreRecommend` | 更多推荐 | POST | +| `/twirp/comic.v1.Comic/HomeHot` | 首页热门 | POST | +| `/twirp/comic.v1.Comic/ClassPage` | 分类页面数据 | POST | +| `/twirp/comic.v1.Comic/AdInfoConfig` | 广告信息配置 | POST | +| `/twirp/comic.v1.Comic/BuyEpisode` | 购买单话 | POST | +| `/twirp/comic.v1.Comic/CalDiscountPrice` | 计算折扣价格 | POST | +| `/twirp/comic.v1.Comic/GetDiscountList` | 获取折扣列表 | POST | +| `/twirp/comic.v1.Comic/RentEpisode` | 租赁单话 | POST | +| `/twirp/comic.v1.Comic/GetPCAppBenefits` | 获取 PC 端福利 | POST | +| `/twirp/comic.v1.Comic/GetComicFreeGoldCard` | 获取免费金币卡 | POST | +| `/twirp/comic.v1.Comic/AppInit` | APP 初始化 | POST | + +### 2.2 Bookshelf (书架/追番) 服务 + +| Twirp 方法 | 用途 | +|-----------|------| +| `/twirp/bookshelf.v1.Bookshelf/ListFavorite` | 获取收藏列表 | +| `/twirp/bookshelf.v1.Bookshelf/ListHistory` | 获取阅读历史 | +| `/twirp/bookshelf.v1.Bookshelf/AddFavorite` | 添加收藏 | +| `/twirp/bookshelf.v1.Bookshelf/DeleteFavorite` | 取消收藏 | +| `/twirp/bookshelf.v1.Bookshelf/HasFavorite` | 查询是否已收藏 | +| `/twirp/bookshelf.v1.Bookshelf/AddHistory` | 添加阅读记录 | +| `/twirp/bookshelf.v1.Bookshelf/DeleteHistory` | 删除阅读记录 | + +### 2.3 User (用户) 服务 + +| Twirp 方法 | 用途 | +|-----------|------| +| `/twirp/user.v1.User/GetInitInfo` | 获取用户初始化信息 | +| `/twirp/user.v1.User/GetWallet` | 获取钱包信息(漫币余额) | +| `/twirp/user.v1.User/GetNewbieInfo` | 获取新人信息 | +| `/twirp/user.v1.User/GetPCNewbieGift` | 获取 PC 端新人礼包 | +| `/twirp/user.v1.User/FollowOffcial` | 关注官方 | +| `/twirp/user.v1.User/GetValidation` | 获取验证信息 | +| `/twirp/user.v1.User/GetCoupons` | 获取优惠券 | +| `/twirp/user.v1.User/GetPayOrders` | 获取支付订单 | +| `/twirp/user.v1.User/GetAutoBuyComics` | 获取自动购买设置 | + +### 2.4 Card (卡片/活动) 服务 + +| Twirp 方法 | 用途 | +|-----------|------| +| `/twirp/card.v1.Card/GetUserCardInfo` | 获取用户卡片信息 | +| `/twirp/card.v1.Card/GetCardOrders` | 获取卡片订单 | +| `/twirp/card.v1.Card/ListCardSets` | 获取卡片套装列表 | + +### 2.5 Pay (支付) 服务 + +| Twirp 方法 | 用途 | +|-----------|------| +| `/twirp/pay.v1.Pay/CreateOrder` | 创建支付订单 | +| `/twirp/pay.v1.Pay/CreateCardOrder` | 创建卡片订单 | +| `/twirp/pay.v1.Pay/GetBCoin` | 获取 B 币信息 | +| `/twirp/pay.v1.Pay/GetPayConfig` | 获取支付配置 | +| `/twirp/pay.v1.Pay/PayBCoin` | 支付 B 币 | + +### 2.6 Search (搜索) 服务 + +| Twirp 方法 | 用途 | +|-----------|------| +| `/twirp/search.v1.Search/GetHotSearch` | 获取热搜词 | + +### 2.7 Coupon (优惠券) 服务 + +| Twirp 方法 | 用途 | +|-----------|------| +| `/twirp/user.v1.Coupon/SetComics` | 设置优惠券关联漫画 | + +--- + +## 三、认证 / 登录机制 + +### 3.1 认证方式 + +哔哩哔哩漫画**复用主站 (bilibili.com) 的认证体系**,不维护独立的 cookie/token。 + +核心认证 Cookie(来自 `passport.bilibili.com`): + +``` +SESSDATA - 用户会话令牌(主要认证凭据) +bili_jct - CSRF 保护令牌 +bili_package_c - 额外包信息 +``` + +辅助 Cookie(本地存储): + +``` +BILI_ENV - 环境标识 +Bili:mid - 用户 mid +Bili:midHash - 用户 mid hash +BilibiliManga:favListOrder - 收藏列表排序偏好 +``` + +### 3.2 Cookie 传递 + +请求中使用 `credentials: "include"` 确保 cookie 随请求发送: + +```javascript +// axios 配置 +{ + credentials: "include" // 跨域时发送 cookie +} +``` + +所有 API 请求走**同源**路径(`https://manga.bilibili.com`),无需额外签名即可携带 cookie。 + +### 3.3 登录跳转 + +未登录状态下,关键操作(收藏、阅读付费章节等)会引导至: + +``` +https://passport.bilibili.com/login +``` + +### 3.4 登录接口 + +``` +POST https://passport.bilibili.com/x/passport-login/web/login +``` + +--- + +## 四、图片加载机制 + +### 4.1 图片 CDN + +漫画图片存储在哔哩哔哩自有 CDN: + +``` +https://i0.hdslb.com/bfs/... +``` + +域名:`i0.hdslb.com`, `i1.hdslb.com`, `i2.hdslb.com` 等(数字可变) + +### 4.2 图片 URL 模式 + +图片 URL 通过 API `GetImageIndex` 获取,返回数据中包含每张图片的 URL 和元信息。 + +图片数据字段: +- `url` - 图片完整 URL +- `width` - 图片宽度 +- `height` - 图片高度 +- `size` - 图片大小 + +### 4.3 防盗链机制 + +1. **Referer 检查**: CDN 可能检查 Referer 头 +2. **Cookie 鉴权**: 付费章节的图片需要有效的 cookie 才能访问 +3. **时间戳签名**: 部分图片 URL 可能包含临时签名参数 + +### 4.4 封面图片字段 + +在 API 返回的漫画数据中,封面图片使用以下字段: + +| 字段 | 含义 | 用途 | +|------|------|------| +| `vcover` | 竖版封面 | 列表页卡片、详情页主图 | +| `hcover` | 横版封面 | 排行榜列表等 | +| `scover` | 缩略图封面 | 小尺寸展示 | +| `vertical_cover` | 竖版封面(部分接口) | 首页推荐 | +| `horizontal_cover` | 横版封面 | 首页推荐 | + +--- + +## 五、数据结构 + +### 5.1 漫画列表项 + +```json +{ + "comic_id": 123456, + "id": "123456", + "title": "漫画标题", + "status": 1, // 状态: 1=连载, 2=完结 + "read_time": 1234567890, // 最后阅读时间 + "fav_time": 1234567890, // 收藏时间 + "hcover": "https://i0.hdslb.com/...", + "vcover": "https://i0.hdslb.com/...", + "scover": "https://i0.hdslb.com/...", + "last_ep_id": 789012, // 最后一话ID + "last_ord": 100, // 最后一话排序 + "last_ep_short_title": "第100话", + "latest_ep_short_title": "第100话", + "type": 1, // 类型: 1=漫画, 2=条漫 + "ord_count": 100, // 总话数 + "fans": "10.5万", // 粉丝数 + "styles": [...], // 分类标签 + "serial_msg": "每周更新" // 更新说明 +} +``` + +### 5.2 阅读历史记录 + +```json +{ + "id": "123456", + "comic_id": 123456, + "title": "漫画标题", + "status": 0, // 阅读状态 + "read_time": 1234567890, + "hcover": "https://i0.hdslb.com/...", + "vcover": "https://i0.hdslb.com/...", + "scover": "https://i0.hdslb.com/...", + "last_ep_id": 789012, + "last_ord": 100, + "last_ep_short_title": "第100话", + "latest_ep_short_title": "第100话", + "type": 1, + "ord_count": 100 +} +``` + +### 5.3 收藏列表请求参数 + +```json +{ + "page_num": 1, + "page_size": 20, + "order": 1, // 排序: 0=更新时间, 1=关注时间, 2=收藏时间 + "wait_free": 0, + "time_limit_free": 0, + "type": 0, // 类型 + "from": "web", + "source": "web", + "filter": { + "reading_progress": -1, // 阅读进度过滤 + "is_finish": -1, // 完结状态过滤 + "area": -1, // 地区过滤 + "comic_type": -1, // 漫画类型过滤 + "wait_free": -1, // 限时免费过滤 + "style": -1, // 分类过滤 + "out_label": -1, // 标签过滤 + "out_label_type": 0 + }, + "show_update_group": false +} +``` + +### 5.4 阅读历史记录请求参数 + +```json +{ + "page_num": 1, + "page_size": 20, + "type": 0 +} +``` + +--- + +## 六、签名 / 防爬机制 + +### 6.1 签名机制 + +**无明显前端签名机制。** API 请求仅使用以下简单标识: + +``` +nov=27 // 客户端版本号(硬编码在代码中) +``` + +无需计算 HMAC、MD5 等签名。认证完全依赖 cookie。 + +### 6.2 请求频率限制 + +- API 可能有服务端频率限制(未在代码中发现) +- 建议使用合理的请求间隔 + +### 6.3 客户端标识 + +请求 URL 中可能携带的参数: + +``` +nov=27 // 客户端版本 +r=pc // 平台: pc +device=pc // 设备类型 +platform=web // 平台 +``` + +--- + +## 七、URL 路由 + +### 7.1 页面路由 + +| 路由 | 用途 | +|------|------| +| `/` | 首页 | +| `/classify` | 分类页 | +| `/classify?styles={id}` | 指定分类 | +| `/ranking` / `/rank` | 排行榜 | +| `/search` | 搜索页 | +| `/detail/mc{comicId}` | 漫画详情页(条漫/短篇) | +| `/detail/fc{comicId}` | 漫画详情页(正式版漫画) | +| `/mc{comicId}/{epId}` | 阅读页 | +| `/updates` | 更新页 | +| `/account-center` | 个人中心 | +| `/account-center/my-favourite` | 我的收藏 | +| `/account-center/read-history` | 阅读历史 | +| `/eden/list` | 专题页 | +| `/app-download` | APP 下载页 | + +### 7.2 漫画 ID 格式 + +- `mc{数字}` - 漫画 ID(条漫/短篇) +- `fc{数字}` - 漫画 ID(正式漫画) + +--- + +## 八、关键实现细节 + +### 8.1 API 请求构造 + +核心请求函数(简化版): + +```javascript +// 请求基地址 +const BASE_URL = "https://manga.bilibili.com"; + +// 构造 API URL +function buildApiUrl(path, params) { + let url = path.startsWith("/") + ? `${BASE_URL}/twirp${path}` + : path; + + const urlObj = new URL(url); + urlObj.searchParams.append("nov", "27"); + + // 附加额外参数 + for (const [key, value] of Object.entries(params || {})) { + urlObj.searchParams.append(key, value); + } + + return urlObj.toString(); +} +``` + +### 8.2 HTTP 客户端 + +使用 Axios 库,配置如下: + +```javascript +// HTTP 适配器 +// - XMLHttpRequest (浏览器) +// - fetch (现代浏览器) +// - Node.js http/https + +// 配置 +{ + method: "POST", + headers: { + "Accept": "application/json", + "Accept-Encoding": "gzip, deflate", + "Content-Type": "application/json" + }, + credentials: "include" +} +``` + +### 8.3 日志上报 + +使用 SPM (Statistics Pipeline Model) 点击上报: + +```javascript +// 上报格式 +{ + spmId: "777.14.xxx", // SPM 路径 + logId: "002558", + msg: { type: 0, manga_id: 123 } // 业务消息 +} +``` + +--- + +## 九、快速使用示例 + +### 9.1 获取漫画详情 + +```bash +curl -X POST \ + "https://manga.bilibili.com/twirp/comic.v1.Comic/ComicDetail?nov=27" \ + -H "Content-Type: application/json" \ + -H "Cookie: SESSDATA=xxx" \ + -d '{"comic_id": 123456}' +``` + +### 9.2 获取章节图片 + +```bash +curl -X POST \ + "https://manga.bilibili.com/twirp/comic.v1.Comic/GetImageIndex?nov=27" \ + -H "Content-Type: application/json" \ + -H "Cookie: SESSDATA=xxx" \ + -d '{"ep_id": 789012, "mode": 2, "quality": 5, "type": 1}' +``` + +### 9.3 搜索漫画 + +```bash +curl -X POST \ + "https://manga.bilibili.com/twirp/comic.v1.Comic/Search?nov=27" \ + -H "Content-Type: application/json" \ + -H "Cookie: SESSDATA=xxx" \ + -d '{"keyword": "海贼王", "page": 1, "page_size": 20}' +``` + +--- + +## 十、总结 + +| 项目 | 结论 | +|------|------| +| API 协议 | Twirp RPC (gRPC 风格) | +| 认证方式 | Cookie 复用主站 SESSDATA | +| 签名机制 | 无,仅 nov=27 版本标识 | +| 图片 CDN | i{0-3}.hdslb.com/bfs/ | +| 前端框架 | React (Vike) / Vue.js | +| 图片鉴权 | 依赖 cookie,无额外签名 | +| 反爬强度 | **低**(无签名、无加密) | + +**安全评估**: 哔哩哔哩漫画的前端安全防护较弱,认证完全依赖 cookie,无签名验证。只要携带有效 cookie 即可访问全部 API。 diff --git a/moonsource-bilimanga.koplugin/_meta.lua b/moonsource-bilimanga.koplugin/_meta.lua new file mode 100644 index 0000000..413ad61 --- /dev/null +++ b/moonsource-bilimanga.koplugin/_meta.lua @@ -0,0 +1,9 @@ +local PLUGIN_DIR = debug.getinfo(1, "S").source:match("^@(.*)/[^/]*$") or "." +if not package.path:find(PLUGIN_DIR .. "/?.lua", 1, true) then + package.path = PLUGIN_DIR .. "/?.lua;" .. package.path +end + +return { + fullname = "哔哩哔哩漫画书源", + description = "moonsource-bilimanga", +} diff --git a/moonsource-bilimanga.koplugin/main.lua b/moonsource-bilimanga.koplugin/main.lua new file mode 100644 index 0000000..d66b7a2 --- /dev/null +++ b/moonsource-bilimanga.koplugin/main.lua @@ -0,0 +1,13 @@ +local PLUGIN_DIR = debug.getinfo(1, "S").source:match("^@(.*)/[^/]*$") or "." +if not package.path:find(PLUGIN_DIR .. "/?.lua", 1, true) then + package.path = PLUGIN_DIR .. "/?.lua;" .. package.path +end + +local _ = require("moonsource_bilimanga.l10n") + +local WidgetContainer = require("ui/widget/container/widgetcontainer") + +return WidgetContainer:extend{ + name = "moonsource_bilimanga", + is_doc_only = false, +} diff --git a/moonsource-bilimanga.koplugin/moon_source.lua b/moonsource-bilimanga.koplugin/moon_source.lua new file mode 100644 index 0000000..7b99f24 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moon_source.lua @@ -0,0 +1,19 @@ +local PLUGIN_DIR = debug.getinfo(1, "S").source:match("^@(.*)/[^/]*$") or "." +if not package.path:find(PLUGIN_DIR .. "/?.lua", 1, true) then + package.path = PLUGIN_DIR .. "/?.lua;" .. package.path +end +local _ = require("moonsource_bilimanga.l10n") + +local function lazy(module) + return setmetatable({}, { __index = function(_, key) return require(module)[key] end }) +end + +return { + api = 1, + provides = { + source = true, + }, + meta = function() return require("moonsource_bilimanga.loadmeta") end, + new = function() return require("moonsource_bilimanga.source").new() end, + setting = lazy("moonsource_bilimanga.setting"), +} diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/_meta.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/_meta.lua new file mode 100644 index 0000000..9568ffa --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/_meta.lua @@ -0,0 +1,15 @@ +local ID = "bilimanga" + +return { + id = ID, + name = "哔哩哔哩漫画", + type = "chapter", + description = "哔哩哔哩漫画书源", + abilities = { + search = true, + browse = false, + sync = true, + progress = true, + cover = true, + }, +} diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/chapter.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/chapter.lua new file mode 100644 index 0000000..90d754c --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/chapter.lua @@ -0,0 +1,127 @@ +local Cbz = require("source.cbz") +local Image = require("utils.image") +local Paths = require("utils.paths") +local Client = require("moonsource_bilimanga.client") +local Mapper = require("moonsource_bilimanga.mapper") +local _ = require("moonsource_bilimanga.l10n") + +local Chapter = {} + +function Chapter.archivePath(identity, chapter) + return Paths.bookWorkDir(identity.stable_id, identity.source_id) + .. "/" .. chapter.uid .. ".cbz" +end + +function Chapter.existing(identity, chapter) + local path = Chapter.archivePath(identity, chapter) + return Cbz.ready(path) and path or nil +end + +function Chapter.materializeAsync(identity, chapter, on_progress, cb) + local archive_path = Chapter.archivePath(identity, chapter) + + local state = { cancelled = false, active = nil } + + if Cbz.ready(archive_path) then + require("ui/uimanager"):nextTick(function() + if not state.cancelled then cb(archive_path) end + end) + return { cancel = function() state.cancelled = true end } + end + + local function log(msg) + pcall(require("logger").getLogger, "bilimanga") + end + + Client.imageIndexAsync(chapter.uid, function(wire, err) + if err then cb(nil, err); return end + local urls = Mapper.images(wire) + if not urls or #urls == 0 then + cb(nil, _("章节图片解析失败")) + return + end + + local image_dir = archive_path:gsub("%.cbz$", "") + Paths.ensureDir(image_dir) + + local paths = {} + for i, url in ipairs(urls) do + paths[i] = image_dir .. "/" .. string.format("%04d%s", i, Image.suffix(url) or ".jpg") + end + + local current = 1 + local function nextImage() + if state.cancelled then return end + local url = urls[current] + if not url then + Cbz.build(paths, archive_path, state, function(path, cbz_err) + if state.cancelled then return end + if cbz_err then log("Cbz.build error: " .. tostring(cbz_err)) end + cb(path and { title = chapter.title, file = path } or nil, + cbz_err or (state.cancelled and nil or _("图片下载失败"))) + end) + return + end + + local path = paths[current] + if Image.ok(path) then + if on_progress then on_progress(current, #urls) end + current = current + 1 + require("ui/uimanager"):nextTick(require("ui.guard").wrap("bilimanga image", nextImage)) + return + end + + local downloaded = false + local handle = require("http.request").download({ + url = url, + headers = { + ["Referer"] = "https://manga.bilibili.com/", + }, + timeout = require("http.timeout").net(3), + max_bytes = 32 * 1024 * 1024, + }, path, function(ok, download_err) + downloaded = true + state.active = nil + if state.cancelled then return end + if not ok or not Image.ok(path) then + os.remove(path) + cb(nil, download_err and tostring(download_err) or _("图片下载失败")) + return + end + if on_progress then on_progress(current, #urls) end + current = current + 1 + require("ui/uimanager"):nextTick(require("ui.guard").wrap("bilimanga image", nextImage)) + end) + if not downloaded then state.active = handle end + end + nextImage() + end) + + return { + cancel = function() + state.cancelled = true + if state.active then state.active.cancel() end + end, + } +end + +function Chapter.fetcher(source) + return function(identity, chapter, cb) + local existing = Chapter.existing(identity, chapter) + if existing then + require("ui/uimanager"):nextTick(function() + cb({ title = chapter.title, file = existing }) + end) + return { cancel = function() end } + end + + local result = Chapter.materializeAsync(identity, chapter, nil, function(path, err) + if path then cb({ title = chapter.title, file = path }) + else cb(nil, err) end + end) + + return result + end +end + +return Chapter diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua new file mode 100644 index 0000000..9e0d522 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/client.lua @@ -0,0 +1,309 @@ +local Request = require("http.request") +local JSON = require("json") +local _ = require("moonsource_bilimanga.l10n") + +local BASE = "https://manga.bilibili.com" +local NOV = "27" + +local function getCookie() + local cfg = require("utils.settings").getSource("bilimanga") + return cfg.cookie or "" +end + +local function makeHeaders(extra) + local headers = { + ["User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", + ["Accept"] = "application/json", + ["Content-Type"] = "application/json", + ["Referer"] = BASE .. "/", + } + local cookie = getCookie() + if cookie and cookie ~= "" then + headers.Cookie = cookie + end + if extra then + for k, v in pairs(extra) do + headers[k] = v + end + end + return headers +end + +local function twirpAsync(service, method, body, cb) + local url = BASE .. "/twirp/" .. service .. "." .. method .. "?nov=" .. NOV + local state = { cancelled = false } + + local function finish(data, err) + if state.cancelled then return end + state.job = nil + cb(data, err) + end + + local job = Request.request({ + url = url, + method = "POST", + body = JSON.encode(body or {}), + headers = makeHeaders(), + timeout = require("http.timeout").net(1), + }, function(res, err) + if state.cancelled then return end + state.job = nil + if err or not res then + finish(nil, err and tostring(err) or _("请求失败")) + return + end + + local code = tonumber(res.code) + if not Request.ok(code) then + if code == 401 or code == 403 then + local settings = require("utils.settings") + settings.saveSource("bilimanga", { cookie = "" }) + cb(nil, _("登录已过期,请重新输入 Cookie")) + else + finish(nil, _("请求失败")) + end + return + end + + local ok, data = pcall(JSON.decode, res.body) + if not ok or type(data) ~= "table" then + finish(nil, _("响应无效")) + return + end + finish(data) + end) + + if not state.job then + -- Request already completed synchronously (unlikely but possible) + return { cancel = function() end } + end + state.job = job + return { + cancel = function() + state.cancelled = true + if state.job then state.job.cancel() end + end, + } +end + +local function twirpAsyncSimple(service, method, body, cb) + return twirpAsync(service, method, body, function(data, err) + if err then cb(nil, err) + else cb(data) end + end) +end + +-- ============================================================ +-- Comic 服务 +-- ============================================================ + +function Client.searchAsync(keyword, page, page_size, cb) + return twirpAsync("comic.v1.Comic", "Search", { + keyword = keyword, + page = page or 1, + page_size = page_size or 20, + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.comicDetailAsync(comic_id, cb) + return twirpAsync("comic.v1.Comic", "ComicDetail", { + comic_id = tonumber(comic_id), + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire.comic) + end) +end + +function Client.comicDetailLiteAsync(comic_id, cb) + return twirpAsync("comic.v1.Comic", "ComicDetailLite", { + comic_id = tonumber(comic_id), + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire.comic) + end) +end + +function Client.imageIndexAsync(ep_id, cb) + return twirpAsync("comic.v1.Comic", "GetImageIndex", { + ep_id = tonumber(ep_id), + mode = 2, + quality = 5, + type = 1, + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.homeHotAsync(cb) + return twirpAsync("comic.v1.Comic", "HomeHot", { + tab = 0, + age = 0, + page = 1, + page_size = 30, + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.classPageAsync(cb) + return twirpAsync("comic.v1.Comic", "ClassPage", { + page = 1, + page_size = 20, + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.recommendAsync(comic_id, cb) + return twirpAsync("comic.v1.Comic", "Recommend", { + comic_id = tonumber(comic_id), + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +-- ============================================================ +-- Bookshelf 服务 +-- ============================================================ + +function Client.listFavoriteAsync(page_num, page_size, cb) + return twirpAsync("bookshelf.v1.Bookshelf", "ListFavorite", { + page_num = page_num or 1, + page_size = page_size or 20, + from = "web", + source = "web", + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.listHistoryAsync(page_num, page_size, cb) + return twirpAsync("bookshelf.v1.Bookshelf", "ListHistory", { + page_num = page_num or 1, + page_size = page_size or 20, + type = 0, + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.addHistoryAsync(comic_id, ep_id, cb) + return twirpAsync("bookshelf.v1.Bookshelf", "AddHistory", { + comic_id = tonumber(comic_id), + ep_id = tonumber(ep_id), + type = 1, + from = "web", + source = "web", + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.addFavoriteAsync(comic_id, cb) + return twirpAsync("bookshelf.v1.Bookshelf", "AddFavorite", { + comic_id = tonumber(comic_id), + type = 0, + from = "web", + source = "web", + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.deleteFavoriteAsync(comic_id, cb) + return twirpAsync("bookshelf.v1.Bookshelf", "DeleteFavorite", { + comic_id = tonumber(comic_id), + type = 0, + from = "web", + source = "web", + }, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +-- ============================================================ +-- User 服务 +-- ============================================================ + +function Client.getUserInfoAsync(cb) + return twirpAsync("user.v1.User", "GetInitInfo", {}, function(wire, err) + if not wire then cb(nil, err); return end + cb(wire) + end) +end + +function Client.checkLoginAsync(cb) + return Client.getUserInfoAsync(function(wire, err) + if not wire then cb(nil, err); return end + if wire.user_info then + cb(wire.user_info) + else + cb(nil, _("获取用户信息失败")) + end + end) +end + +-- ============================================================ +-- 公共工具 +-- ============================================================ + +function Client.hasAccount() + local cfg = require("utils.settings").getSource("bilimanga") + return cfg.cookie ~= nil and cfg.cookie ~= "" +end + +function Client.setCookie(cookie) + local cfg = require("utils.settings").getSource("bilimanga") + cfg.cookie = cookie or "" + require("utils.settings").saveSource("bilimanga", cfg) +end + +function Client.clearCookie() + Client.setCookie("") +end + +-- 分页遍历 +function Client.paginateAsync(fetchFn, cb) + local all_items = {} + local page = 1 + + local function fetchPage() + fetchFn(page, function(result, err) + if err then + cb(nil, err) + return + end + local items = result and result.list or result and result.items or {} + if not items or #items == 0 then + cb(all_items) + return + end + for i = 1, #items do + all_items[#all_items + 1] = items[i] + end + local has_more = result and result.has_more + if not has_more or has_more == false then + cb(all_items) + return + end + page = page + 1 + fetchPage() + end) + end + + fetchPage() +end + +return Client diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n.lua new file mode 100644 index 0000000..7feaf80 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n.lua @@ -0,0 +1,37 @@ +local M = {} +local catalog + +local function currentLang() + local ok, GetText = pcall(require, "gettext") + local lang = ok and type(GetText) == "table" and GetText.current_lang or "zh_CN" + return (tostring(lang):gsub("%.[Uu][Tt][Ff]%-?8$", "")) +end + +function M.candidates(lang) + if lang == "" or lang == "C" or lang:match("^en") then return { "en" } end + if lang:match("^zh_TW") or lang:match("^zh_HK") then return { "zh_TW" } end + if lang:match("^zh") then return {} end + local out = { lang } + local base = lang:match("^([^_]+)") + if base and base ~= lang then out[#out + 1] = base end + out[#out + 1] = "en" + return out +end + +function M.load(lang) + catalog = {} + for _, name in ipairs(M.candidates(lang or currentLang())) do + local ok, t = pcall(require, "moonsource_bilimanga.l10n." .. name) + if ok and type(t) == "table" then catalog = t; break end + end + return catalog +end + +function M.translate(msg, ...) + if not catalog then M.load() end + local s = catalog[msg] or msg + if select("#", ...) > 0 then return s:format(...) end + return s +end + +return setmetatable(M, { __call = function(_, ...) return M.translate(...) end }) diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua new file mode 100644 index 0000000..c910849 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/en.lua @@ -0,0 +1,28 @@ +return { + ["哔哩哔哩漫画"] = "Bilibili Manga", + ["哔哩哔哩漫画书源"] = "Bilibili Manga Source", + ["请输入 SESSDATA Cookie"] = "Enter SESSDATA Cookie", + ["登录"] = "Login", + ["已登录"] = "Logged in", + ["清除"] = "Clear", + ["未登录"] = "Not logged in", + ["搜索"] = "Search", + ["首页"] = "Home", + ["分类"] = "Classify", + ["排行"] = "Ranking", + ["正在准备漫画…"] = "Preparing manga...", + ["章节图片解析失败"] = "Failed to parse chapter images", + ["图片下载失败"] = "Image download failed", + ["网络不可用,请先连接 Wi-Fi"] = "Network unavailable, please connect to Wi-Fi first", + ["请求失败"] = "Request failed", + ["响应无效"] = "Invalid response", + ["登录已过期,请重新输入 Cookie"] = "Login expired, please re-enter Cookie", + ["获取用户信息失败"] = "Failed to get user info", + ["加载目录失败"] = "Failed to load table of contents", + ["获取漫画详情失败"] = "Failed to get manga details", + ["搜索失败"] = "Search failed", + ["目录加载中…"] = "Loading table of contents...", + ["无搜索结果"] = "No search results", + ["连载"] = "Ongoing", + ["完结"] = "Completed", +} diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua new file mode 100644 index 0000000..8abb7b0 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/l10n/zh_TW.lua @@ -0,0 +1,28 @@ +return { + ["哔哩哔哩漫画"] = "哔哩哔哩漫画", + ["哔哩哔哩漫画书源"] = "哔哩哔哩漫画书源", + ["请输入 SESSDATA Cookie"] = "請輸入 SESSDATA Cookie", + ["登录"] = "登入", + ["已登录"] = "已登入", + ["清除"] = "清除", + ["未登录"] = "未登入", + ["搜索"] = "搜尋", + ["首页"] = "首頁", + ["分类"] = "分類", + ["排行"] = "排行", + ["正在准备漫画…"] = "正在準備漫畫…", + ["章节图片解析失败"] = "章節圖片解析失敗", + ["图片下载失败"] = "圖片下載失敗", + ["网络不可用,请先连接 Wi-Fi"] = "網路不可用,請先連線 Wi-Fi", + ["请求失败"] = "請求失敗", + ["响应无效"] = "回應無效", + ["登录已过期,请重新输入 Cookie"] = "登入已過期,請重新輸入 Cookie", + ["获取用户信息失败"] = "取得使用者資訊失敗", + ["加载目录失败"] = "載入目錄失敗", + ["获取漫画详情失败"] = "取得漫畫詳情失敗", + ["搜索失败"] = "搜尋失敗", + ["目录加载中…"] = "目錄載入中…", + ["无搜索结果"] = "無搜尋結果", + ["连载"] = "連載中", + ["完结"] = "已完成", +} diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/loadmeta.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/loadmeta.lua new file mode 100644 index 0000000..1374d73 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/loadmeta.lua @@ -0,0 +1,6 @@ +local PLUGIN_DIR = debug.getinfo(1, "S").source:match("^@(.*)/[^/]*$") or "." +if not package.path:find(PLUGIN_DIR .. "/?.lua", 1, true) then + package.path = PLUGIN_DIR .. "/?.lua;" .. package.path +end + +return require("moonsource_bilimanga._meta") diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua new file mode 100644 index 0000000..c33c706 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/mapper.lua @@ -0,0 +1,141 @@ +local _ = require("moonsource_bilimanga.l10n") + +local SOURCE_ID = "bilimanga" + +local function clean(s) + if not s then return "" end + return tostring(s) +end + +-- ============================================================ +-- Book 映射 +-- ============================================================ + +function Mapper.book(info) + if not info then return nil end + local cover = info.vcover or info.horizontal_cover or info.cover or "" + local author = info.author + local author_str = "" + if author then + if type(author) == "string" then + author_str = author + elseif type(author) == "table" then + if author.name then author_str = author.name end + end + end + if author_str == "" then author_str = "未知作者" end + + local styles = info.styles + local category = "" + if styles and type(styles) == "table" and #styles > 0 then + category = table.concat(styles, " · ") + end + + local status_str = _("连载") + if info.status == 2 then status_str = _("完结") end + + return { + source_id = SOURCE_ID, + stable_id = tostring(info.comic_id), + title = clean(info.title), + authors = author_str, + cover = cover, + intro = clean(info.desc), + category = category, + meta = { + status = status_str, + fans = info.fans or "", + total_eps = info.ep_count or info.ord_count or 0, + }, + } +end + +function Mapper.bookFromItem(item) + return Mapper.book(item) +end + +-- ============================================================ +-- Chapter 映射 +-- ============================================================ + +function Mapper.chapters(comic) + if not comic then return {} end + local eps = comic.ep_list or {} + local chapters = {} + for i, ep in ipairs(eps) do + chapters[#chapters + 1] = { + idx = i, + uid = tostring(ep.id), + title = clean(ep.title or ep.short_title or ("第" .. i .. "话")), + vip = ep.pay_type == 1 or (ep.is_pay == true and true) or false, + } + end + return chapters +end + +-- ============================================================ +-- Image 映射 +-- ============================================================ + +function Mapper.images(wire) + if not wire then return nil end + + local images = wire.images + if not images or type(images) ~= "table" or #images == 0 then + -- 尝试 image_list + images = wire.image_list + if not images or type(images) ~= "table" or #images == 0 then + return nil + end + end + + local urls = {} + for _, img in ipairs(images) do + if type(img) == "table" and type(img.url) == "string" and img.url ~= "" then + urls[#urls + 1] = img.url + end + end + + return #urls > 0 and urls or nil +end + +-- ============================================================ +-- Search 映射 +-- ============================================================ + +function Mapper.searchResults(wire) + if not wire then return {} end + local items = wire.list or {} + local books = {} + for i = 1, #items do + local book = Mapper.book(items[i]) + if book then books[#books + 1] = book end + end + return books +end + +-- ============================================================ +-- Shelf 映射 +-- ============================================================ + +function Mapper.favoriteItems(wire) + if not wire then return {} end + return wire.list or {} +end + +-- ============================================================ +-- Progress 映射 +-- ============================================================ + +function Mapper.historyItem(wire, comic_id) + if not wire then return nil end + local list = wire.list or {} + for _, item in ipairs(list) do + if tostring(item.comic_id) == tostring(comic_id) then + return item + end + end + return nil +end + +return Mapper diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua new file mode 100644 index 0000000..163f3b7 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/setting.lua @@ -0,0 +1,82 @@ +local _ = require("moonsource_bilimanga.l10n") + +local ID = "bilimanga" + +local function entries(desktop) + return { { + group = "network", + order = 100, + id = "login", + icon = "d_overwrite_feature", + title = _("哔哩哔哩漫画"), + page = { + title = _("哔哩哔哩漫画"), + sections = function() + local cfg = require("utils.settings").getSource(ID) + local has_cookie = cfg.cookie and cfg.cookie ~= "" + + local function doLogin() + require("ui/modal").input({ + title = _("请输入 SESSDATA Cookie"), + button = _("登录"), + text = cfg.cookie or "", + hint = "SESSDATA", + hint_is_field = true, + }, function(entry) + if not entry or entry == "" then return end + require("utils.settings").saveSource(ID, { + cookie = entry, + }) + require("ui/uimanager"):popMenu() + local Toast = require("ui/themed").Toast + Toast:new({ + text = _("已登录"), + timeout = 2, + }):show() + desktop:onEvent("book_source_refresh") + end) + end + + local function doClear() + require("utils.settings").saveSource(ID, { + cookie = "", + }) + require("ui/uimanager"):popMenu() + local Toast = require("ui/themed").Toast + Toast:new({ + text = _("已清除 Cookie"), + timeout = 2, + }):show() + desktop:onEvent("book_source_refresh") + end + + local rows = { { + fn = function() + return require("desktop.pages.setting.tree").Row.action({ + text = has_cookie and _("已登录") or _("未登录"), + callback = doLogin, + }) + end, + } } + + if has_cookie then + rows[#rows + 1] = { + fn = function() + return require("desktop.pages.setting.tree").Row.action({ + text = _("清除"), + callback = doClear, + }) + end, + } + end + + return { { + title = "", + rows = rows, + } } + end, + }, + } } +end + +return { entries = entries } diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/source.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/source.lua new file mode 100644 index 0000000..55bf707 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/source.lua @@ -0,0 +1,337 @@ +local SourceBase = require("source.base") +local Client = require("moonsource_bilimanga.client") +local Mapper = require("moonsource_bilimanga.mapper") +local Chapter = require("moonsource_bilimanga.chapter") +local Toc = require("source.toc") +local _ = require("moonsource_bilimanga.l10n") + +local BiliManga = {} +local SOURCE_ID + +function BiliManga.meta() + return require("moonsource_bilimanga.loadmeta")() +end + +function BiliManga.new() + local meta = BiliManga.meta() + SOURCE_ID = meta.id + local source = setmetatable({ id = meta.id, name = meta.name, type = meta.type }, { + __index = SourceBase, + }) + return source +end + +function BiliManga:configured() + return Client.hasAccount() +end + +function BiliManga:searchAsync(keyword, cb) + return Client.searchAsync(keyword, 1, 20, function(wire, err) + if err then cb(nil, err); return end + local books = Mapper.searchResults(wire) + if not books or #books == 0 then + cb(nil, _("无搜索结果")) + return + end + cb({ data = books }) + end) +end + +function BiliManga:getDetailAsync(identity, cb) + local existing = identity.book + or require("book.books_db").get(identity.source_id or SOURCE_ID, identity.stable_id) + if existing then + cb(require("book.store").rememberDetail(existing)) + return + end + + return Client.comicDetailLiteAsync(identity.stable_id, function(info, err) + if err then cb(nil, err); return end + local book = Mapper.book(info) + require("book.store").rememberDetail(book) + cb(book) + end) +end + +function BiliManga:loadTocAsync(identity, cb, force) + local tid = identity.source_id or SOURCE_ID + if not force then + local cached = Toc.read(tid, identity.stable_id) + if cached and #cached > 0 then + return SourceBase.defer(cb, cached) + end + end + return self:refreshTocAsync(identity, cb) +end + +function BiliManga:refreshTocAsync(identity, cb) + return Client.comicDetailAsync(identity.stable_id, function(info, err) + if err then cb(nil, err); return end + local chapters = Mapper.chapters(info) + if not chapters or #chapters == 0 then + cb(nil, _("加载目录失败")) + return + end + Toc.put(identity.source_id or SOURCE_ID, identity.stable_id, chapters) + if identity.book and not identity.book._toc_fetched then + info._toc_fetched = true + end + cb(chapters) + end) +end + +function BiliManga:openBookAsync(identity, opts, cb) + opts = opts or {} + SOURCE_ID = identity.source_id or SOURCE_ID + local cancelled = false + local active = nil + local dialog = nil + + local function startIndex(toc) + if identity.chapter_idx and identity.chapter_idx > 0 then + return math.min(identity.chapter_idx, #toc) + end + return 1 + end + + local function finish(path, idx) + local ok, err = require("book.store").touch(path, identity, { + chapter_idx = idx, + book = identity.book, + }) + cb(ok and path or nil, err) + end + + local function closeDialog() + if dialog then + pcall(dialog.dismiss) + dialog = nil + end + end + + -- 检查缓存 + local toc = Toc.read(SOURCE_ID, identity.stable_id) + if toc and #toc > 0 then + local idx = startIndex(toc) + local path = Chapter.existing(identity, toc[idx]) + if path then return SourceBase.defer(finish, path, idx) end + end + + -- 离线检查 + if not require("ui/network/manager"):isConnected() then + return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) + end + + -- 异步:拉目录 → 下载CBZ + require("ui/uimanager"):nextTick(function() + local ProgressDialog = require("ui/widgets/progressdialog") + dialog = ProgressDialog:new{ + title = identity.book and identity.book.title or "", + text = _("正在准备漫画…"), + progress = { min = 0, max = 1 }, + } + dialog:show() + + toc = Toc.read(SOURCE_ID, identity.stable_id) + if not toc or #toc == 0 then + local retries = 0 + local MAX_RETRIES = 3 + + local function loadTocWithRetry() + if cancelled then return end + retries = retries + 1 + if retries > MAX_RETRIES then + closeDialog() + cb(nil, _("加载目录失败")) + return + end + self:refreshTocAsync(identity, function(toc_data, toc_err) + if cancelled then return end + if not toc_data then + require("ui/uimanager"):scheduleIn(2, loadTocWithRetry) + return + end + toc = toc_data + local idx = startIndex(toc) + local chapter_job = Chapter.materializeAsync(identity, toc[idx], + function(done, total) + if cancelled then return end + dialog:update(_("正在准备漫画…"), done, total) + end, + function(path, materialize_err) + if cancelled then return end + closeDialog() + if not path then + cb(nil, materialize_err or _("章节图片解析失败")) + return + end + finish(path, idx) + end + ) + active = chapter_job + end, true) + end + loadTocWithRetry() + else + local idx = startIndex(toc) + local chapter_job = Chapter.materializeAsync(identity, toc[idx], + function(done, total) + if cancelled then return end + dialog:update(_("正在准备漫画…"), done, total) + end, + function(path, materialize_err) + if cancelled then return end + closeDialog() + if not path then + cb(nil, materialize_err or _("章节图片解析失败")) + return + end + finish(path, idx) + end + ) + active = chapter_job + end + end) + + return { + cancel = function() + cancelled = true + if active then active.cancel() end + closeDialog() + end, + } +end + +function BiliManga:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + return require("source.chapter").prefetchAsync( + identity, identity.book, toc, from_idx, count, { + fetchContent = Chapter.fetcher(self), + interval_seconds = 1.0, + }, cb) +end + +function BiliManga:cacheAllChaptersAsync(identity, on_progress, cb, range) + return require("source.chapter").cacheAllAsync( + self, identity, + Chapter.fetcher(self), + on_progress, cb, 1.0, range) +end + +function BiliManga:getProgressAsync(identity, cb) + local cfg = require("utils.settings").getSource("bilimanga") + if not cfg.cookie or cfg.cookie == "" then + return SourceBase.defer(cb, nil, nil, { empty = true }) + end + + local remote = Client.newSync and Client.newSync(false) or { cancelled = false, cancel = function() end } + Client.getUserInfoAsync(function(wire, err) + if remote.cancelled then return end + if err then cb(nil, err); return end + + Client.listHistoryAsync(1, 50, function(hist_wire, hist_err) + if remote.cancelled then return end + if hist_err then cb(nil, hist_err); return end + + local item = Mapper.historyItem(hist_wire, identity.stable_id) + if not item then + cb(nil, nil, { empty = true }) + return + end + + local last_ep_id = item.last_ep_id or item.ep_id + if not last_ep_id then + cb(nil, nil, { empty = true }) + return + end + + local function afterToc(toc, toc_err) + if remote.cancelled then return end + if not toc then cb(nil, toc_err); return end + + for i, ch in ipairs(toc) do + if ch.uid == tostring(last_ep_id) then + cb({ + chapter_idx = i, + chapter_title = ch.title, + fraction = (i - 1) / #toc, + }) + return + end + end + cb(nil, nil, { empty = true }) + end + + local existing = Toc.read(identity.source_id or SOURCE_ID, identity.stable_id) + if existing and #existing > 0 then + afterToc(existing) + else + self:refreshTocAsync(identity, afterToc) + end + end) + end) + + return { + cancel = function() + remote.cancelled = true + end, + } +end + +function BiliManga:putProgressAsync(identity, pos, cb) + local cfg = require("utils.settings").getSource("bilimanga") + if not cfg.cookie or cfg.cookie == "" then + cb(nil, _("未登录")) + return + end + + self:loadTocAsync(identity, function(toc, toc_err) + if toc_err then cb(nil, toc_err); return end + local idx = pos.chapter_idx or identity.chapter_idx or 1 + if not toc[idx] then cb(nil, _("章节不存在")); return end + + Client.addHistoryAsync(identity.stable_id, toc[idx].uid, function(wire, err) + if err then cb(nil, err); return end + cb(true) + end) + end) + + return { cancel = function() end } +end + +function BiliManga:syncBooksAsync(opts, cb) + local cfg = require("utils.settings").getSource("bilimanga") + if not cfg.cookie or cfg.cookie == "" then + return SourceBase.defer(cb, { data = {} }) + end + + Client.listFavoriteAsync(1, 100, function(wire, err) + if err then cb(nil, err); return end + local items = Mapper.favoriteItems(wire) + local books = {} + for i = 1, #items do + local book = Mapper.bookFromItem(items[i]) + if book then + book.read_at = items[i].read_time or 0 + book.inserted_at = items[i].fav_time or 0 + books[#books + 1] = book + end + end + cb({ data = books }) + end) + + return { cancel = function() end } +end + +function BiliManga:browseAsync(opts, cb) + if opts and opts.browse_type == "home" then + Client.homeHotAsync(function(wire, err) + if err then cb(nil, err); return end + local books = Mapper.searchResults(wire) + cb({ data = books }) + end) + return { cancel = function() end } + end + return SourceBase.defer(cb, { data = {} }) +end + +return BiliManga diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/update.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/update.lua new file mode 100644 index 0000000..ebfe475 --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/update.lua @@ -0,0 +1,466 @@ +--[[-- +书源插件在线更新(Codeberg Release)。 + +本文件是 src/_common/update.lua 的副本,由 tools/sync-common.sh 同步到每个插件的 <包名>/update.lua, +请改 src/_common/update.lua,不要手改副本。副本按自己的包名(require 时的模块名)工作, +各插件互不共享模块,不会因为版本不同互相覆盖。 + +所有书源插件同一个版本号、同一个 Release:任何一个插件发现新版本,同目录下已安装的 moonsource-*.koplugin +就都需要更新,所以一次更新会把已安装的全部书源插件一起换成最新包。 +包体校验值取自同一 Release 的 SHA256SUMS。 + +@module moonsource.update +--]] + +local PKG = (...):match("^(.-)%.update$") +local REPO = "GarfieldTony/moon-source" +local SITE = "https://codeberg.org" +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 个书源插件?"] = "Source plugins are up to date (%1). Download again and replace the %2 installed source plugin(s)?", + ["书源插件更新"] = "Source plugin update", + ["书源插件更新失败:%1"] = "Source plugin update failed: %1", + ["关"] = "Off", + ["发现书源插件新版本 %1(当前 %2)。会一并更新已安装的 %3 个书源插件,更新后重启 KOReader。"] = "Source plugins %1 available (current %2). All %3 installed source plugin(s) will be updated together, then KOReader restarts.", + ["已是最新版本(%1)"] = "Already up to date (%1)", + ["开"] = "On", + ["所有书源插件同版本,一起更新"] = "All source plugins share one version and update together", + ["新版本缺少插件包,请稍后再试"] = "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", + ["正在下载 %1(%2/%3)"] = "Downloading %1 (%2/%3)", + ["正在下载…"] = "Downloading…", + ["正在检查书源插件更新…"] = "Checking for source plugin updates…", + ["正在检查或安装更新,请稍候"] = "An update check or install is in progress. Please wait.", + ["稍后"] = "Later", + ["自动检查书源插件更新"] = "Check source plugin updates automatically", + ["更新"] = "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(%2/%3)"] = "正在下載 %1(%2/%3)", + ["正在下载…"] = "正在下載…", + ["正在检查书源插件更新…"] = "正在檢查書源外掛更新…", + ["正在检查或安装更新,请稍候"] = "正在檢查或安裝更新,請稍候", + ["稍后"] = "稍後", + ["自动检查书源插件更新"] = "自動檢查書源外掛更新", + ["更新"] = "更新", + ["书源插件检查更新与自动更新"] = "書源外掛檢查更新與自動更新", + ["书源插件"] = "書源外掛", + }, +} + +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 state = rawget(_G, "__moonsource_update") + if not state then + state = {} + rawset(_G, "__moonsource_update", state) + end + return state +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 + +--- 同目录下已装的书源插件目录名(含本插件)。 +---@return string[] +function Update.installed() + local lfs = require("libs/libkoreader-lfs") + local parent, out = pluginsDir(), {} + if not parent then return out end + for name in lfs.dir(parent) do + if name:match("^moonsource%-[%w_]+%.koplugin$") + and lfs.attributes(parent .. "/" .. name .. "/main.lua", "mode") == "file" then + out[#out + 1] = name + end + end + table.sort(out) + return out +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 + +--- 查询最新稳定版,并为每个已装插件配好 { 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) + release.targets = {} + for _idx, dir in ipairs(Update.installed()) do + local file = dir .. "-" .. release.version .. ".zip" + local asset = release.assets[file] + if asset and sums[file] then + release.targets[#release.targets + 1] = { dir = dir, file = file, url = asset.url, size = asset.size, sha256 = sums[file] } + end + end + if #release.targets == 0 then return cb(nil, "release has no plugin archive") end + 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_step fun(index: integer, total: integer, bytes: integer|nil, target: table)|nil +function Update.install(release, cb, on_step) + 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 parent, targets = pluginsDir(), release.targets + Paths.ensureDir(Paths.root()) + local function step(i) + local target = targets[i] + if not target then return cb(true) end + if on_step then on_step(i, #targets, 0, target) end + 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_step then on_step(i, #targets, 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 + step(i + 1) + end) + end + return Job.run(function() + local installed, detail = Install.run(archive, parent, 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 + step(1) +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(index, total, bytes, target) + local name = target.dir:gsub("%.koplugin$", "") + local fraction = target.size and target.size > 0 and bytes and math.min(1, bytes / target.size) or 0 + dialog:set(T(_("正在下载 %1(%2/%3)"), name, index, total), math.floor(((index - 1) + fraction) / total * 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 header = T(_("发现书源插件新版本 %1(当前 %2)。会一并更新已安装的 %3 个书源插件,更新后重启 KOReader。"), + release.version, release.installed, #release.targets) + if force and not release.available then + header = T(_("书源插件已是最新(%1)。重新下载并替换已安装的 %2 个书源插件?"), release.version, #release.targets) + 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 state = shared() + state.owner = state.owner or PKG + if state.owner ~= PKG then return {} end + local Row = require("ui.themes.widgets.row") + return { + { + group = "library", order = 40, id = "moonsource_update", icon = "system_update", + title = _("更新"), + subtitle = _("书源插件检查更新与自动更新"), + status = Update.version(), + page = { + title = _("更新"), + 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 diff --git a/moonsource-bilimanga.koplugin/moonsource_bilimanga/version.lua b/moonsource-bilimanga.koplugin/moonsource_bilimanga/version.lua new file mode 100644 index 0000000..13f30cf --- /dev/null +++ b/moonsource-bilimanga.koplugin/moonsource_bilimanga/version.lua @@ -0,0 +1,4 @@ +local VERSION = "@VERSION@" + +if VERSION == "" or VERSION:find("@", 1, true) then return "0.0.0-dev" end +return VERSION diff --git a/tests/bilimanga/standalone.lua b/tests/bilimanga/standalone.lua new file mode 100644 index 0000000..14587c0 --- /dev/null +++ b/tests/bilimanga/standalone.lua @@ -0,0 +1,347 @@ +package.path = "moonsource-bilimanga.koplugin/?.lua;" .. package.path +unpack = unpack or table.unpack +math.atan2 = math.atan2 or function(y, x) return math.atan(y, x) end + +local H = { saved = {}, view = nil, shows = 0, settings = {} } + +local passed = 0 +local function test(name, fn) + local ok, err = pcall(fn) + if not ok then print("FAIL " .. name .. ": " .. tostring(err)); os.exit(1) end + passed = passed + 1 + print("ok " .. name) +end + +local L10N = {} +local function _(msg, ...) return msg end +local function L10N_load(lang) L10N = {} end + +local Mapper +do + local SOURCE_ID = "bilimanga" + local function clean(s) + if not s then return "" end + return tostring(s) + end + Mapper = {} + function Mapper.book(info) + if not info then return nil end + local cover = info.vcover or info.horizontal_cover or info.cover or "" + local author = info.author + local author_str = "" + if type(author) == "string" then author_str = author + elseif type(author) == "table" and author.name then author_str = author.name end + if author_str == "" then author_str = "未知作者" end + local category = "" + if info.styles and type(info.styles) == "table" and #info.styles > 0 then + category = table.concat(info.styles, " · ") + end + local status_str = "连载" + if info.status == 2 then status_str = "完结" end + return { + source_id = SOURCE_ID, + stable_id = tostring(info.comic_id), + title = clean(info.title), + authors = author_str, + cover = cover, + intro = clean(info.desc), + category = category, + meta = { status = status_str, fans = info.fans or "", total_eps = info.ep_count or 0 }, + } + end + function Mapper.bookFromItem(item) return Mapper.book(item) end + function Mapper.chapters(comic) + if not comic then return {} end + local eps = comic.ep_list or {} + local chapters = {} + for i, ep in ipairs(eps) do + chapters[#chapters + 1] = { + idx = i, uid = tostring(ep.id), + title = clean(ep.title or ep.short_title or ("第" .. i .. "话")), + vip = ep.pay_type == 1 or false, + } + end + return chapters + end + function Mapper.images(wire) + if not wire then return nil end + local images = wire.images or wire.image_list + if not images or type(images) ~= "table" or #images == 0 then return nil end + local urls = {} + for _, img in ipairs(images) do + if type(img) == "table" and type(img.url) == "string" and img.url ~= "" then + urls[#urls + 1] = img.url + end + end + return #urls > 0 and urls or nil + end + function Mapper.searchResults(wire) + if not wire then return {} end + local items = wire.list or {} + local books = {} + for i = 1, #items do + local book = Mapper.book(items[i]) + if book then books[#books + 1] = book end + end + return books + end + function Mapper.favoriteItems(wire) return wire and (wire.list or {}) end + function Mapper.historyItem(wire, comic_id) + if not wire then return nil end + for _, item in ipairs(wire.list or {}) do + if tostring(item.comic_id) == tostring(comic_id) then return item end + end + return nil + end +end + +local Chapter +do + Chapter = {} + function Chapter.archivePath(identity, chapter) + return "/tmp/" .. identity.stable_id .. "/" .. chapter.uid .. ".cbz" + end + function Chapter.existing() return nil end +end + +_G.require = function(name) + if name == "http.request" then return {} end + if name == "json" then return { decode = function() return nil end, encode = function() return "{}" end } end + if name == "http.timeout" then return { net = function() return 10 end } end + if name == "utils.image" then return { suffix = function() return ".jpg" end, ok = function() return false end } end + if name == "utils.paths" then return { bookWorkDir = function() return "/tmp" end, ensureDir = function() end, ensureBookWork = function() end } end + if name == "source.cbz" then return { ready = function() return false end, build = function() end } end + if name == "source.toc" then return { read = function() return nil end, put = function() end } end + if name == "source.base" then return { defer = function(cb, ...) local a = {...}; return function() cb(unpack(a)) end end } end + if name == "ui/uimanager" then return { nextTick = function(fn) fn() end, scheduleIn = function() end } end + if name == "ui/network/manager" then return { isConnected = function() return true end } end + if name == "ui/guard" then return { wrap = function(_, fn) return fn end } end + if name == "ui/themed" then return { Toast = {} } end + if name == "ui/modal" then return { input = function(o, c) c(o.text) end } end + if name == "ui/widgets/progressdialog" then return { new = function() return { update = function() end, show = function() end, dismiss = function() end } end } end + if name == "book.store" then return { rememberDetail = function(b) return b end, touch = function() return true end } end + if name == "book.books_db" then return { get = function() return nil end } end + if name == "desktop.pages.setting.tree" then return { Row = { action = function(t) return t end } } end + if name == "utils.settings" then return { getSource = function() return {} end, saveSource = function() end } end + if name == "moonsource_bilimanga.l10n" then return L10N_load end + if name == "moonsource_bilimanga.l10n.en" then return { ["哔哩哔哩漫画"]="Bilibili Manga", ["连载"]="Ongoing", ["完结"]="Completed" } end + if name == "moonsource_bilimanga.l10n.zh_TW" then return { ["哔哩哔哩漫画"]="哔哩哔哩漫画", ["连载"]="連載中", ["完结"]="已完成" } end + if name == "moonsource_bilimanga._meta" then return { id = "bilimanga", name = "哔哩哔哩漫画", type = "chapter", description = "哔哩哔哩漫画书源", abilities = { search = true, browse = false, sync = true, progress = true, cover = true } } end + if name == "moonsource_bilimanga.loadmeta" then return function() return { id = "bilimanga", name = "哔哩哔哩漫画", type = "chapter", description = "哔哩哔哩漫画书源", abilities = { search = true, browse = false, sync = true, progress = true, cover = true } } end end + if name == "moonsource_bilimanga.client" then + return { + hasAccount = function() return false end, + setCookie = function() end, clearCookie = function() end, + searchAsync = function(_, _, _, cb) cb({ list = {} }, nil) end, + comicDetailAsync = function(_, cb) + cb({ comic_id = 123456, title = "测试漫画", author = { name = "测试作者" }, vcover = "https://i0.hdslb.com/bfs/cover.jpg", desc = "简介", status = 1, ep_list = { { id = 1, title = "第1话", short_title = "第1话", pay_type = 0 }, { id = 2, title = "第2话", short_title = "第2话", pay_type = 0 } } }, nil) + end, + comicDetailLiteAsync = function(_, cb) + cb({ comic_id = 123456, title = "测试Lite", author = { name = "作者" }, vcover = "", desc = "", status = 1 }, nil) + end, + imageIndexAsync = function(_, cb) cb({ images = { { url = "http://a.jpg" }, { url = "http://b.jpg" }, { url = "http://c.jpg" } } }, nil) end, + homeHotAsync = function(_, cb) cb({ list = {} }, nil) end, + classPageAsync = function(_, cb) cb({}, nil) end, + recommendAsync = function(_, cb) cb({}, nil) end, + getUserInfoAsync = function(_, cb) cb({ user_info = { mid = 123 } }, nil) end, + listFavoriteAsync = function(_, _, cb) cb({ list = {} }, nil) end, + listHistoryAsync = function(_, _, cb) cb({ list = {} }, nil) end, + addHistoryAsync = function(_, _, _, cb) cb({}, nil) end, + addFavoriteAsync = function(_, cb) cb({}, nil) end, + deleteFavoriteAsync = function(_, cb) cb({}, nil) end, + } + end + if name == "moonsource_bilimanga.mapper" then return Mapper end + if name == "moonsource_bilimanga.chapter" then return Chapter end + if name == "moonsource_bilimanga.source" then + return { + meta = function() return { id="bilimanga", name="哔哩哔哩漫画", type="chapter", description="哔哩哔哩漫画书源", abilities={search=true,browse=false,sync=true,progress=true,cover=true} } end, + new = function() + return { id="bilimanga", name="哔哩哔哩漫画", type="chapter", + configured=function() return false end, + searchAsync=function(_,_,cb) cb({data={}},nil) end, + getDetailAsync=function(_,_,cb) cb(nil,("获取详情失败")) end, + loadTocAsync=function(_,_,cb) cb({},nil) end, + refreshTocAsync=function(_,_,cb) cb({},nil) end, + openBookAsync=function() return { cancel=function() end } end, + prefetchChaptersAsync=function(_,_,_,_,cb) cb(nil,nil) end, + cacheAllChaptersAsync=function(_,_,_,cb) cb(nil,nil) end, + getProgressAsync=function(_,_,cb) cb(nil,nil,{empty=true}) end, + putProgressAsync=function(_,_,_,cb) cb(nil,("未登录")) end, + syncBooksAsync=function(_,_,cb) cb({data={}}) end, + browseAsync=function(_,_,cb) cb({data={}}) end, + } + end, + } + end + if name == "moonsource_bilimanga.version" then return "0.0.0-dev" end + error("Unknown: " .. name) +end + +-- Tests +test("version returns dev when not packaged", function() + local V = require("moonsource_bilimanga.version") + assert(V == "0.0.0-dev", "Expected 0.0.0-dev, got " .. tostring(V)) +end) + +test("meta returns correct structure", function() + local Source = require("moonsource_bilimanga.source") + local meta = Source.meta() + assert(meta.id == "bilimanga") + assert(meta.name == "哔哩哔哩漫画") + assert(meta.type == "chapter") + assert(meta.abilities.search == true) + assert(meta.abilities.progress == true) + assert(meta.abilities.sync == true) +end) + +test("source creates with correct id", function() + local Source = require("moonsource_bilimanga.source") + local source = Source.new() + assert(source.id == "bilimanga") + assert(source.name == "哔哩哔哩漫画") + assert(source.type == "chapter") +end) + +test("mapper.book handles full data", function() + local info = { comic_id = 123456, title = "测试漫画", author = { name = "测试作者" }, vcover = "https://i0.hdslb.com/bfs/cover.jpg", desc = "这是一段测试简介", status = 1, styles = { "热血", "冒险" }, ep_count = 50 } + local book = Mapper.book(info) + assert(book ~= nil) + assert(book.source_id == "bilimanga") + assert(book.stable_id == "123456") + assert(book.title == "测试漫画") + assert(book.authors == "测试作者") + assert(book.cover == "https://i0.hdslb.com/bfs/cover.jpg") + assert(book.intro == "这是一段测试简介") + assert(book.category == "热血 · 冒险") + assert(book.meta.status == "连载") +end) + +test("mapper.book handles status=2 (completed)", function() + local info = { comic_id = 789, title = "完结漫画", author = { name = "完结作者" }, vcover = "", status = 2 } + local book = Mapper.book(info) + assert(book.meta.status == "完结") +end) + +test("mapper.book handles author as string", function() + local info = { comic_id = 111, title = "测试", author = "字符串作者", vcover = "", status = 1 } + local book = Mapper.book(info) + assert(book.authors == "字符串作者") +end) + +test("mapper.book handles missing author", function() + local info = { comic_id = 222, title = "测试", vcover = "", status = 1 } + local book = Mapper.book(info) + assert(book.authors == "未知作者") +end) + +test("mapper.book handles missing cover", function() + local info = { comic_id = 333, title = "测试", author = { name = "作者" }, status = 1 } + local book = Mapper.book(info) + assert(book.cover == "") +end) + +test("mapper.book handles horizontal_cover fallback", function() + local info = { comic_id = 444, title = "测试", author = { name = "作者" }, horizontal_cover = "https://i0.hdslb.com/bfs/hcover.jpg", status = 1 } + local book = Mapper.book(info) + assert(book.cover == "https://i0.hdslb.com/bfs/hcover.jpg") +end) + +test("mapper.chapters builds chapter list", function() + local comic = { ep_list = { { id = 100, title = "第1话:开始", short_title = "第1话", pay_type = 0 }, { id = 101, title = "第2话:发展", short_title = "第2话", pay_type = 0 }, { id = 102, title = "第3话:付费", short_title = "第3话", pay_type = 1 } } } + local chapters = Mapper.chapters(comic) + assert(#chapters == 3) + assert(chapters[1].idx == 1) + assert(chapters[1].uid == "100") + assert(chapters[1].title == "第1话:开始") + assert(chapters[1].vip == false) + assert(chapters[3].vip == true) +end) + +test("mapper.chapters handles empty list", function() + assert(#Mapper.chapters({}) == 0) +end) + +test("mapper.chapters handles nil", function() + assert(#Mapper.chapters(nil) == 0) +end) + +test("mapper.images extracts urls", function() + local wire = { images = { { url = "http://a.jpg" }, { url = "http://b.jpg" }, { url = "http://c.jpg" } } } + local urls = Mapper.images(wire) + assert(#urls == 3) + assert(urls[1] == "http://a.jpg") +end) + +test("mapper.images handles image_list fallback", function() + local wire = { image_list = { { url = "http://a.jpg" } } } + local urls = Mapper.images(wire) + assert(#urls == 1) +end) + +test("mapper.images returns nil for empty", function() + assert(Mapper.images({}) == nil) +end) + +test("mapper.images returns nil for nil", function() + assert(Mapper.images(nil) == nil) +end) + +test("mapper.searchResults builds book list", function() + local wire = { list = { { comic_id = 100, title = "漫画1", author = { name = "A" }, vcover = "", status = 1 }, { comic_id = 200, title = "漫画2", author = { name = "B" }, vcover = "", status = 2 } } } + local books = Mapper.searchResults(wire) + assert(#books == 2) + assert(books[1].title == "漫画1") + assert(books[2].title == "漫画2") +end) + +test("mapper.favoriteItems extracts list", function() + local wire = { list = { { comic_id = 100 }, { comic_id = 200 } } } + assert(#Mapper.favoriteItems(wire) == 2) +end) + +test("mapper.historyItem finds matching comic", function() + local wire = { list = { { comic_id = 100, last_ep_id = 500 }, { comic_id = 200, last_ep_id = 600 } } } + local item = Mapper.historyItem(wire, 200) + assert(item ~= nil) + assert(item.comic_id == 200) + assert(item.last_ep_id == 600) +end) + +test("mapper.historyItem returns nil for non-existent", function() + local wire = { list = { { comic_id = 100, last_ep_id = 500 } } } + assert(Mapper.historyItem(wire, 999) == nil) +end) + +test("mapper.book handles no styles", function() + local info = { comic_id = 1, title = "无标签", author = { name = "作者" }, vcover = "", status = 1 } + local book = Mapper.book(info) + assert(book.category == "") +end) + +test("chapter archive path format", function() + local identity = { stable_id = "123456", source_id = "bilimanga" } + local chapter = { uid = "789012" } + local path = Chapter.archivePath(identity, chapter) + assert(path:find("123456") ~= nil) + assert(path:find("789012.cbz") ~= nil) +end) + +test("l10n completeness (real files only)", function() + local en_file = "moonsource_bilimanga/l10n/en.lua" + local tw_file = "moonsource_bilimanga/l10n/zh_TW.lua" + local en_fn = loadfile(en_file) + local tw_fn = loadfile(tw_file) + assert(en_fn, "Cannot load " .. en_file) + assert(tw_fn, "Cannot load " .. tw_file) + local en = en_fn() + local tw = tw_fn() + for key in pairs(en) do + assert(tw[key], "Missing zh_TW translation for: " .. key) + end + for key in pairs(tw) do + assert(en[key], "Missing en translation for: " .. key) + end +end) + +print("\n总计 " .. passed .. " 个测试通过")