From 99d94c0d5136ef533d609af3aec519164cc638e4 Mon Sep 17 00:00:00 2001 From: Garfield Date: Fri, 27 Nov 2026 08:08:01 +0800 Subject: [PATCH] =?UTF-8?q?:truck:=20(split):=20=E4=BB=8E=E6=9C=88?= =?UTF-8?q?=E8=AF=BB=E6=8B=86=E5=87=BA=E7=8B=AC=E7=AB=8B=E4=BB=93=E5=BA=93?= =?UTF-8?q?=EF=BC=8C=E6=B2=BF=E7=94=A8=E5=8E=9F=E4=B9=A6=E6=BA=90=20id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/release.yml | 86 +++ .gitignore | 4 + CHANGELOG.md | 7 + LICENSE | 674 ++++++++++++++++++ README.md | 47 ++ moonsource-copymanga.koplugin/_meta.lua | 5 + moonsource-copymanga.koplugin/main.lua | 9 + moonsource-copymanga.koplugin/moon_source.lua | 17 + .../moonsource_copymanga/README.md | 18 + .../moonsource_copymanga/_meta.lua | 15 + .../moonsource_copymanga/auth.lua | 176 +++++ .../moonsource_copymanga/chapter.lua | 169 +++++ .../moonsource_copymanga/client.lua | 435 +++++++++++ .../moonsource_copymanga/l10n/en.lua | 52 ++ .../moonsource_copymanga/l10n/zh_TW.lua | 52 ++ .../moonsource_copymanga/loadmeta.lua | 5 + .../moonsource_copymanga/mapper.lua | 193 +++++ .../moonsource_copymanga/protocol.lua | 64 ++ .../moonsource_copymanga/setting.lua | 156 ++++ .../moonsource_copymanga/source.lua | 449 ++++++++++++ .../moonsource_copymanga/version.lua | 4 + tests/copymanga/api_spec.lua | 127 ++++ tests/copymanga/auth_spec.lua | 88 +++ tests/copymanga/browse_spec.lua | 57 ++ tests/copymanga/chapter_spec.lua | 122 ++++ tests/copymanga/client_spec.lua | 187 +++++ tests/copymanga/mapper_spec.lua | 131 ++++ tests/copymanga/open_spec.lua | 151 ++++ tests/copymanga/progress_spec.lua | 197 +++++ tests/copymanga/protocol_spec.lua | 69 ++ tests/copymanga/setting_spec.lua | 52 ++ tests/copymanga/sync_spec.lua | 91 +++ tests/copymanga/toc_spec.lua | 70 ++ tools/package.sh | 25 + tools/release.sh | 41 ++ tools/run-tests.sh | 16 + 36 files changed, 4061 insertions(+) create mode 100644 .github/workflows/release.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 moonsource-copymanga.koplugin/_meta.lua create mode 100644 moonsource-copymanga.koplugin/main.lua create mode 100644 moonsource-copymanga.koplugin/moon_source.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/README.md create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/_meta.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/auth.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/chapter.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/client.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/l10n/en.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/l10n/zh_TW.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/loadmeta.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/mapper.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/protocol.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/setting.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/source.lua create mode 100644 moonsource-copymanga.koplugin/moonsource_copymanga/version.lua create mode 100644 tests/copymanga/api_spec.lua create mode 100644 tests/copymanga/auth_spec.lua create mode 100644 tests/copymanga/browse_spec.lua create mode 100644 tests/copymanga/chapter_spec.lua create mode 100644 tests/copymanga/client_spec.lua create mode 100644 tests/copymanga/mapper_spec.lua create mode 100644 tests/copymanga/open_spec.lua create mode 100644 tests/copymanga/progress_spec.lua create mode 100644 tests/copymanga/protocol_spec.lua create mode 100644 tests/copymanga/setting_spec.lua create mode 100644 tests/copymanga/sync_spec.lua create mode 100644 tests/copymanga/toc_spec.lua create mode 100755 tools/package.sh create mode 100755 tools/release.sh create mode 100755 tools/run-tests.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..cb8d0df --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,86 @@ +name: Release + +# 推送 vX.Y.Z(或 vX.Y.Z-rc.1 等预发布)标签:打包本仓库的插件为 zip → 建 Release 并上传。 +# 更新日志取自 CHANGELOG.md 里 "## <版本号>" 这一节,作为 Release 说明(月读的更新弹窗也会显示)。 +# 令牌默认用内置 GITHUB_TOKEN;需要时可在仓库密钥里配 RELEASE_TOKEN 覆盖。 +on: + push: + tags: + - "v*" + +jobs: + release: + runs-on: gitea + container: + image: node:22-bookworm + steps: + # 实例内网地址在任务容器里解析不了,签出和 API 都走公网地址 + - name: Checkout + uses: actions/checkout@v4 + with: + github-server-url: https://git.garfieldho.me + + - name: Resolve version + id: ver + run: | + set -euo pipefail + TAG="${GITHUB_REF_NAME}" + VERSION="${TAG#v}" + if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.+-].*)?$ ]]; then + echo "标签不合法:${TAG}(应为 vMAJOR.MINOR.PATCH)" + exit 1 + fi + PRERELEASE=false + [[ "$VERSION" == *-* ]] && PRERELEASE=true + { + echo "tag=${TAG}" + echo "version=${VERSION}" + echo "prerelease=${PRERELEASE}" + } >> "$GITHUB_OUTPUT" + shell: bash + + - name: Install packaging tools + run: apt-get update && apt-get install -y -o Acquire::Retries=3 rsync zip + + - name: Package plugin + run: tools/package.sh "${{ steps.ver.outputs.version }}" dist + + - name: Create release and upload assets + env: + TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }} + TAG: ${{ steps.ver.outputs.tag }} + PRERELEASE: ${{ steps.ver.outputs.prerelease }} + VERSION: ${{ steps.ver.outputs.version }} + run: | + set -euo pipefail + : "${TOKEN:?没有可用令牌:没有内置令牌,也没有配置 RELEASE_TOKEN}" + API="https://git.garfieldho.me/api/v1/repos/${GITHUB_REPOSITORY}" + AUTH="Authorization: token ${TOKEN}" + + # 同一标签重跑:删掉旧 Release 再建,附件不会重复 + OLD=$(curl -fsS -H "$AUTH" "${API}/releases/tags/${TAG}" 2>/dev/null | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{console.log(JSON.parse(s).id||"")}catch(e){}})' || true) + [ -n "$OLD" ] && curl -fsS -X DELETE -H "$AUTH" "${API}/releases/${OLD}" + + BODY=$(node -e ' + const fs = require("fs"); + let notes = ""; + try { + const lines = fs.readFileSync("CHANGELOG.md", "utf8").split(/\r?\n/); + const start = lines.findIndex(l => l.trim() === "## " + process.env.VERSION); + if (start >= 0) { + let end = lines.findIndex((l, i) => i > start && /^## /.test(l)); + if (end < 0) end = lines.length; + notes = lines.slice(start + 1, end).join("\n").trim(); + } + } catch (e) {} + const tail = "给月读增加在线平台书源的 KOReader 插件。把 zip 解压到 KOReader 的 plugins/ 目录即可,附件 SHA256SUMS 用于校验。与各平台官方无关,使用风险自行承担。"; + console.log(JSON.stringify({tag_name:process.env.TAG,name:process.env.TAG,prerelease:process.env.PRERELEASE==="true",body:notes?notes+"\n\n---\n"+tail:tail})); + ') + ID=$(curl -fsS -X POST -H "$AUTH" -H "Content-Type: application/json" -d "$BODY" "${API}/releases" \ + | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.parse(s).id))') + + for f in dist/*; do + echo "upload $(basename "$f")" + curl -fsS -X POST -H "$AUTH" -F "attachment=@${f}" "${API}/releases/${ID}/assets?name=$(basename "$f")" >/dev/null + done + shell: bash diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0bcbcdc --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +*.swp +dist/ +.idea/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..da6eabb --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 更新日志 + +## 0.0.1 + +- 「拷贝漫画」书源拆成独立仓库,独立发版、独立更新;原来所有书源同版本一起更新的做法取消。 +- 检查更新与自动更新只管本书源:月读「书库 → 更新」里每个书源各有一项,只提示、不静默安装,装完重启 KOReader。 +- 书源 id、书架、进度、登录配置和缓存沿用原有数据,从旧版覆盖安装即可,无需迁移。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..1fa04ba --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# 月读书源:拷贝漫画 + +给月读增加「拷贝漫画」在线书源的 KOReader 插件。本仓库只含这一个插件,独立维护、独立发版,全部书源见 [moon-source 组织](https://git.garfieldho.me/moon-source)。 + +## 免责声明 + +- 本仓库与「拷贝漫画」官方**没有任何关联**,所有商标、书名、内容归原权利人所有。 +- 插件只是在用户自己的账号、自己的设备上,按用户本人已有的权限读取内容;不提供、不分发任何书籍内容,也不绕过付费。 +- 使用可能违反对应平台的用户协议,账号可能被限制或封禁。是否使用、风险如何,由使用者自行判断并承担。 +- 权利人认为本仓库内容有问题,请通过仓库 issue 联系,核实后会及时处理。 + +## 安装 + +1. 先装好月读。 +2. 从 [Release](../../releases) 下载 `moonsource-copymanga.koplugin-<版本>.zip`,解压出 `moonsource-copymanga.koplugin` 目录,整个复制到 KOReader 的 `plugins/` 下。 +3. 重启 KOReader,在月读的书源列表里启用。 + +书源 id 是 `copymanga`,与旧版(合并仓库、内置书源)相同,书架、进度、登录配置、缓存沿用原有数据,无需迁移。 + +## 更新 + +在月读的「书库 → 拷贝漫画 更新」里有「检查书源插件更新」和「自动检查书源插件更新」(默认开,每 24 小时一次,只提示、不静默安装)。 +本插件只检查并更新自己(本仓库的 Release),校验值取自 Release 的 `SHA256SUMS`,装完重启 KOReader。 + +> 从旧的合并仓库 `GarfieldTony/moon-source` 迁移:旧仓库的更新入口已停用,请直接从本仓库下载最新包覆盖安装。 + +## 发布 + +推送 `vX.Y.Z` 标签(带 `-` 的如 `v1.2.0-rc.1` 为预发布),Forgejo Actions 会打包 `moonsource-copymanga.koplugin-<版本>.zip`,连同 `SHA256SUMS` 上传到 Release。 +更新日志写在 `CHANGELOG.md`,格式是 `## <版本号>` 一节,发布时取对应小节作为 Release 说明(月读的更新弹窗也会显示)。无需配置密钥,默认用内置令牌。本地打包:`tools/package.sh <版本> [输出目录]`。 + +## 测试 + +离线单元测试复用月读仓库的测试运行器(需要 luajit): + +```sh +MOON_DIR=/path/to/moon tools/run-tests.sh # 全部 +MOON_DIR=/path/to/moon tools/run-tests.sh tests/copymanga/xxx_spec.lua +``` + +## 公共文件 + +`<包名>/update.lua`、`tools/package.sh`、`tools/run-tests.sh`、`.github/workflows/release.yml`、`tests/update/update_spec.lua` 由 [moonsource-template](https://git.garfieldho.me/moon-source/moonsource-template) 同步,请改模板仓库,不要在这里手改。 + +## 许可 + +见 [LICENSE](LICENSE)。 diff --git a/moonsource-copymanga.koplugin/_meta.lua b/moonsource-copymanga.koplugin/_meta.lua new file mode 100644 index 0000000..1ef2637 --- /dev/null +++ b/moonsource-copymanga.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:拷贝漫画"), + description = _("给月读增加「拷贝漫画」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-copymanga.koplugin/main.lua b/moonsource-copymanga.koplugin/main.lua new file mode 100644 index 0000000..417046a --- /dev/null +++ b/moonsource-copymanga.koplugin/main.lua @@ -0,0 +1,9 @@ +--[[-- +KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。 +--]] +local WidgetContainer = require("ui/widget/container/widgetcontainer") + +return WidgetContainer:extend{ + name = "moonsource_copymanga", + is_doc_only = false, +} diff --git a/moonsource-copymanga.koplugin/moon_source.lua b/moonsource-copymanga.koplugin/moon_source.lua new file mode 100644 index 0000000..0d5e823 --- /dev/null +++ b/moonsource-copymanga.koplugin/moon_source.lua @@ -0,0 +1,17 @@ +--[[-- +月读第三方书源描述:拷贝漫画。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。 +--]] + +local function lazy(module) + return setmetatable({}, { __index = function(_, key) return require(module)[key] end }) +end + +return { + api = 1, + provides = { + source = true, + }, + meta = function() return require("moonsource_copymanga.source").meta() end, + new = function() return require("moonsource_copymanga.source").new() end, + setting = lazy("moonsource_copymanga.setting"), +} diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/README.md b/moonsource-copymanga.koplugin/moonsource_copymanga/README.md new file mode 100644 index 0000000..338b469 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/README.md @@ -0,0 +1,18 @@ +# 拷贝漫画 + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| API 站点选择 | 支持 | 建议使用已核对的 `https://api.manga2026.xyz`;保留旧站点及自定义地址,不自动切换 | +| 账号密码登录 | 支持 | 原 API 登录,保存前校验账号;新登录不保存密码 | +| Cookie、扫码与验证码登录 | 不支持 | 未接入可验证的 API 契约 | +| 搜索与书城 | 支持 | 搜索、男/女频日周月总榜及题材,默认聚合约 60 本 | +| 详情与分组目录 | 支持 | 分组分页、默认组在前,保留章节 UUID | +| 漫画阅读 | 支持 | 按页图顺序下载 CBZ;使用 App API,不解析官网 HTML | +| 受限与付费漫画 | 未验证 | 没有真实账号权限验证,不承诺受限章节可读 | +| 章节缓存与离线阅读 | 支持 | 复用已缓存 CBZ;未缓存内容离线明确失败 | +| 书架拉取 | 支持 | 分页读取收藏 | +| 书架新增与移出 | 已实现,未实测 | 本地先生效,收藏上行后回读确认 | +| 阅读进度同步 | 部分支持 | 旧 API 保留章节级读写;当前推荐节点未验证写入和回读,只保存本地进度 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 书评、章评、段评与回复 | 不支持 | 未接入可验证接口,不代表其他客户端没有评论 | +| 账号切换 | 部分支持 | 需先退出清理旧数据,未同步记录会丢失;换站点不改变书籍身份和 CBZ 路径 | diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/_meta.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/_meta.lua new file mode 100644 index 0000000..e5d0a83 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +@module moonsource_copymanga._meta +--]] + +local _ = require("l10n").get("moonsource_copymanga") + +return { + id = "copymanga", + name = _("拷贝漫画"), + type = "chapter", + description = _("拷贝漫画在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步") }, +} diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/auth.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/auth.lua new file mode 100644 index 0000000..d4e2083 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/auth.lua @@ -0,0 +1,176 @@ +--[[-- +拷贝漫画账号会话:按所选站点的 API 登录,持久化 Token 与账号密码。 + +密码要落盘:令牌被挤掉(HTTP 401)时 `client` 用本地账号自动重登; +只存 Token 会在过期后只能弹「重新登录」,整书缓存也会跟着挂。 + +登录规则与 kComics / 官方 App 一致: + salt = 6 位随机整数 + password = base64(明文密码 .. "-" .. salt) + POST /api/v3/login (x-www-form-urlencoded) + +@module koplugin.book.moonsource_copymanga.auth +--]] + +local Client = require("moonsource_copymanga.client") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_copymanga") + +local Auth = {} +local SOURCE_ID = "copymanga" + +---@return table +local function cfg() + return require("utils.settings").getSource(SOURCE_ID) +end + +---@param patch table +local function save(patch) + local settings = require("utils.settings") + local current = settings.getSource(SOURCE_ID) + for key, value in pairs(patch) do + current[key] = value + end + settings.saveSource(SOURCE_ID, current) +end + +--- 站点前端同款密码编码。 +---@param password string +---@param salt string|number +---@return string +function Auth.encodePassword(password, salt) + return Text.base64Encode(tostring(password) .. "-" .. tostring(salt)) +end + +---@return string +local function newSalt() + return tostring(math.random(100000, 999999)) +end + +---@return boolean +function Auth.hasSession() + local token = cfg().token + return type(token) == "string" and token ~= "" +end + +---@return string|nil +function Auth.userLabel() + local current = cfg() + if type(current.nickname) == "string" and current.nickname ~= "" then + return current.nickname + end + if type(current.username) == "string" and current.username ~= "" then + return current.username + end + return nil +end + +--- 本地保存的账号密码;缺任一端则没有可自动重登的凭据。 +---@return string|nil, string|nil +function Auth.credentials() + local current = cfg() + local username = current.username + local password = current.password + if type(username) == "string" and username ~= "" + and type(password) == "string" and password ~= "" + then + return username, password + end + return nil +end + +--- 清除登录态,保留站点地址。 +function Auth.clearSession() + save({ + token = "", + user_id = "", + username = "", + nickname = "", + password = "", + }) +end + +--- 账号密码登录;成功后写入 token / 用户信息。 +---@param username string +---@param password string +---@param cb fun(ok: boolean|nil, err: string|nil, rejected: boolean|nil) rejected = 服务端拒绝(非网络错误) +---@return { cancel: fun() } +function Auth.loginAsync(username, password, cb) + username = Text.stripWhitespace(username) + password = tostring(password or "") + if username == "" or password == "" then + return require("source.base").defer(cb, nil, _("请输入账号和密码")) + end + + local current = cfg() + local base_url = Client.normalizeBaseUrl(current.base_url) + local old_token, old_user_id = current.token, current.user_id + local cancelled = false + local salt = newSalt() + local body = Text.formEncode({ + username = username, + password = Auth.encodePassword(password, salt), + salt = salt, + }) + local headers = Client.headers() + headers["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8" + + local request = require("http.request").request({ + url = base_url .. "/api/v3/login", + method = "POST", + body = body, + headers = headers, + cache_ttl = 0, + allow_redirects = false, + timeout = require("http.timeout").net(1), + connect_timeout = require("http.timeout").net(1), + }, function(res, err) + if cancelled then return end + local wire, decode_err = Client.decode(res and res.body, err) + if not wire then + -- 第三个参数:服务端回了包并拒绝(密码错 / 风控),区别于网络错误。 + cb(nil, decode_err, err == nil and res ~= nil) + return + end + local results = type(wire.results) == "table" and wire.results or {} + local token = results.token + if type(token) ~= "string" or token == "" then + cb(nil, _("登录失败:未返回令牌"), true) + return + end + if cfg().token ~= old_token or Client.normalizeBaseUrl(cfg().base_url) ~= base_url then + cb(nil, _("登录状态已改变,请重试")) + return + end + local user_id = tostring(results.user_id or "") + if user_id == "" then + cb(nil, _("登录失败:未返回账号标识"), true) + return + end + local function commit() + save({ + token = token, + user_id = user_id, + username = tostring(results.username or username), + nickname = tostring(results.nickname or results.username or username), + -- 明文密码供 401 自动重登(#42);退出登录时 clearSession 清掉。 + password = password, + }) + end + if old_user_id ~= user_id then + if not require("source.logout").replaceLibrary(SOURCE_ID, commit) then + cb(nil, _("准备本地同步失败")) + return + end + else + commit() + end + cb(true) + end) + return { cancel = function() + cancelled = true + request.cancel() + end } +end + +return Auth diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/chapter.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/chapter.lua new file mode 100644 index 0000000..4795e5d --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/chapter.lua @@ -0,0 +1,169 @@ +--[[-- +拷贝漫画章节图片下载与 CBZ 打包。 + +@module koplugin.book.moonsource_copymanga.chapter +--]] + +local Cbz = require("source.cbz") +local Image = require("utils.image") +local Paths = require("utils.paths") +local Protocol = require("moonsource_copymanga.protocol") +local _ = require("l10n").get("moonsource_copymanga") + +local Chapter = {} + +--- 章节 CBZ 路径。按章节 uuid 命名:多分组漫画更新后连续章序号会整体后移,按序号命名会串章。 +---@param identity BookIdentity +---@param chapter BookChapter +---@return string +function Chapter.archivePath(identity, chapter) + return Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/" .. chapter.uid .. ".cbz" +end + +--- 已下载好的章节 CBZ;没有则 nil。 +---@param identity BookIdentity +---@param chapter BookChapter +---@return string|nil +function Chapter.existing(identity, chapter) + local path = Chapter.archivePath(identity, chapter) + return Cbz.ready(path) and path or nil +end + +--- 下载并打包一个漫画章节;已有 CBZ 直接复用。 +---@param client CopymangaClient +---@param identity BookIdentity +---@param chapter BookChapter +---@param on_progress fun(done: integer, total: integer)|nil +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Chapter.materializeAsync(client, identity, chapter, on_progress, cb) + Paths.ensureBookWork(identity.stable_id, identity.source_id) + local archive_path = Chapter.archivePath(identity, chapter) + ---@type { cancelled: boolean, active: CancelHandle|nil, writer: ArchiverWriter|nil } + local state = { cancelled = false, active = nil, writer = nil } + if Cbz.ready(archive_path) then + require("ui/uimanager"):nextTick(require("ui.guard").wrap("copymanga callback", function() + if not state.cancelled then cb(archive_path) end + end)) + return { cancel = function() state.cancelled = true end } + end + + state.active = client:chapterAsync(identity.stable_id, chapter.uid, function(wire, err) + state.active = nil + if state.cancelled then return end + if not wire then cb(nil, err); return end + local urls, decode_err = Protocol.chapterImages(wire) + if not urls then cb(nil, decode_err); return end + + local image_dir = archive_path:gsub("%.cbz$", "") + Paths.ensureDir(image_dir) + local paths, current = {}, 1 + for i, url in ipairs(urls) do + paths[i] = image_dir .. "/" .. string.format("%04d%s", i, Image.suffix(url) or ".jpg") + end + + local function nextImage() + if state.cancelled then return end + local url = urls[current] + if not url then + Cbz.build(paths, archive_path, state, cb) + 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("copymanga image", nextImage)) + return + end + local mine = current + local handle = require("http.request").download({ + url = url, + headers = { ["Referer"] = client.base_url .. "/" }, + timeout = require("http.timeout").net(3), + max_bytes = 32 * 1024 * 1024, + }, path, function(ok, download_err) + 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 or _("漫画图片下载失败")) + return + end + if on_progress then on_progress(current, #urls) end + current = current + 1 + nextImage() + end) + -- 回调同步触发时已发出下一个请求,不能用旧句柄覆盖它(同 http/github)。 + if current == mine then state.active = handle end + end + nextImage() + end) + + return { cancel = function() + if state.cancelled then return end + state.cancelled = true + if state.active then state.active.cancel() end + if state.writer then state.writer:close() end + os.remove(archive_path .. ".part") + end } +end + +--- 后台预取章节 CBZ;已有文件由 materializeAsync 直接复用。 +--- 单章失败不阻断后续。不 touch 书架路径,避免阅读中改掉当前章登记。 +---@param client CopymangaClient +---@param identity BookIdentity +---@param toc BookChapter[] +---@param from_idx integer 当前章序号(预取 from_idx+1 …);0 表示从第一章开始 +---@param count integer +---@param ops { progress: fun(done: integer, total: integer)|nil, interval_seconds: number|nil }|nil +---@param cb fun(cached: integer, total: integer, failed: integer, err: any)|nil +---@return { cancel: fun() } +function Chapter.prefetchAsync(client, identity, toc, from_idx, count, ops, cb) + ops = ops or {} + local cancelled, active = false, nil + local cached_count, failed_count, last_error = 0, 0, nil + local chapters = {} + for idx = from_idx + 1, math.min(#toc, from_idx + count) do + chapters[#chapters + 1] = toc[idx] + end + + local pos = 1 + local interval = ops.interval_seconds or 0 + local UIManager = require("ui/uimanager") + local function step() + if cancelled then return end + local chapter = chapters[pos] + pos = pos + 1 + if not chapter then + if cb then cb(cached_count, #chapters, failed_count, last_error) end + return + end + active = Chapter.materializeAsync(client, identity, chapter, nil, function(path, err) + active = nil + if cancelled then return end + if path then + cached_count = cached_count + 1 + else + failed_count = failed_count + 1 + last_error = err or last_error + end + if ops.progress then + ops.progress(cached_count + failed_count, #chapters) + end + if interval > 0 then + UIManager:scheduleIn(interval, require("ui.guard").wrap("copymanga step", step)) + else + UIManager:nextTick(require("ui.guard").wrap("copymanga step", step)) + end + end) + end + + UIManager:nextTick(require("ui.guard").wrap("copymanga step", step)) + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +return Chapter diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/client.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/client.lua new file mode 100644 index 0000000..bf328ef --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/client.lua @@ -0,0 +1,435 @@ +--[[-- +拷贝漫画 App API 客户端。 + +协议对齐 kComics:``COPY/3.0.0`` + ``/api/v3/*``,返回 JSON wire。 + +@module koplugin.book.moonsource_copymanga.client +--]] + +local JSON = require("json") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_copymanga") +local Auth = require("source.auth") + +---@class CopymangaClient +---@field base_url string +---@field token string +---@field progress_supported boolean +local Client = {} +Client.__index = Client + +local DEFAULT_BASE_URL = "https://api.copy202601.com" + +Client.DEFAULT_BASE_URL = DEFAULT_BASE_URL +Client.CURRENT_BASE_URL = "https://api.manga2026.xyz" +Client.SITES = { "https://www.mangacopy.com", "https://www.copy4000.com", Client.CURRENT_BASE_URL } +local SITE_APIS = { + ["https://www.mangacopy.com"] = "https://api.mangacopy.com", + ["https://www.copy4000.com"] = "https://api.copy4000.com", +} + +---@return string +function Client.normalizeBaseUrl(url) + url = Text.rtrimSlashes(Text.stripWhitespace(url)) + if url == "" then + return DEFAULT_BASE_URL + end + return SITE_APIS[url] or url +end + +--- App 请求头。登录与章节接口都靠这组字段识别客户端。 +---@param token string|nil +---@return table +function Client.headers(token) + local headers = { + ["User-Agent"] = "COPY/3.0.0", + ["version"] = "2025.08.15", + ["platform"] = "1", + ["webp"] = "1", + ["region"] = "1", + } + if type(token) == "string" and token ~= "" then + headers["Authorization"] = "Token " .. token + end + return headers +end + +---@param cfg { base_url: string|nil, token: string|nil } +---@return CopymangaClient +function Client:new(cfg) + local base_url = Client.normalizeBaseUrl(cfg.base_url) + return setmetatable({ + base_url = base_url, + token = cfg.token or "", + progress_supported = base_url ~= Client.CURRENT_BASE_URL, + }, self) +end + +---@return boolean +function Client:configured() + return self.base_url:match("^https?://[^/]+$") ~= nil +end + +--- code 200 才算成功;拒绝请求时保留服务端原因,不据 210 推断用户账号状态。 +---@param raw string|nil +---@param err string|nil +---@return table|nil, string|nil +function Client.decode(raw, err) + if not raw then return nil, err end + local ok, wire = pcall(JSON.decode, raw) + if not ok or type(wire) ~= "table" then + return nil, _("响应无效") + end + local code = tonumber(wire.code) + if code ~= 200 then + if type(wire.message) == "string" and wire.message ~= "" then + return nil, wire.message + end + return nil, code == 210 and _("拷贝漫画 API 拒绝请求(210),请按官网提示处理") or _("请求失败") + end + return wire +end + +--- 进行中的自动重登:等待者回调列表;nil = 空闲。全进程只发一次登录,免得并发 401 各自登录、互相挤掉令牌。 +---@type fun(ok: boolean|nil, err: string|nil, rejected: boolean|nil)[]|nil +local relogin_waiters + +--- 用本地保存的账号密码重登(单飞)。没存密码时立即 cb(nil, nil, true)。 +--- 不随单个请求取消:登录结果要分给所有等待者。 +---@param cb fun(ok: boolean|nil, err: string|nil, rejected: boolean|nil) +local function relogin(cb) + if relogin_waiters then + relogin_waiters[#relogin_waiters + 1] = cb + return + end + local Auth = require("moonsource_copymanga.auth") + local username, password = Auth.credentials() + if not username then + cb(nil, nil, true) + return + end + relogin_waiters = { cb } + Auth.loginAsync(username, password, function(ok, err, rejected) + local waiters = relogin_waiters or {} + relogin_waiters = nil + for _idx, waiter in ipairs(waiters) do waiter(ok, err, rejected) end + end) +end + +--- 只使用当前站点的最新令牌,退出或切站后不复用旧实例的登录态。 +---@return string +function Client:_latestToken() + local cfg = require("utils.settings").getSource("copymanga") + if Client.normalizeBaseUrl(cfg.base_url) ~= self.base_url then return "" end + self.token = type(cfg.token) == "string" and cfg.token or "" + return self.token +end + +--- GET JSON。令牌失效(HTTP 401,如在别处登录后被挤掉)时用本地保存的账号密码重登一次再重试。 +--- 别的请求已经换过令牌时直接用新令牌重试,不再登录。重登被服务端拒绝才提示重新登录,网络错误原样回传。 +---@param path string +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:_getJson(path, cb, public) + local expired = _("点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → 拷贝漫画 → 拷贝漫画账号」。账号和密码重新填一遍,点「登录」。") + local active, cancelled + local function send(may_relogin) + local sent = public and "" or self:_latestToken() + local pending = true + local handle = require("http.request").get(self.base_url .. path, { + accept = "application/json", + headers = Client.headers(sent), + allow_redirects = public == true, + timeout = require("http.timeout").net(2), + connect_timeout = require("http.timeout").net(1), + }, function(raw, err, res) + pending = false + if cancelled then return end + if not (res and res.code == 401) then + cb(Client.decode(raw, err)) + return + end + if not may_relogin then + cb(nil, Auth.expire("copymanga", expired)) + return + end + if self:_latestToken() ~= sent then + send(false) + return + end + active = nil + relogin(function(ok, login_err, rejected) + if cancelled then return end + if ok then Auth.ok("copymanga"); send(false); return end + cb(nil, rejected and Auth.expire("copymanga", expired) or (login_err or _("请求失败"))) + end) + end) + if pending then active = handle end + end + send(true) + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +---@param stable_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:detailAsync(stable_id, cb) + return self:_getJson("/api/v3/comic2/" .. Text.urlEncode(stable_id) .. "?platform=1", cb, true) +end + +---@param keyword string +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:searchAsync(keyword, cb) + return self:_getJson("/api/v3/search/comic?limit=30&offset=0&platform=1&q_type=&q=" .. Text.urlEncode(keyword), cb, true) +end + +--- 排行榜一页(20 部)。audience 为 male / female,nil 是全部;date_type 1 日 2 周 3 月 4 总。 +---@param date_type string +---@param audience string|nil +---@param offset integer +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:rankAsync(date_type, audience, offset, cb) + local path = "/api/v3/ranks?limit=20&type=1&platform=1&offset=" .. offset .. "&date_type=" .. date_type + if audience then path = path .. "&audience_type=" .. audience end + return self:_getJson(path, cb, true) +end + +--- 分类列表一页(20 部),按人气。 +---@param theme string +---@param offset integer +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:themeAsync(theme, offset, cb) + return self:_getJson("/api/v3/comics?limit=20&free_type=1&ordering=-popular&offset=" .. offset + .. "&theme=" .. Text.urlEncode(theme), cb, true) +end + +--- 云端浏览记录(需登录)。browse 为 null 表示从未读过。 +---@param stable_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:getProgressAsync(stable_id, cb) + return self:_getJson( + "/api/v3/comic2/" .. Text.urlEncode(stable_id) .. "/query?platform=1", + cb + ) +end + +--- 按分组分页拉全量章节行(uuid / name / group_*)。 +---@param stable_id string +---@param groups { path_word: string, name: string }[] 见 Mapper.groups(至少有默认组) +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client:chaptersAsync(stable_id, groups, cb) + local cancelled, active = false, nil + local rows, gi = {}, 1 + local offset, limit = 0, 100 + + local function step() + if cancelled then return end + local group = groups[gi] + if not group then + cb(rows) + return + end + local path = "/api/v3/comic/" .. Text.urlEncode(stable_id) + .. "/group/" .. Text.urlEncode(group.path_word) + .. "/chapters?limit=" .. limit .. "&offset=" .. offset .. "&platform=1" + local pending = true + local handle = self:_getJson(path, function(wire, err) + pending = false + active = nil + if cancelled then return end + if not wire then cb(nil, err); return end + local list, parse_err = require("moonsource_copymanga.mapper").list(wire, offset) + if not list then cb(nil, parse_err); return end + local root = wire.results + for _idx, row in ipairs(list) do + if type(row) == "table" and type(row.uuid) == "string" and row.uuid ~= "" then + rows[#rows + 1] = { + uuid = row.uuid, + name = row.name, + group_path = group.path_word, + group_name = group.name, + } + end + end + local total = tonumber(root.total) or 0 + offset = offset + #list + if #list == 0 or offset >= total then + gi = gi + 1 + offset = 0 + end + step() + end, true) + if pending then active = handle end + end + + step() + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +---@param stable_id string +---@param chapter_uid string +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:chapterAsync(stable_id, chapter_uid, cb) + local endpoint = self.base_url == Client.CURRENT_BASE_URL and "/chapter/" or "/chapter2/" + local path = "/api/v3/comic/" .. Text.urlEncode(stable_id) + .. endpoint .. Text.urlEncode(chapter_uid) .. "?platform=1" + return self:_getJson(path, cb) +end + +--- 收藏或取消收藏(需登录)。comic_id 是 comic2 返回的 uuid,不是 path_word。 +---@param comic_id string +---@param collect boolean +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:setCollectAsync(comic_id, collect, cb) + -- 自动重登后新 token 只写进设置,这里先取最新的,免得拿旧 token 收藏失败。 + if self:_latestToken() == "" then + return require("source.base").defer(cb, nil, _("请先登录拷贝漫画账号")) + end + local body = Text.formEncode({ + comic_id = comic_id, + is_collect = collect and "1" or "0", + authorization = "Token " .. self.token, + }) + return require("http.request").post( + self.base_url .. "/api/v3/member/collect/comic", + body, + { + accept = "application/json", + headers = Client.headers(self.token), + content_type = "application/x-www-form-urlencoded;charset=utf-8", + allow_redirects = false, + cache_ttl = 0, + timeout = require("http.timeout").net(1), + connect_timeout = require("http.timeout").net(1), + }, + function(raw, err) + cb(Client.decode(raw, err)) + end + ) +end + +-- 收藏列表每页条数(接口上限 50)。 +local COLLECT_PAGE = 50 + +--- 分页拉全量收藏(需登录),回调收藏行数组(每行 ``{ comic = {...} }``)。 +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client:collectAllAsync(cb) + if self:_latestToken() == "" then + return require("source.base").defer(cb, nil, _("请先登录拷贝漫画账号")) + end + local cancelled, rows, offset = false, {}, 0 + ---@type { cancel: fun() } + local active + + local function step() + local pending = true + local handle = self:_getJson("/api/v3/member/collect/comics?free_type=1&limit=" .. COLLECT_PAGE + .. "&offset=" .. offset .. "&ordering=-datetime_updated", function(wire, err) + pending = false + if cancelled then return end + if not wire then cb(nil, err); return end + local list, parse_err = require("moonsource_copymanga.mapper").list(wire, offset) + if not list then cb(nil, parse_err); return end + local root = wire.results + for _idx, row in ipairs(list) do + rows[#rows + 1] = row + end + offset = offset + #list + if #list == 0 or offset >= (tonumber(root.total) or 0) then + cb(rows) + return + end + step() + end) + if pending then active = handle end + end + + step() + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +---@param cb fun(books: Book[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client:shelfSyncAsync(cb) + return self:collectAllAsync(function(rows, err) + if not rows then cb(nil, err); return end + cb(require("moonsource_copymanga.mapper").collect(rows)) + end) +end + +---@param client CopymangaClient +---@param stable_id string +---@param collect boolean +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +local function changeCollect(client, stable_id, collect, cb) + local cancelled, active, pending = false, nil, true + local detail = client:detailAsync(stable_id, function(wire, err) + pending = false + if cancelled then return end + local comic_id = wire and require("moonsource_copymanga.mapper").comicId(wire) + if not comic_id then cb(nil, err or _("漫画详情解析失败")); return end + local writing = true + local write = client:setCollectAsync(comic_id, collect, function(result, write_err) + writing = false + if cancelled then return end + if not result then cb(nil, write_err); return end + local reading = true + local readback = client:collectAllAsync(function(rows, read_err) + reading = false + if cancelled then return end + if not rows then cb(nil, read_err); return end + local found = false + for _idx, row in ipairs(rows) do + local comic = type(row) == "table" and row.comic + if type(comic) ~= "table" or type(comic.uuid) ~= "string" or comic.uuid == "" then + cb(nil, _("响应无效")); return + end + if comic.uuid == comic_id then found = true end + end + if found ~= collect then cb(nil, _("书架同步未确认")); return end + cb(result) + end) + if reading then active = readback end + end) + if writing then active = write end + end) + if pending then active = detail end + return { cancel = function() + cancelled = true + if active then active.cancel() end + end } +end + +---@param stable_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:addToShelfAsync(stable_id, cb) + return changeCollect(self, stable_id, true, cb) +end + +---@param stable_id string +---@param cb fun(wire: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client:removeFromShelfAsync(stable_id, cb) + return changeCollect(self, stable_id, false, cb) +end + +return Client diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/l10n/en.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/l10n/en.lua new file mode 100644 index 0000000..a0f6e44 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/l10n/en.lua @@ -0,0 +1,52 @@ +return { + ["百合"] = "Girls' love", + ["热血"] = "Hot-blooded", + ["搞笑"] = "Comedy", + ["战争"] = "War", + ["穿越"] = "Time travel", + ["治愈"] = "Heartwarming", + ["惊悚"] = "Thriller", + ["校园"] = "School life", + ["重生"] = "Rebirth", + ["恐怖"] = "Horror", + ["确定退出拷贝漫画账号?"] = "Sign out of CopyManga?", + ["拷贝漫画账号"] = "CopyManga account", + ["正在准备漫画…"] = "Preparing comic…", + ["正在登录…"] = "Signing in…", + ["漫画图片下载失败"] = "Failed to download comic image", + ["漫画目录为空"] = "Comic chapter list is empty", + ["漫画目录保存失败"] = "Failed to save comic chapter list", + ["漫画详情解析失败"] = "Failed to parse comic details", + ["登录失败:未返回令牌"] = "Sign-in failed: no token returned", + ["章节图片解析失败"] = "Failed to parse chapter images", + ["缺少章节信息"] = "Missing chapter info", + ["站点地址无效"] = "Invalid site address", + ["登录状态已改变,请重试"] = "Sign-in state changed. Please try again", + ["请先退出当前账号"] = "Sign out of the current account first", + ["登录失败:未返回账号标识"] = "Sign-in failed: no account ID returned", + ["书架同步未确认"] = "Bookshelf synchronization could not be confirmed", + ["请先登录拷贝漫画账号"] = "Sign in to CopyManga first", + ["点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → 拷贝漫画 → 拷贝漫画账号」。账号和密码重新填一遍,点「登录」。"] = "Tap Sign in again on this message. If there is no button, open Settings → Library → Account → CopyManga → CopyManga account. Enter the username and password again, then tap Sign in.", + ["请输入账号和密码"] = "Enter account and password", + ["拷贝漫画 API 拒绝请求(210),请按官网提示处理"] = "CopyManga API rejected the request (210). Follow the official site's instructions.", + ["励志"] = "Self-improvement", + ["美食"] = "Food", + ["仙侠"] = "Xianxia", + ["历史"] = "History", + ["周榜"] = "Weekly", + ["奇幻"] = "Fantasy", + ["女频"] = "Female", + ["总榜"] = "All-time", + ["悬疑"] = "Mystery", + ["日榜"] = "Daily", + ["月榜"] = "Monthly", + ["武侠"] = "Wuxia", + ["男频"] = "Male", + ["科幻"] = "Sci-Fi", + ["轻小说"] = "Light Novels", + ["都市"] = "Urban", + ["书架同步"] = "Shelf sync", + ["拷贝漫画在线阅读"] = "Copymanga online reading", + ["搜索与发现"] = "Search and discover", + ["进度同步"] = "Progress sync", +} diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/l10n/zh_TW.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/l10n/zh_TW.lua new file mode 100644 index 0000000..d84e943 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/l10n/zh_TW.lua @@ -0,0 +1,52 @@ +return { + ["百合"] = "百合", + ["热血"] = "熱血", + ["搞笑"] = "搞笑", + ["战争"] = "戰爭", + ["穿越"] = "穿越", + ["治愈"] = "療癒", + ["惊悚"] = "驚悚", + ["校园"] = "校園", + ["重生"] = "重生", + ["恐怖"] = "恐怖", + ["确定退出拷贝漫画账号?"] = "確定登出拷貝漫畫帳號?", + ["拷贝漫画账号"] = "拷貝漫畫帳號", + ["正在准备漫画…"] = "正在準備漫畫…", + ["正在登录…"] = "正在登入…", + ["漫画图片下载失败"] = "漫畫圖片下載失敗", + ["漫画目录为空"] = "漫畫目錄為空", + ["漫画目录保存失败"] = "漫畫目錄儲存失敗", + ["漫画详情解析失败"] = "漫畫詳情解析失敗", + ["登录失败:未返回令牌"] = "登入失敗:未返回權杖", + ["章节图片解析失败"] = "章節圖片解析失敗", + ["缺少章节信息"] = "缺少章節資訊", + ["站点地址无效"] = "站點地址無效", + ["登录状态已改变,请重试"] = "登入狀態已改變,請重試", + ["请先退出当前账号"] = "請先登出目前帳號", + ["登录失败:未返回账号标识"] = "登入失敗:未回傳帳號識別碼", + ["书架同步未确认"] = "書架同步未確認", + ["请先登录拷贝漫画账号"] = "請先登入拷貝漫畫帳號", + ["点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → 拷贝漫画 → 拷贝漫画账号」。账号和密码重新填一遍,点「登录」。"] = "點這個提示上的「重新登入」。沒有按鈕就打開「設定 → 書庫 → 帳號 → 拷貝漫畫 → 拷貝漫畫帳號」。帳號和密碼重新填一遍,點「登入」。", + ["请输入账号和密码"] = "請輸入帳號和密碼", + ["拷贝漫画 API 拒绝请求(210),请按官网提示处理"] = "拷貝漫畫 API 拒絕請求(210),請按官網提示處理", + ["励志"] = "勵志", + ["美食"] = "美食", + ["仙侠"] = "仙俠", + ["历史"] = "歷史", + ["周榜"] = "週榜", + ["奇幻"] = "奇幻", + ["女频"] = "女頻", + ["总榜"] = "總榜", + ["悬疑"] = "懸疑", + ["日榜"] = "日榜", + ["月榜"] = "月榜", + ["武侠"] = "武俠", + ["男频"] = "男頻", + ["科幻"] = "科幻", + ["轻小说"] = "輕小說", + ["都市"] = "都市", + ["书架同步"] = "書架同步", + ["拷贝漫画在线阅读"] = "拷貝漫畫線上閱讀", + ["搜索与发现"] = "搜尋與發現", + ["进度同步"] = "進度同步", +} diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/loadmeta.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/loadmeta.lua new file mode 100644 index 0000000..5640e34 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_copymanga._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/mapper.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/mapper.lua new file mode 100644 index 0000000..c7a883c --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/mapper.lua @@ -0,0 +1,193 @@ +--[[-- +拷贝漫画 App API 数据映射。 + +@module koplugin.book.moonsource_copymanga.mapper +--]] + +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_copymanga") + +local Mapper = {} +local SOURCE_ID = "copymanga" + +---@param wire table +---@param offset integer|nil +---@return table[]|nil, string|nil, boolean|nil +function Mapper.list(wire, offset) + local root = wire.results + if type(root) ~= "table" or type(root.list) ~= "table" then return nil, _("响应无效") end + local total = tonumber(root.total) + offset = offset or tonumber(root.offset) or 0 + if total and #root.list == 0 and offset < total then return nil, _("响应无效") end + return root.list, nil, total and offset + #root.list < total or (not total and #root.list > 0) +end + +---@param rows table[]|nil +---@return string|nil +local function names(rows) + local list = {} + for _idx, row in ipairs(rows or {}) do + if type(row) == "table" and type(row.name) == "string" and row.name ~= "" then + list[#list + 1] = row.name + end + end + return #list > 0 and table.concat(list, ", ") or nil +end + +--- 回包的 results 表;wire 或 results 不是表时给空表。 +---@param wire table|nil +---@return table +local function resultsOf(wire) + local results = type(wire) == "table" and wire.results + return type(results) == "table" and results or {} +end + +---@param row table|nil +---@return table|nil +local function comicOf(row) + if type(row) ~= "table" then return nil end + if type(row.comic) == "table" then return row.comic end + return row +end + +---@param row table|nil +---@return Book|nil +function Mapper.book(row) + row = comicOf(row) + if type(row) ~= "table" or type(row.path_word) ~= "string" or row.path_word == "" then + return nil + end + local intro = row.intro or row.brief + return { + source_id = SOURCE_ID, + stable_id = row.path_word, + title = row.name, + authors = names(row.author), + category = row.category or names(row.theme), + intro = intro and Text.stripHtml(intro), + cover = row.cover, + percent = tonumber(row.percent) or 0, + deleted = (row.deleted == true or tonumber(row.deleted) == 1) and 1 or nil, + } +end + +--- 搜索 wire → Book[]。 +---@param wire table +---@return Book[]|nil, string|nil, boolean|nil +function Mapper.search(wire) + local rows, err, more = Mapper.list(wire) + if not rows then return nil, err end + local out = {} + for _idx, row in ipairs(rows) do + local book = Mapper.book(row) + if not book then return nil, _("响应无效") end + out[#out + 1] = book + end + return out, nil, more +end + +--- 收藏行(见 Client:collectAllAsync)→ 在架书。 +---@param rows table[] +---@return Book[]|nil, string|nil +function Mapper.collect(rows) + local books = {} + for _idx, row in ipairs(rows) do + local book = Mapper.book(row) + if not book then return nil, _("响应无效") end + book.deleted = 0 + books[#books + 1] = book + end + return books +end + +--- comic2 JSON → 书籍元数据。 +---@param wire table +---@return Book|nil +function Mapper.detail(wire) + return Mapper.book(resultsOf(wire).comic) +end + +--- comic2 JSON → 云端收藏用的漫画 uuid。 +---@param wire table|nil +---@return string|nil +function Mapper.comicId(wire) + local comic = resultsOf(wire).comic + local uuid = type(comic) == "table" and comic.uuid or nil + if type(uuid) == "string" and uuid ~= "" then return uuid end + return nil +end + +--- comic2.groups → 默认组在前的分组列表。 +---@param wire table|nil +---@return { path_word: string, name: string }[] +function Mapper.groups(wire) + local raw = resultsOf(wire).groups + local list = {} + if type(raw) == "table" then + for _group_key, group in pairs(raw) do + if type(group) == "table" + and type(group.path_word) == "string" + and group.path_word ~= "" + then + list[#list + 1] = { + path_word = group.path_word, + name = type(group.name) == "string" and group.name ~= "" + and group.name or group.path_word, + } + end + end + table.sort(list, function(a, b) + if a.path_word == "default" then return true end + if b.path_word == "default" then return false end + return a.path_word < b.path_word + end) + end + if #list == 0 then + return { { path_word = "default", name = "默认" } } + end + return list +end + +--- 分组章节行 → 连续目录;非默认组加组名前缀。 +---@param rows table[]|nil +---@return BookChapter[]|nil +function Mapper.chapters(rows) + local chapters, seen = {}, {} + for _idx, row in ipairs(rows or {}) do + local uid = type(row) == "table" and row.uuid or nil + if type(uid) == "string" and uid ~= "" and not seen[uid] then + seen[uid] = true + local title = tostring(row.name or uid) + if row.group_path and row.group_path ~= "default" + and type(row.group_name) == "string" and row.group_name ~= "" + then + title = row.group_name .. " · " .. title + end + chapters[#chapters + 1] = { + idx = #chapters + 1, + uid = uid, + title = title, + depth = 1, + } + end + end + return #chapters > 0 and chapters or nil +end + +--- comic2/query wire → 占位进度 + 章节 uuid。browse 为 null 表示从未读过。 +--- 云端只有章粒度,fraction 由门面按目录换算。 +---@param wire table|nil +---@return ProgressPosition|nil, string|nil +function Mapper.progress(wire) + local browse = resultsOf(wire).browse + if type(browse) ~= "table" then return nil end + local uid = browse.chapter_uuid or browse.chapter_id + if type(uid) ~= "string" or uid == "" then return nil end + local title = browse.chapter_name + return { + fraction = 0, + chapter_title = type(title) == "string" and title ~= "" and title or nil, + }, uid +end + +return Mapper diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/protocol.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/protocol.lua new file mode 100644 index 0000000..9433558 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/protocol.lua @@ -0,0 +1,64 @@ +--[[-- +拷贝漫画 App 章节载荷。 + +chapter2 返回 ``contents``(图片 URL)和 ``words``(阅读序号)。 +图床把宽度写在文件名里(``.c800x.`` / ``.c1500x.``)。手机端要 1500 宽 webp, +墨水屏翻页会整页解码,长图会卡。这里固定要 800 宽 JPEG。没有档位的地址不动。 + +@module koplugin.book.moonsource_copymanga.protocol +--]] + +local _ = require("l10n").get("moonsource_copymanga") + +local Protocol = {} + +---@param wire table|nil +---@return table|nil +local function chapterRoot(wire) + if type(wire) ~= "table" then return nil end + if type(wire.chapter) == "table" then return wire.chapter end + local results = wire.results + if type(results) == "table" and type(results.chapter) == "table" then + return results.chapter + end + if type(wire.contents) == "table" then return wire end + return nil +end + +--- 图床档位改成 800 宽 JPEG。``.webp.c1500x.webp`` 与 ``.c800x.webp`` 两种写法都认。 +---@param url string +---@return string +local function screenUrl(url) + local rewritten = url:gsub("%.webp(%.c%d+x%.)webp", ".jpg%1jpg", 1) + rewritten = rewritten:gsub("%.c%d+x%.webp", ".c800x.jpg") + return (rewritten:gsub("%.c%d+x%.jpe?g", ".c800x.jpg")) +end + +--- 解码章节页,返回按 ``words`` 排序的图片 URL。 +---@param wire table|nil +---@return string[]|nil, string|nil +function Protocol.chapterImages(wire) + local chapter = chapterRoot(wire) + local contents = chapter and chapter.contents + if type(contents) ~= "table" then return nil, _("章节图片解析失败") end + local words = type(chapter.words) == "table" and chapter.words or {} + local pages = {} + for i, row in ipairs(contents) do + local url = type(row) == "table" and row.url or nil + if type(url) == "string" and url:match("^https?://") then + pages[#pages + 1] = { + url = screenUrl(url), + order = tonumber(words[i]) or (i - 1), + } + end + end + table.sort(pages, function(a, b) return a.order < b.order end) + local images = {} + for _idx, page in ipairs(pages) do + images[#images + 1] = page.url + end + if #images == 0 then return nil, _("章节图片解析失败") end + return images +end + +return Protocol diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/setting.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/setting.lua new file mode 100644 index 0000000..ab394a2 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/setting.lua @@ -0,0 +1,156 @@ +--[[-- +拷贝漫画源设置。 + +@module koplugin.book.moonsource_copymanga.setting +--]] + +local Client = require("moonsource_copymanga.client") +local _ = require("l10n").get("moonsource_copymanga") + +local SOURCE_ID = "copymanga" +local Setting = {} +local editBaseUrl + +local function selectBaseUrl() + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + local current = Client.normalizeBaseUrl(cfg.base_url) + local items = {} + for _idx, url in ipairs(Client.SITES) do + items[#items + 1] = { + text = url, + variant = Client.normalizeBaseUrl(url) == current and "primary" or "normal", + callback = function() + cfg.base_url = url + settings.saveSource(SOURCE_ID, cfg) + require("source.registry").reload() + end, + } + end + items[#items + 1] = { + text = _("自定义"), + callback = function() editBaseUrl() end, + } + require("ui.themes.widgets.sheet"):new{ title = _("站点地址"), items = items }:show() +end + +editBaseUrl = function() + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + require("ui.themes.widgets.input"):new{ + title = _("站点地址"), + fields = { { text = Client.normalizeBaseUrl(cfg.base_url), hint = Client.DEFAULT_BASE_URL } }, + ok_text = _("保存"), + callback = function(value) + local url = Client.normalizeBaseUrl(value) + if not url:match("^https?://[^/%s?#]+$") then + require("ui.themes.widgets.toast"):new{ text = _("站点地址无效"), timeout = 3 }:show() + return + end + cfg.base_url = url + settings.saveSource(SOURCE_ID, cfg) + require("source.registry").reload() + end, + }:show() +end + +---@param username string +---@param password string +local function doLogin(username, password) + local Auth = require("moonsource_copymanga.auth") + local NetworkMgr = require("ui/network/manager") + local Toast = require("ui.themes.widgets.toast") + if not NetworkMgr:isConnected() then + Toast:new{ text = _("网络不可用,请先连接 Wi-Fi"), timeout = 3 }:show() + return + end + local job + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("拷贝漫画账号"), text = _("正在登录…"), dismissable = false, + on_cancel = function() if job then job.cancel() end end, + } + job = waiting:showWhile(Auth.loginAsync, username, password, function(ok, err) + waiting:close() + if not ok then + Toast:new{ text = err or _("登录失败"), timeout = 3 }:show() + return + end + Toast:new{ text = _("登录成功"), timeout = 2 }:show() + require("source.registry").reload() + end) +end + +local function showLogin() + local Auth = require("moonsource_copymanga.auth") + local username, password = Auth.credentials() + if not username then + local cfg = require("utils.settings").getSource(SOURCE_ID) + username = tostring(cfg.username or "") + password = "" + end + require("ui.themes.widgets.input"):new{ + title = _("拷贝漫画账号"), + fields = { + { text = username, hint = _("账号") }, + { text = password, hint = _("密码"), text_type = "password" }, + }, + ok_text = _("登录"), + callback = function(user, pass) doLogin(user, pass) end, + }:show() +end + +---@return table[] +function Setting.rows() + local Auth = require("moonsource_copymanga.auth") + local rows = { + function(iw) + local cfg = require("utils.settings").getSource(SOURCE_ID) + return require("ui.themes.widgets.row").widget({ + width = iw, + chevron = true, + kind = "nav", + icon = "dns", + title = _("站点地址"), + status = Client.normalizeBaseUrl(cfg.base_url), + status_on = true, + callback = selectBaseUrl, + }) + end, + function(iw) + local status, status_on + if Auth.hasSession() then + status, status_on = Auth.userLabel() or _("已登录"), true + else + status, status_on = _("未登录 · 点此登录"), false + end + return require("ui.themes.widgets.row").widget({ + width = iw, + chevron = true, + kind = "nav", + icon = "account_circle", + title = _("拷贝漫画账号"), + status = status, + status_on = status_on, + callback = function() showLogin() end, + }) + end, + } + if not Auth.hasSession() then return rows end + rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出拷贝漫画账号?"), Auth.clearSession) + return rows +end + +---@return string, boolean +function Setting.rowStatus() + local Auth = require("moonsource_copymanga.auth") + if Auth.hasSession() then + return Auth.userLabel() or _("已登录"), true + end + local cfg = require("utils.settings").getSource(SOURCE_ID) + return Client.normalizeBaseUrl(cfg.base_url), true +end + +--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。 +Setting.login = showLogin + +return Setting diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/source.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/source.lua new file mode 100644 index 0000000..c26c38e --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/source.lua @@ -0,0 +1,449 @@ +--[[-- +拷贝漫画数据源门面。 + +书架是收藏列表,经 Shelf 双向同步;进度双向(章粒度),无远端笔记、统计。 +一章是一组图片 URL,章节 CBZ 按章节 uuid 命名(分组拼接后章号会整体后移)。重登后用最新 token。 + +@module koplugin.book.moonsource_copymanga.source +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_copymanga.client") +local Mapper = require("moonsource_copymanga.mapper") +local SourceBase = require("source.base") +local Shelf = require("source.shelf") +local Toc = require("source.toc") +local logger = require("utils.log") +local _ = require("l10n").get("moonsource_copymanga") + +local Copymanga = {} + +---@return BookSourceMeta +function Copymanga.meta() + return require("moonsource_copymanga.loadmeta")() +end + +---@class CopymangaSource : SourceBase +---@field _client CopymangaClient +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return CopymangaSource +function Copymanga.new() + local cfg = require("utils.settings").getSource("copymanga") + local meta = Copymanga.meta() + local client = Client:new(cfg) + -- 新节点只验证了读章节,不能把拿到图片当作云端进度写入成功。 + local function index(_instance, key) + if client.progress_supported == false and (key == "getProgressAsync" or key == "putProgressAsync") then return nil end + return Source[key] + end + return setmetatable({ + id = meta.id, + name = meta.name, + type = meta.type, + _client = client, + }, { __index = index }) +end + +--- 已登录才算配置好:书架、进度都要令牌;书城浏览匿名可用,不看这里。 +--- 未登录时删书当场撕墓碑、不入队推脏行(见 SourceBase:deleteBookAsync)。 +---@return boolean +function Source:configured() + return self._client:configured() and require("moonsource_copymanga.auth").hasSession() +end + +--- API 收藏双向同步,写入后的确认由客户端回读完成。 +---@param opts { dirty_only?: boolean, force?: boolean, on_progress?: fun(text: string|nil, done: integer|nil, total: integer|nil) }|nil +---@param cb fun(result: SyncResult|nil, err: any) +---@return { cancel: fun() } +function Source:syncBooksAsync(opts, cb) + opts = opts or {} + if not require("moonsource_copymanga.auth").hasSession() then + return SourceBase.syncBooksAsync(self, opts, cb) + end + return Shelf.syncAsync(self.id, self._client, nil, opts, cb) +end + +---@param client CopymangaClient +---@param stable_id string +---@param groups { path_word: string, name: string }[] +---@param cb fun(chapters: BookChapter[]|nil, err: string|nil) +---@return { cancel: fun() } +local function loadChapters(client, stable_id, groups, cb) + return client:chaptersAsync(stable_id, groups, function(rows, err) + if not rows then cb(nil, err); return end + local chapters = Mapper.chapters(rows) + if not chapters then cb(nil, _("漫画目录为空")); return end + cb(chapters) + end) +end + +--- 绕过缓存拉目录并写回。 +---@param self CopymangaSource +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@return { cancel: fun() } +local function fetchTocAsync(self, identity, cb) + local cancelled, job = false, nil + job = self._client:detailAsync(identity.stable_id, function(wire, err) + if cancelled then return end + if not wire then cb(nil, err); return end + job = loadChapters(self._client, identity.stable_id, Mapper.groups(wire), function(chapters, chapter_err) + if cancelled then return end + if not chapters then cb(nil, chapter_err); return end + if not Toc.put(identity.source_id, identity.stable_id, chapters) then + cb(nil, _("漫画目录保存失败")) + return + end + cb(chapters) + end) + end) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +--- 书城搜索:回包形状同 listStoreAsync。 +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +---@return { cancel: fun() }|nil +function Source:searchAsync(keyword, cb) + return self._client:searchAsync(keyword, function(wire, err) + if not wire then + cb(nil, err) + return + end + local books, parse_err = Mapper.search(wire) + cb(books and { data = books } or nil, parse_err) + end) +end + + +-- 官网「查看全部分類」的题材(接口 filter/comic/tags 只回前 20 个,其余题材同样可查);漫展场次标签不收。 +local THEMES = { + { "aiqing", "愛情" }, { "huanlexiang", "歡樂向" }, { "maoxian", "冒險" }, { "qihuan", "奇幻" }, + { "baihe", "百合" }, { "xiaoyuan", "校园" }, { "kehuan", "科幻" }, { "dongfang", "東方" }, + { "danmei", "耽美" }, { "gedou", "格鬥" }, { "teenslove", "TL" }, { "shenghuo", "生活" }, + { "qingxiaoshuo", "轻小说" }, { "xuanyi", "悬疑" }, { "mengxi", "萌系" }, { "shengui", "神鬼" }, + { "zhichang", "职场" }, { "zhiyu", "治愈" }, { "jiecao", "节操" }, { "sige", "四格" }, + { "gaoxiao", "搞笑" }, { "changtiao", "長條" }, { "jingji", "竞技" }, { "mohuan", "魔幻" }, + { "jianniang", "舰娘" }, { "weiniang", "伪娘" }, { "rexue", "热血" }, { "jingsong", "惊悚" }, + { "meishi", "美食" }, { "xingzhuanhuan", "性转换" }, { "lizhi", "励志" }, { "hougong", "後宮" }, + { "yinyuewudao", "音乐舞蹈" }, { "zhentan", "侦探" }, { "COLOR", "彩色" }, { "aa", "AA" }, + { "yishijie", "异世界" }, { "lishi", "历史" }, { "chuanyue", "穿越" }, { "jizhan", "机战" }, + { "zhanzheng", "战争" }, { "dushi", "都市" }, { "chongsheng", "重生" }, { "kongbu", "恐怖" }, + { "shengcun", "生存" }, { "wuxia", "武侠" }, { "zhaixi", "宅系" }, { "zhuansheng", "转生" }, + { "fate", "FATE" }, { "Uncensored", "無修正" }, { "xianxia", "仙侠" }, { "loveLive", "LoveLive" }, + { "zazhifuzengxiezhenji", "雜誌附贈寫真集" }, { "qita", "其他" }, +} + +local PERIODS = { { "day", _("日榜") }, { "week", _("周榜") }, { "month", _("月榜") }, { "total", _("总榜") } } +local AUDIENCES = { { "all", _("全部") }, { "male", _("男频") }, { "female", _("女频") } } + +--- 书城浏览:节点 `周期:受众`(缺省 day:all,每页 20 部)或 `theme:<题材>`(按人气)。 +--- 书城 chip 最多两行:第一行周期,第二行受众 + 题材(放不下的折进「更多」);选题材后周期 / 受众不高亮,点回去就是榜单。 +---@param opts { node?: string, limit?: integer } +---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil) +---@return { cancel: fun() } +function Source:browseAsync(opts, cb) + opts = opts or {} + local node = opts.node or "day:all" + local theme = node:match("^theme:(.+)$") + local period, audience = node:match("^(%a+):(%a+)$") + local valid_period, valid_audience = false, false + for _idx, row in ipairs(PERIODS) do if row[1] == period then valid_period = true end end + for _idx, row in ipairs(AUDIENCES) do if row[1] == audience then valid_audience = true end end + if not theme and (not valid_period or not valid_audience) then period, audience, node = "day", "all", "day:all" end + if theme then period, audience = "day", "all" end + local periods, filters = {}, {} + for _idx, row in ipairs(PERIODS) do periods[#periods + 1] = { id = row[1] .. ":" .. audience, title = row[2] } end + for _idx, row in ipairs(AUDIENCES) do filters[#filters + 1] = { id = period .. ":" .. row[1], title = row[2] } end + for _idx, row in ipairs(THEMES) do filters[#filters + 1] = { id = "theme:" .. row[1], title = row[2] } end + local groups = { Browse.group(periods, node), Browse.group(filters, node) } + return Browse.pages(function(page, done) + local function finish(wire, err) + if not wire then + done(nil, err) + return + end + done(Mapper.search(wire)) + end + local offset = (page - 1) * 20 + if theme then + return self._client:themeAsync(theme, offset, finish) + end + return self._client:rankAsync(period, audience ~= "all" and audience or nil, offset, finish) + end, opts.limit or 60, groups, cb) +end + +function Source:getDetailAsync(identity, cb) + local cancelled, job = false, nil + job = self._client:detailAsync(identity.stable_id, function(wire, err) + if cancelled then return end + if not wire then cb(nil, err); return end + local book = Mapper.detail(wire) + if not book then cb(nil, _("漫画详情解析失败")); return end + local existing = require("book.books_db").get(self.id, identity.stable_id) + if existing then + book.deleted = existing.deleted + end + local progress = require("book.progress_db").get(self.id, identity.stable_id) + if progress then + book.percent = require("book.progress").clampPercent(progress.fraction, false, true) + end + local function finish() + require("book.store").rememberMany({ book }) + cb(book) + end + if Toc.read(self.id, identity.stable_id) then + finish() + return + end + -- 顺手预热目录:详情回包里已有分组,省一次 comic2。 + job = loadChapters(self._client, identity.stable_id, Mapper.groups(wire), function(chapters) + if cancelled then return end + if chapters and not Toc.put(self.id, identity.stable_id, chapters) then + logger.warn("copymanga toc persist failed", identity.stable_id) + end + finish() + end) + end) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@param force boolean|nil 真=跳过缓存强制拉 +---@return { cancel: fun() }|nil +function Source:loadTocAsync(identity, cb, force) + if not force then + local cached = Toc.read(identity.source_id, identity.stable_id) + if cached and #cached > 0 then + return SourceBase.defer(cb, cached) + end + end + return fetchTocAsync(self, identity, cb) +end + +Source.refreshTocAsync = fetchTocAsync + +--- 起始章:显式章号 > 本地进度章号 > 本地进度全书比例 > 第一章。 +---@param identity BookIdentity +---@param opts table +---@param toc BookChapter[] +---@return integer +local function startIndex(identity, opts, toc) + local idx = opts.chapter_idx + if not idx then + local pending = require("book.progress_db").get(identity.source_id, identity.stable_id) + idx = pending and (pending.chapter_idx or math.floor(pending.fraction * #toc) + 1) + end + return math.max(1, math.min(#toc, idx or 1)) +end + +---@param identity BookIdentity +---@param opts table|nil +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Source:openBookAsync(identity, opts, cb) + opts = opts or {} + local Chapter = require("moonsource_copymanga.chapter") + 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 toc = Toc.read(identity.source_id, identity.stable_id) + if toc then + local idx = startIndex(identity, opts, 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 + + local cancelled, active, dialog = false, nil, nil + local function closeDialog() + if dialog then dialog:close(); dialog = nil end + end + require("ui/uimanager"):nextTick(function() + if cancelled then return end + dialog = require("ui.themes.widgets.progress_dialog"):new{ + title = identity.book and identity.book.title or identity.stable_id, + dismissable = false, + } + dialog:show() + dialog:set(_("正在准备漫画…")) + active = self:loadTocAsync(identity, function(fresh, err) + active = nil + if cancelled then return end + if not fresh then closeDialog(); cb(nil, err); return end + local idx = startIndex(identity, opts, fresh) + active = Chapter.materializeAsync(self._client, identity, fresh[idx], + function(done, total) + if dialog and total > 0 then dialog:update(_("正在准备漫画…"), done, total) end + end, + function(path, materialize_err) + active = nil + closeDialog() + if cancelled then return end + if not path then cb(nil, materialize_err); return end + finish(path, idx) + end + ) + end) + end) + + return { cancel = function() + cancelled = true + if active then active.cancel() end + closeDialog() + end } +end + +--- 阅读中后台预取后续章节 CBZ。会话侧固定预取后面 3 章。 +---@param identity BookIdentity +---@param toc BookChapter[] +---@param from_idx integer +---@param count integer +---@param cb fun()|nil +---@return { cancel: fun() } +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + return require("moonsource_copymanga.chapter").prefetchAsync( + self._client, identity, toc, from_idx, count, nil, cb + ) +end + +--- 拉取云端浏览记录,用目录把 chapter_uuid 换成本地章序号。 +--- 官方只有章粒度,没有页内坐标。 +---@param identity BookIdentity +---@param cb fun(pos: ProgressPosition|nil, err: string|nil, meta: table|nil) +---@return { cancel: fun() } +function Source:getProgressAsync(identity, cb) + if not require("moonsource_copymanga.auth").hasSession() then + return SourceBase.defer(cb, nil, nil, { empty = true }) + end + local cancelled, toc_job = false, nil + local request = self._client:getProgressAsync(identity.stable_id, function(wire, err) + if cancelled then return end + if not wire then cb(nil, err); return end + local pos, uid = Mapper.progress(wire) + if not pos or not uid then cb(nil, nil, { empty = true }); return end + + local function finish(idx) + if not idx then cb(nil, nil, { empty = true }); return end + pos.chapter_idx = idx + pos.fraction = Toc.wholeFraction( + identity.source_id, identity.stable_id, idx, pos.chapter_fraction + ) or pos.fraction + pos.extra = { chapter_uid = uid, chapter_idx = idx } + cb(pos) + end + + local idx = Toc.index(identity.source_id, identity.stable_id, uid) + if idx then + finish(idx) + return + end + -- 缓存目录里没有这一话:多半是别的设备读了新更新的章节,缓存还没过期也得重拉。 + toc_job = fetchTocAsync(self, identity, function(toc, toc_err) + if cancelled then return end + if not toc then cb(nil, toc_err); return end + finish(Toc.index(identity.source_id, identity.stable_id, uid)) + end) + end) + return { cancel = function() + cancelled = true + request.cancel() + if toc_job then toc_job.cancel() end + end } +end + +--- 推送当前章到云端。官方没有独立浏览写入接口; +--- 带 Token 的 chapter2 GET 就是打开章节时写入浏览记录的副作用。 +---@param identity BookIdentity +---@param pos ProgressPosition +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Source:putProgressAsync(identity, pos, cb) + if not require("moonsource_copymanga.auth").hasSession() then + return SourceBase.defer(cb, nil, _("请先登录拷贝漫画账号")) + end + local chapter_idx = pos.chapter_idx or identity.chapter_idx + if not chapter_idx then + return SourceBase.defer(cb, nil, _("缺少章节信息")) + end + local cancelled, toc_job, push_job = false, nil, nil + + local function push(uid) + if not uid then + cb(nil, _("缺少章节信息")) + return + end + push_job = self._client:chapterAsync(identity.stable_id, uid, function(wire, err) + if cancelled then return end + cb(wire and true or nil, err) + end) + end + + local extra = pos.extra + local uid = extra and extra.chapter_idx == chapter_idx and extra.chapter_uid + or Toc.uid(identity.source_id, identity.stable_id, chapter_idx) + if uid then + push(uid) + else + toc_job = self:loadTocAsync(identity, function(toc, err) + if cancelled then return end + if not toc then cb(nil, err); return end + push(Toc.uid(identity.source_id, identity.stable_id, chapter_idx)) + end) + end + return { cancel = function() + cancelled = true + if toc_job then toc_job.cancel() end + if push_job then push_job.cancel() end + end } +end + +--- 缓存漫画章节(全本或 range 指定的一段);已落盘章节自动跳过,章与章之间留间隔以免打爆接口。 +---@param identity BookIdentity +---@param on_progress fun(done: integer, total: integer)|nil +---@param cb fun(ok: boolean, cached: integer, err: string|nil, total: integer, failed: integer) +---@param range ChapterCacheRange|nil 缺省全本 +---@return { cancel: fun() } +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local cancelled, active = false, nil + active = self:loadTocAsync(identity, function(toc, err) + if cancelled then return end + if not toc then cb(false, 0, err, 0, 0); return end + local from_idx, count = require("source.chapter").cacheRange(toc, range) + active = require("moonsource_copymanga.chapter").prefetchAsync( + self._client, identity, toc, from_idx, count, + { + progress = on_progress, + interval_seconds = 1.5, + }, + function(cached, total, failed, last_err) + if not cancelled then + cb(failed == 0, cached, last_err, total, failed) + end + end + ) + end) + return { cancel = function() + cancelled = true + active.cancel() + end } +end + +return Copymanga diff --git a/moonsource-copymanga.koplugin/moonsource_copymanga/version.lua b/moonsource-copymanga.koplugin/moonsource_copymanga/version.lua new file mode 100644 index 0000000..25b37f6 --- /dev/null +++ b/moonsource-copymanga.koplugin/moonsource_copymanga/version.lua @@ -0,0 +1,4 @@ +-- 版本号由 tools/package.sh 打包时把占位符换成发布版本;源码运行显示 0.0.0-dev。 +local VERSION = "@VERSION@" +if VERSION:find("^@") then return "0.0.0-dev" end +return VERSION diff --git a/tests/copymanga/api_spec.lua b/tests/copymanga/api_spec.lua new file mode 100644 index 0000000..703db96 --- /dev/null +++ b/tests/copymanga/api_spec.lua @@ -0,0 +1,127 @@ +--[[-- +站点映射保持单一 API 协议;书架写入必须回读确认,取消不能漏到下一阶段。 + +@module tests.moonsource_copymanga.api_spec +--]] + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +package.loaded["json"] = JSON +local Client = require("moonsource_copymanga.client") +local settings = require("utils.settings") +local calls, replies, cancelled = {}, {}, {} +package.loaded["http.request"] = { + get = function(url, opts, cb) + calls[#calls + 1] = { url = url, headers = opts.headers, redirects = opts.allow_redirects } + local reply = table.remove(replies, 1) + local id = #calls + if reply.hold then reply.callback = cb else cb(reply.raw, reply.err) end + return { cancel = function() cancelled[id] = true end } + end, + post = function(url, body, opts, cb) + calls[#calls + 1] = { url = url, headers = opts.headers, body = body, redirects = opts.allow_redirects } + local reply = table.remove(replies, 1) + local id = #calls + if reply.hold then reply.callback = cb else cb(reply.raw, reply.err) end + return { cancel = function() cancelled[id] = true end } + end, +} +local detail = '{"code":200,"results":{"comic":{"uuid":"comic-id","path_word":"test","name":"Test"}}}' +local empty = '{"code":200,"results":{"list":[],"total":0}}' +local collected = '{"code":200,"results":{"list":[{"comic":{"uuid":"comic-id","path_word":"test"}}],"total":1}}' + +for _idx, site in ipairs(Client.SITES) do + local api = site:gsub("https://www%.", "https://api.") + Assert.eq(Client.normalizeBaseUrl(site .. "/"), api) + Assert.eq(Client.normalizeBaseUrl(api), api) + local cfg = settings.getSource("copymanga") + cfg.base_url, cfg.token, cfg.user_id = site, "private-token", "1" + settings.saveSource("copymanga", cfg) + local client = Client:new(cfg) + local result, err + replies = { { raw = empty } } + client:searchAsync("one", function(wire, e) result, err = wire, e end) + Assert.is_nil(err) + Assert.is_true(result ~= nil) + Assert.is_true(calls[#calls].url:find(api .. "/api/v3/search/comic?", 1, true) == 1) + Assert.eq(calls[#calls].headers["User-Agent"], "COPY/3.0.0") + Assert.is_nil(calls[#calls].headers.Authorization) + + replies = { { raw = '{"code":200,"results":{"chapter":{"contents":[{"url":"https://images.example/page.jpg"}]}}}' } } + client:chapterAsync("test", "chapter-id", function(wire, e) result, err = wire, e end) + Assert.is_nil(err) + Assert.is_true(result ~= nil) + local endpoint = api == Client.CURRENT_BASE_URL and "chapter" or "chapter2" + Assert.eq(calls[#calls].url, api .. "/api/v3/comic/test/" .. endpoint .. "/chapter-id?platform=1") + + replies = { { raw = detail }, { raw = '{"code":200}' }, { raw = collected } } + client:addToShelfAsync("test", function(wire, e) result, err = wire, e end) + Assert.is_nil(err) + Assert.is_true(result ~= nil) + Assert.eq(calls[#calls - 1].url, api .. "/api/v3/member/collect/comic") + Assert.is_true(calls[#calls - 1].body:find("is_collect=1", 1, true) ~= nil) + Assert.eq(calls[#calls].headers.Authorization, "Token private-token") + Assert.is_false(calls[#calls].redirects) + Assert.is_false(calls[#calls - 1].redirects) + + replies = { { raw = detail }, { raw = '{"code":200}' }, { raw = collected } } + client:removeFromShelfAsync("test", function(wire, e) result, err = wire, e end) + Assert.is_nil(result) + Assert.eq(err, "书架同步未确认") + + replies = { { raw = detail }, { raw = '{"code":200}' }, { raw = empty } } + client:removeFromShelfAsync("test", function(wire, e) result, err = wire, e end) + Assert.is_nil(err) + Assert.is_true(result ~= nil) + + local held = { hold = true } + replies = { { raw = detail }, { raw = '{"code":200}' }, held } + local completed = false + local job = client:addToShelfAsync("test", function() completed = true end) + job.cancel() + Assert.is_true(cancelled[#calls], "取消回读阶段,不得被同步返回的旧句柄覆盖") + held.callback(collected) + Assert.is_false(completed) + + local source = require("moonsource_copymanga.source").new() + if api == Client.CURRENT_BASE_URL then + Assert.is_nil(source.getProgressAsync) + Assert.is_nil(source.putProgressAsync) + else + Assert.eq(type(source.getProgressAsync), "function") + Assert.eq(type(source.putProgressAsync), "function") + end +end + +do + local client = Client:new(settings.getSource("copymanga")) + local result, err + replies = { { raw = '{"code":200,"results":{}}' } } + client:shelfSyncAsync(function(rows, e) result, err = rows, e end) + Assert.is_nil(result) + Assert.eq(err, "响应无效") + replies = { { raw = '{"code":200,"results":{"list":[{}],"total":1}}' } } + client:shelfSyncAsync(function(rows, e) result, err = rows, e end) + Assert.is_nil(result) + Assert.eq(err, "响应无效") + replies = { { raw = '{"code":200,"results":{"list":[],"total":2}}' } } + client:shelfSyncAsync(function(rows, e) result, err = rows, e end) + Assert.is_nil(result) + Assert.eq(err, "响应无效") + + replies = { + { raw = '{"code":200,"results":{"list":[{"comic":{"path_word":"one"}}],"total":2}}' }, + { raw = '{"code":200,"results":{"list":[{"comic":{"path_word":"two"}}],"total":2}}' }, + } + client:shelfSyncAsync(function(rows, e) result, err = rows, e end) + Assert.is_nil(err) + Assert.len(result, 2) + Assert.is_true(calls[#calls].url:find("offset=1", 1, true) ~= nil) + require("moonsource_copymanga.auth").clearSession() + Assert.eq(client:_latestToken(), "") + local cfg = settings.getSource("copymanga") + cfg.base_url, cfg.token = Client.SITES[1], "new-site-token" + settings.saveSource("copymanga", cfg) + Assert.eq(client:_latestToken(), "") +end +require("moonsource_copymanga.auth").clearSession() diff --git a/tests/copymanga/auth_spec.lua b/tests/copymanga/auth_spec.lua new file mode 100644 index 0000000..a22e363 --- /dev/null +++ b/tests/copymanga/auth_spec.lua @@ -0,0 +1,88 @@ +--[[-- +拷贝漫画登录密码编码用例。 + +@module tests.moonsource_copymanga.auth_spec +--]] + +local Assert = require("support.assert") +package.loaded["json"] = require("support.json_stub") +local switches = 0 +require("source.logout").replaceLibrary = function(id, commit) + Assert.eq(id, "copymanga") + switches = switches + 1 + commit() + return true +end +local Auth = require("moonsource_copymanga.auth") +local Text = require("utils.text") + +do + -- 与站点前端一致:base64(password .. "-" .. salt) + Assert.eq(Auth.encodePassword("secret", 123456), Text.base64Encode("secret-123456")) + Assert.eq(Auth.encodePassword("密 码", "000001"), Text.base64Encode("密 码-000001")) +end + +do + local settings = require("utils.settings") + local current = settings.getSource("copymanga") + local original_base = current.base_url + current.base_url = "https://www.copy4000.com" + settings.saveSource("copymanga", current) + local pending, request + local cancelled = false + package.loaded["http.request"] = { + request = function(opts, cb) + request, pending = opts, cb + return { cancel = function() cancelled = true end } + end, + } + Auth.clearSession() + local ok, err + local job = Auth.loginAsync("user", " spaced password ", function(result, e) ok, err = result, e end) + Assert.eq(request.url, "https://api.copy4000.com/api/v3/login") + Assert.is_false(request.allow_redirects) + Assert.eq(request.cache_ttl, 0) + Assert.is_true(request.body:find(require("utils.text").urlEncode(Auth.encodePassword(" spaced password ", + require("utils.text").urlDecode(request.body:match("salt=([^&]+)")))), 1, true) ~= nil) + pending({ body = '{"code":200,"results":{"token":"first","user_id":"1"}}' }) + Assert.is_true(ok) + Assert.eq(current.password, " spaced password ", "登录成功必须落盘密码,401 才能自动重登") + Assert.eq(current.username, "user") + + job = Auth.loginAsync("other", "pass", function(result, e) ok, err = result, e end) + pending({ body = '{"code":200,"results":{"token":"other","user_id":"2"}}' }) + Assert.is_true(ok) + Assert.is_nil(err) + Assert.eq(current.token, "other") + Assert.eq(switches, 2, "换账号准备同步,不再要求先退出清数据") + + job = Auth.loginAsync("user", "pass", function(result, e) ok, err = result, e end) + job.cancel() + pending({ body = '{"code":200,"results":{"token":"cancelled","user_id":"1"}}' }) + Assert.is_true(cancelled) + Assert.eq(current.token, "other") + Auth.clearSession() + current.base_url = original_base + settings.saveSource("copymanga", current) +end + +do + Assert.is_false(Auth.hasSession()) + Assert.is_nil(Auth.userLabel()) + Assert.is_nil(Auth.credentials()) +end + +do + local settings = require("utils.settings") + local cfg = settings.getSource("copymanga") + cfg.username = "user" + cfg.password = "secret" + cfg.token = "tok" + settings.saveSource("copymanga", cfg) + local username, password = Auth.credentials() + Assert.eq(username, "user") + Assert.eq(password, "secret") + Auth.clearSession() + Assert.is_nil(Auth.credentials()) + Assert.is_false(Auth.hasSession()) +end diff --git a/tests/copymanga/browse_spec.lua b/tests/copymanga/browse_spec.lua new file mode 100644 index 0000000..72223f4 --- /dev/null +++ b/tests/copymanga/browse_spec.lua @@ -0,0 +1,57 @@ +--[[-- +拷贝漫画书城浏览:榜单与题材共用一套 chip,题材节点走 /comics 且不高亮周期 / 受众。 + +@module tests.moonsource_copymanga.browse_spec +--]] + +local Assert = require("support.assert") + +local fake_client = {} +local calls = {} + +local function stub(name, factory) + package.preload[name] = factory + package.loaded[name] = nil +end + +stub("utils.settings", function() + return { getSource = function() return { token = "tok" } end, saveSource = function() end } +end) +stub("moonsource_copymanga.client", function() + return { new = function() return fake_client end, headers = function() return {} end, + normalizeBaseUrl = function(url) return url end } +end) + +local function page(name) + return { results = { list = { { path_word = name, name = name } } } } +end +fake_client.rankAsync = function(_, period, audience, offset, cb) + calls[#calls + 1] = "rank:" .. period .. ":" .. tostring(audience) .. ":" .. offset + cb(page("r")) + return { cancel = function() end } +end +fake_client.themeAsync = function(_, theme, offset, cb) + calls[#calls + 1] = "theme:" .. theme .. ":" .. offset + cb(page("t")) + return { cancel = function() end } +end + +package.loaded["moonsource_copymanga.source"] = nil +local src = require("moonsource_copymanga.source").new() + +local res +src:browseAsync({ node = "theme:rexue", limit = 1 }, function(r) res = r end) +Assert.eq(calls[1], "theme:rexue:0") +Assert.eq(res.data[1].stable_id, "t") +Assert.len(res.groups, 2) +Assert.eq(res.groups[2].active, "theme:rexue") +Assert.is_nil(res.groups[1].active) + +src:browseAsync({ limit = 1 }, function(r) res = r end) +Assert.eq(calls[2], "rank:day:nil:0") +Assert.eq(res.groups[1].active, "day:all") +Assert.eq(res.groups[2].active, "day:all") + +src:browseAsync({ node = "web:ordering=-popular&theme=rexue", limit = 1 }, function(r) res = r end) +Assert.eq(calls[3], "rank:day:nil:0", "切回 App 后不能把官网节点当榜单周期") +Assert.eq(res.groups[1].active, "day:all") diff --git a/tests/copymanga/chapter_spec.lua b/tests/copymanga/chapter_spec.lua new file mode 100644 index 0000000..fac0113 --- /dev/null +++ b/tests/copymanga/chapter_spec.lua @@ -0,0 +1,122 @@ +--[[-- +拷贝漫画章节预取 / 全书缓存用例。 + +@module tests.moonsource_copymanga.chapter_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() + +package.preload["ffi/archiver"] = function() + return { Writer = { new = function() return {} end } } +end +package.preload["utils.paths"] = function() + return { ensureBookWork = function() end, bookWorkDir = function() return "/tmp" end } +end +package.preload["moonsource_copymanga.protocol"] = function() + return { chapterImages = function() end } +end +package.preload["moonsource_copymanga.client"] = function() + return { headers = function() return {} end } +end +package.loaded["moonsource_copymanga.chapter"] = nil + +local Chapter = require("moonsource_copymanga.chapter") + +local calls = {} +local fail_at +-- 章节 CBZ 按 uuid 命名,不随目录里的连续章号漂移。 +Assert.eq(Chapter.archivePath({ source_id = "copymanga", stable_id = "comic" }, { idx = 7, uid = "uuid-7" }), + "/tmp/uuid-7.cbz") + +Chapter.materializeAsync = function(_, _, chapter, _, cb) + local idx = chapter.idx + calls[#calls + 1] = idx + if fail_at == idx then + require("ui/uimanager"):nextTick(function() cb(nil, "fail") end) + else + require("ui/uimanager"):nextTick(function() cb("/tmp/" .. idx .. ".cbz") end) + end + return { cancel = function() end } +end + +local toc = { + { idx = 1, uid = "a" }, + { idx = 2, uid = "b" }, + { idx = 3, uid = "c" }, + { idx = 4, uid = "d" }, + { idx = 5, uid = "e" }, +} +local identity = { source_id = "copymanga", stable_id = "comic" } + +do + local cached, total, failed + Chapter.prefetchAsync({}, identity, toc, 2, 3, nil, function(c, t, f) + cached, total, failed = c, t, f + end) + Stubs.flush() + Assert.eq(calls[1], 3) + Assert.eq(calls[2], 4) + Assert.eq(calls[3], 5) + Assert.len(calls, 3) + Assert.eq(cached, 3) + Assert.eq(total, 3) + Assert.eq(failed, 0) +end + +do + calls = {} + local cached, total, failed + Chapter.prefetchAsync({}, identity, toc, 5, 3, nil, function(c, t, f) + cached, total, failed = c, t, f + end) + Stubs.flush() + Assert.len(calls, 0) + Assert.eq(cached, 0) + Assert.eq(total, 0) + Assert.eq(failed, 0) +end + +do + calls = {} + fail_at = 4 + local cached, total, failed, last_err + local progressed = {} + Chapter.prefetchAsync({}, identity, toc, 2, 3, { + progress = function(done, all) progressed[#progressed + 1] = { done, all } end, + }, function(c, t, f, err) + cached, total, failed, last_err = c, t, f, err + end) + Stubs.flush() + Assert.len(calls, 3) + Assert.eq(cached, 2) + Assert.eq(total, 3) + Assert.eq(failed, 1) + Assert.eq(last_err, "fail") + Assert.eq(progressed[#progressed][1], 3) + Assert.eq(progressed[#progressed][2], 3) + fail_at = nil +end + +do + calls = {} + local cached + Chapter.prefetchAsync({}, identity, toc, 0, #toc, { + interval_seconds = 1.5, + }, function(c) cached = c end) + Stubs.flush() + Assert.len(calls, 5) + Assert.eq(cached, 5) +end + +do + calls = {} + local done = false + local job = Chapter.prefetchAsync({}, identity, toc, 1, 3, nil, function() done = true end) + job.cancel() + Stubs.flush() + Assert.len(calls, 0) + Assert.is_false(done) +end diff --git a/tests/copymanga/client_spec.lua b/tests/copymanga/client_spec.lua new file mode 100644 index 0000000..8f8fd4e --- /dev/null +++ b/tests/copymanga/client_spec.lua @@ -0,0 +1,187 @@ +--[[-- +拷贝漫画 App 客户端:常量与令牌失效自动重登。 + +@module tests.moonsource_copymanga.client_spec +--]] + +local Assert = require("support.assert") + +-- 记录请求;get 按队列回放 { code, body },request 是登录 POST。 +local gets, logins, replies, login_ok = {}, 0, {}, true +-- login_hold:登录回调先挂起,模拟并发;login_net:登录走网络错误。 +local login_hold, login_net = nil, false +package.loaded["http.request"] = { + get = function(url, opts, cb) + gets[#gets + 1] = { url = url, auth = opts.headers.Authorization } + local reply = table.remove(replies, 1) + if reply.code == 200 then + cb(reply.body, nil, { code = 200, body = reply.body }) + else + cb(nil, "HTTP " .. reply.code, { code = reply.code, body = reply.body }) + end + return { cancel = function() end } + end, + request = function(_opts, cb) + logins = logins + 1 + if login_net then + cb(nil, "connection timed out") + return { cancel = function() end } + end + local body = login_ok + and '{"code":200,"results":{"token":"fresh","user_id":"1","username":"user"}}' + or '{"code":400,"message":"密码错误"}' + if login_hold then + login_hold[#login_hold + 1] = function() cb({ code = 200, body = body }) end + else + cb({ code = 200, body = body }) + end + return { cancel = function() end } + end, +} +package.loaded["json"] = { decode = require("support.json_stub").decode } +package.loaded["moonsource_copymanga.auth"] = nil +package.loaded["moonsource_copymanga.client"] = nil +local Client = require("moonsource_copymanga.client") + +do + Assert.eq(Client.normalizeBaseUrl(""), Client.DEFAULT_BASE_URL) + Assert.eq(Client.normalizeBaseUrl("https://api.example.com/"), "https://api.example.com") + Assert.eq(Client.normalizeBaseUrl("https://copy4000.com"), "https://copy4000.com") +end + +do + local headers = Client.headers("abc") + Assert.eq(headers["User-Agent"], "COPY/3.0.0") + Assert.eq(headers.platform, "1") + Assert.eq(headers.Authorization, "Token abc") + Assert.is_nil(Client.headers("").Authorization) +end + +do + local client = Client:new({}) + Assert.eq(client.base_url, Client.DEFAULT_BASE_URL) + Assert.is_true(client:configured()) +end + +local settings = require("utils.settings") +local function session(password) + local cfg = settings.getSource("copymanga") + cfg.base_url = nil + cfg.user_id = "1" + cfg.token, cfg.username, cfg.password = "stale", "user", password + settings.saveSource("copymanga", cfg) +end +local INVALID = '{"code":401,"message":"Invalid token header. Please login again."}' +local OK = '{"code":200,"results":{"list":[],"total":0}}' + +-- 匿名 API 被拒绝时保留真实原因,不误称用户账号被风控,也不自动重登。 +do + session("secret") + gets, logins, replies = {}, 0, { + { code = 200, body = '{"code":210,"message":"请更新官方 App 并等待限制解除"}' }, + } + local result, err + Client:new(settings.getSource("copymanga")):detailAsync("test", function(wire, e) result, err = wire, e end) + Assert.is_nil(result) + Assert.eq(err, "请更新官方 App 并等待限制解除") + Assert.is_nil(gets[1].auth) + Assert.eq(logins, 0) + result, err = Client.decode('{"code":210}') + Assert.is_nil(result) + Assert.eq(err, "拷贝漫画 API 拒绝请求(210),请按官网提示处理") + result, err = Client.decode('{"code":210,"message":false}') + Assert.is_nil(result) + Assert.eq(err, "拷贝漫画 API 拒绝请求(210),请按官网提示处理") +end + +-- #42:令牌被挤掉后返回 401,用保存的账号密码重登一次,换新令牌重试。 +do + session("secret") + gets, logins, replies, login_ok = {}, 0, { { code = 401, body = INVALID }, { code = 200, body = OK } }, true + local client = Client:new(settings.getSource("copymanga")) + local wire, err + client:collectAllAsync(function(rows, e) wire, err = rows, e end) + Assert.is_nil(err) + Assert.len(wire, 0) + Assert.eq(logins, 1) + Assert.len(gets, 2) + Assert.eq(gets[1].auth, "Token stale") + Assert.eq(gets[2].auth, "Token fresh") + Assert.eq(client.token, "fresh") +end + +-- 重登后仍 401:只重登一次,不死循环,给出可读提示而不是「HTTP 401」。 +do + session("secret") + gets, logins, replies, login_ok = {}, 0, { { code = 401, body = INVALID }, { code = 401, body = INVALID } }, true + local err + Client:new(settings.getSource("copymanga")):collectAllAsync(function(_rows, e) err = e end) + Assert.eq(logins, 1) + Assert.matches(err, "拷贝漫画账号") +end + +-- 重登失败(密码已改)或没存密码:直接提示重新登录。 +do + session("secret") + gets, logins, replies, login_ok = {}, 0, { { code = 401, body = INVALID } }, false + local err + Client:new(settings.getSource("copymanga")):collectAllAsync(function(_rows, e) err = e end) + Assert.eq(logins, 1) + Assert.matches(err, "拷贝漫画账号") + + session("") + gets, logins, replies = {}, 0, { { code = 401, body = INVALID } } + Client:new(settings.getSource("copymanga")):collectAllAsync(function(_rows, e) err = e end) + Assert.eq(logins, 0) + Assert.matches(err, "拷贝漫画账号") +end + +-- 并发 401:只登录一次,所有等待的请求都用新令牌重试成功;另一个实例也拿到新令牌。 +do + session("secret") + gets, logins, login_ok, login_hold = {}, 0, true, {} + replies = { { code = 401, body = INVALID }, { code = 401, body = INVALID }, + { code = 200, body = OK }, { code = 200, body = OK } } + local a, b = Client:new(settings.getSource("copymanga")), Client:new(settings.getSource("copymanga")) + local errs, done = {}, 0 + local function finish(_rows, e) done = done + 1; errs[#errs + 1] = e end + a:collectAllAsync(finish) + b:collectAllAsync(finish) + Assert.eq(logins, 1, "并发 401 只登录一次") + login_hold[1]() + login_hold = nil + Assert.eq(done, 2) + Assert.len(errs, 0) + Assert.eq(gets[3].auth, "Token fresh") + Assert.eq(gets[4].auth, "Token fresh") + Assert.eq(b.token, "fresh") + + -- 另一个请求已换过令牌:用新令牌直接重试,不再登录。 + local cfg = settings.getSource("copymanga") + cfg.token = "stale" + settings.saveSource("copymanga", cfg) + local c = Client:new(cfg) + logins, gets = 0, {} + replies = { { code = 200, body = OK } } + cfg.token = "newer" + settings.saveSource("copymanga", cfg) + c:collectAllAsync(function() end) + Assert.eq(gets[1].auth, "Token newer", "总是用设置里的最新令牌") + Assert.eq(logins, 0) +end + +-- 重登遇到网络错误:原样回传,不误导用户去重新登录。 +do + session("secret") + gets, logins, replies, login_net = {}, 0, { { code = 401, body = INVALID } }, true + local err + Client:new(settings.getSource("copymanga")):collectAllAsync(function(_rows, e) err = e end) + login_net = false + Assert.eq(logins, 1) + Assert.eq(err, "connection timed out") +end + +require("moonsource_copymanga.auth").clearSession() +package.loaded["http.request"] = nil + +return true diff --git a/tests/copymanga/mapper_spec.lua b/tests/copymanga/mapper_spec.lua new file mode 100644 index 0000000..285a5c4 --- /dev/null +++ b/tests/copymanga/mapper_spec.lua @@ -0,0 +1,131 @@ +--[[-- +拷贝漫画数据映射用例。 + +@module tests.moonsource_copymanga.mapper_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local Mapper = require("moonsource_copymanga.mapper") + +do + local book = Mapper.book({ + name = "测试漫画", + path_word = "test-comic", + cover = "https://img.example/cover.jpg", + author = { { name = "作者甲" }, { name = "作者乙" } }, + }) + Assert.eq(book.source_id, "copymanga") + Assert.eq(book.stable_id, "test-comic") + Assert.eq(book.authors, "作者甲, 作者乙") + Assert.is_nil(Mapper.book({ name = "没有 path_word" })) +end + +do + local wire = { + results = { + comic = { + uuid = "comic-uuid-1", + name = "测试漫画", + path_word = "test-comic", + cover = "https://img.example/cover.jpg", + author = { { name = "作者甲" } }, + theme = { { name = "冒險" } }, + brief = "第一行第二行", + }, + }, + } + Assert.eq(Mapper.comicId(wire), "comic-uuid-1") + Assert.is_nil(Mapper.comicId({ results = { comic = { name = "无id" } } })) + local book = Mapper.detail(wire) + Assert.eq(book.stable_id, "test-comic") + Assert.eq(book.title, "测试漫画") + Assert.eq(book.authors, "作者甲") + Assert.eq(book.category, "冒險") + Assert.eq(book.intro, "第一行第二行") + Assert.eq(book.cover, "https://img.example/cover.jpg") +end + +do + local groups = Mapper.groups({ + results = { + groups = { + extra = { name = "番外", path_word = "extra" }, + default = { name = "默认", path_word = "default" }, + }, + }, + }) + Assert.len(groups, 2) + Assert.eq(groups[1].path_word, "default") + Assert.eq(groups[2].path_word, "extra") +end + +do + local groups = Mapper.groups({ results = {} }) + Assert.len(groups, 1) + Assert.eq(groups[1].path_word, "default") +end + +do + local chapters = Mapper.chapters({ + { uuid = "uuid-1", name = "第一話", group_path = "default", group_name = "默认" }, + { uuid = "uuid-2", name = "第二話", group_path = "default", group_name = "默认" }, + { uuid = "uuid-1", name = "第一話", group_path = "default", group_name = "默认" }, + { uuid = "uuid-x", name = "番外1", group_path = "extra", group_name = "番外" }, + }) + Assert.len(chapters, 3) + Assert.eq(chapters[1].idx, 1) + Assert.eq(chapters[1].uid, "uuid-1") + Assert.eq(chapters[2].title, "第二話") + Assert.eq(chapters[3].title, "番外 · 番外1") +end + +do + local books = Mapper.collect({ + { + comic = { + name = "收藏漫画", + path_word = "fav-comic", + cover = "https://img.example/fav.jpg", + author = { { name = "作者丙" } }, + }, + }, + }) + Assert.len(books, 1) + Assert.eq(books[1].stable_id, "fav-comic") + Assert.eq(books[1].title, "收藏漫画") + Assert.eq(books[1].authors, "作者丙") + Assert.eq(books[1].deleted, 0) + local invalid, err = Mapper.collect({ { comic = { name = "坏行" } } }) + Assert.is_nil(invalid) + Assert.eq(err, "响应无效") +end + +do + local pos, uid = Mapper.progress({ + results = { + browse = { + chapter_uuid = "chap-uuid-9", + chapter_name = "第九话", + }, + }, + }) + Assert.eq(uid, "chap-uuid-9") + Assert.eq(pos.chapter_title, "第九话") + Assert.eq(pos.fraction, 0) +end + +do + local pos, uid = Mapper.progress({ + results = { browse = { chapter_id = "fallback-id" } }, + }) + Assert.eq(uid, "fallback-id") + Assert.is_nil(pos.chapter_title) +end + +do + Assert.is_nil(Mapper.progress({ results = { browse = nil } })) + Assert.is_nil(Mapper.progress({ results = { browse = { chapter_name = "无id" } } })) + Assert.is_nil(Mapper.progress({ results = {} })) + Assert.is_nil(Mapper.progress(nil)) +end diff --git a/tests/copymanga/open_spec.lua b/tests/copymanga/open_spec.lua new file mode 100644 index 0000000..05a4b43 --- /dev/null +++ b/tests/copymanga/open_spec.lua @@ -0,0 +1,151 @@ +--[[-- +拷贝漫画离线打开:已有 CBZ(按章节 uuid 命名)时不触发目录/详情/下载; +起始章取显式章号或本地进度;没缓存又没网立即失败。 + +@module tests.moonsource_copymanga.open_spec +--]] +---@diagnostic disable: undefined-field + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() + +local calls = 0 +local touched +local pending +local connected = false + +local function stub(name, factory) + package.preload[name] = factory + package.loaded[name] = nil +end + +stub("source.base", function() + return { + loadMeta = function(id) return { id = id, name = id, type = "book" } end, + defer = function(cb, ...) + local args = { n = select("#", ...), ... } + require("ui/uimanager"):nextTick(function() cb(unpack(args, 1, args.n)) end) + return { cancel = function() end } + end, + } +end) +stub("source.shelf", function() return {} end) +stub("source.toc", function() + return { + -- 统一目录接口始终提供持久化快照,不再绕回旧 JSON 字段。 + read = function() + return { { idx = 1, uid = "uuid-1" }, { idx = 2, uid = "uuid-2" }, { idx = 3, uid = "uuid-3" } } + end, + } +end) +stub("moonsource_copymanga.mapper", function() return {} end) +stub("utils.settings", function() + return { getSource = function() return {} end } +end) +stub("moonsource_copymanga.client", function() + return { + new = function() + return setmetatable({}, { + __index = function() + return function() + calls = calls + 1 + error("network path reached") + end + end, + }) + end, + headers = function() return {} end, + } +end) +stub("ffi/archiver", function() return { Writer = { new = function() return {} end } } end) +stub("utils.paths", function() + return { + bookWorkDir = function() return "/offline-cache/comic" end, + } +end) +stub("libs/libkoreader-lfs", function() + return { + attributes = function(path) + if path == "/offline-cache/comic/uuid-2.cbz" then + return { mode = "file", size = 42 } + end + return nil + end, + } +end) +stub("json", function() + return { decode = require("support.json_stub").decode } +end) +stub("book.books_db", function() + return { + getToc = function(_, _, max_age) + Assert.is_nil(max_age, "离线开书读目录不看 TTL") + return '[{"idx":1,"uid":"uuid-1"},{"idx":2,"uid":"uuid-2"},{"idx":3,"uid":"uuid-3"}]' + end, + } +end) +stub("book.progress_db", function() + return { get = function() return pending end } +end) +stub("ui/network/manager", function() + return { isConnected = function() return connected end } +end) +stub("book.store", function() + return { + touch = function(path, identity, opts) + touched = { path = path, identity = identity, opts = opts } + return true + end, + } +end) + +package.loaded["moonsource_copymanga.chapter"] = nil +package.loaded["moonsource_copymanga.source"] = nil +local Copymanga = require("moonsource_copymanga.source") +local source = Copymanga.new() +local identity = { + source_id = "copymanga", + stable_id = "comic", + book = {}, +} + +local function open(opts) + local result, err + source:openBookAsync(identity, opts, function(path, open_err) + result, err = path, open_err + end) + Stubs.flush() + return result, err +end + +-- 显式章号:按目录换成 uuid,命中已下载的 CBZ。 +do + touched = nil + local result, err = open({ chapter_idx = 2 }) + Assert.eq(calls, 0) + Assert.eq(result, "/offline-cache/comic/uuid-2.cbz") + Assert.is_nil(err) + Assert.eq(touched.path, result) + Assert.eq(touched.opts.chapter_idx, 2) +end + +-- 不带章号:用本地进度的章号。 +do + pending = { chapter_idx = 2, fraction = 0.1 } + local result = open(nil) + Assert.eq(result, "/offline-cache/comic/uuid-2.cbz") + pending = nil +end + +-- 本地进度没有章号:按全书比例换算(2/3 → 第 3 章,没下载);离线立即失败,不发请求。 +do + pending = { fraction = 0.7 } + touched = nil + local result, err = open(nil) + Assert.is_nil(result) + Assert.eq(err, "网络不可用,请先连接 Wi-Fi") + Assert.is_nil(touched) + Assert.eq(calls, 0) + pending = nil +end diff --git a/tests/copymanga/progress_spec.lua b/tests/copymanga/progress_spec.lua new file mode 100644 index 0000000..96a1e59 --- /dev/null +++ b/tests/copymanga/progress_spec.lua @@ -0,0 +1,197 @@ +--[[-- +拷贝漫画进度:query 拉浏览记录,chapter2 推当前章。 + +@module tests.moonsource_copymanga.progress_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local Stubs = require("support.stubs") + +local fake_client = {} +local logged_in = true +local toc_store = {} + +local function stub(name, factory) + package.preload[name] = factory + package.loaded[name] = nil +end + +stub("json", function() + return { + decode = require("support.json_stub").decode, + encode = require("support.json_stub").encode, + } +end) +stub("book.books_db", function() + return { + getToc = function(source_id, stable_id) + return toc_store[source_id .. "\31" .. stable_id] + end, + setToc = function(source_id, stable_id, payload) + toc_store[source_id .. "\31" .. stable_id] = payload + return true + end, + get = function() return nil end, + } +end) +stub("utils.settings", function() + return { + getSource = function() return { token = "tok" } end, + saveSource = function() end, + } +end) +stub("moonsource_copymanga.auth", function() + return { hasSession = function() return logged_in end } +end) +stub("moonsource_copymanga.client", function() + return { + new = function() return fake_client end, + headers = function() return {} end, + normalizeBaseUrl = function(url) return url end, + } +end) + +package.loaded["source.toc"] = nil +package.loaded["moonsource_copymanga.source"] = nil +local Copymanga = require("moonsource_copymanga.source") +local Toc = require("source.toc") +local src = Copymanga.new() + +local IDENTITY = { + source_id = "copymanga", + stable_id = "test-comic", + chapter_idx = 2, +} + +Toc.put("copymanga", "test-comic", { + { idx = 1, uid = "chap-1", title = "第一话" }, + { idx = 2, uid = "chap-2", title = "第二话" }, + { idx = 3, uid = "chap-3", title = "第三话" }, +}) + +do + logged_in = false + local pos, err, meta + src:getProgressAsync(IDENTITY, function(p, e, m) pos, err, meta = p, e, m end) + Stubs.flush() + Assert.is_nil(pos) + Assert.is_nil(err) + Assert.is_true(meta.empty) + logged_in = true +end + +do + fake_client.getProgressAsync = function(_, _, cb) + cb({ results = { browse = nil } }) + return { cancel = function() end } + end + local pos, err, meta + src:getProgressAsync(IDENTITY, function(p, e, m) pos, err, meta = p, e, m end) + Assert.is_nil(pos) + Assert.is_nil(err) + Assert.is_true(meta.empty) +end + +do + fake_client.getProgressAsync = function(_, _, cb) + cb({ + results = { + browse = { chapter_uuid = "chap-2", chapter_name = "第二话" }, + }, + }) + return { cancel = function() end } + end + local pos, err + src:getProgressAsync(IDENTITY, function(p, e) pos, err = p, e end) + Assert.is_nil(err) + Assert.eq(pos.chapter_idx, 2) + Assert.eq(pos.chapter_title, "第二话") + Assert.eq(pos.fraction, 1 / 3) + Assert.eq(pos.extra.chapter_uid, "chap-2") +end + +do + fake_client.getProgressAsync = function(_, _, cb) + cb(nil, "网络错误") + return { cancel = function() end } + end + local pos, err + src:getProgressAsync(IDENTITY, function(p, e) pos, err = p, e end) + Assert.is_nil(pos) + Assert.eq(err, "网络错误") +end + +-- 云端读到缓存目录里没有的新话:缓存没过期也强制重拉目录再定位。 +do + local detail_calls = 0 + fake_client.getProgressAsync = function(_, _, cb) + cb({ results = { browse = { chapter_uuid = "chap-4", chapter_name = "第四话" } } }) + return { cancel = function() end } + end + fake_client.detailAsync = function(_, _, cb) + detail_calls = detail_calls + 1 + cb({ results = { comic = { path_word = "test-comic" } } }) + return { cancel = function() end } + end + fake_client.chaptersAsync = function(_, _, _, cb) + cb({ + { uuid = "chap-1", name = "第一话" }, { uuid = "chap-2", name = "第二话" }, + { uuid = "chap-3", name = "第三话" }, { uuid = "chap-4", name = "第四话" }, + }) + return { cancel = function() end } + end + local pos, err + src:getProgressAsync(IDENTITY, function(p, e) pos, err = p, e end) + Assert.is_nil(err) + Assert.eq(detail_calls, 1) + Assert.eq(pos.chapter_idx, 4) + Assert.eq(pos.extra.chapter_uid, "chap-4") +end + +-- 没有章号不能默认推第一章,否则会把云端浏览记录改回开头。 +do + local ok, err + src:putProgressAsync({ source_id = "copymanga", stable_id = "test-comic" }, {}, + function(value, e) ok, err = value, e end) + Stubs.flush() + Assert.is_nil(ok) + Assert.eq(err, "缺少章节信息") +end + +do + logged_in = false + local ok, err + src:putProgressAsync(IDENTITY, { chapter_idx = 2 }, function(value, e) ok, err = value, e end) + Stubs.flush() + Assert.is_nil(ok) + Assert.eq(err, "请先登录拷贝漫画账号") + logged_in = true +end + +do + local pushed + fake_client.chapterAsync = function(_, stable_id, uid, cb) + pushed = { stable_id = stable_id, uid = uid } + cb({ code = 200 }) + return { cancel = function() end } + end + local ok, err + src:putProgressAsync(IDENTITY, { chapter_idx = 3 }, function(value, e) ok, err = value, e end) + Assert.is_true(ok) + Assert.is_nil(err) + Assert.eq(pushed.stable_id, "test-comic") + Assert.eq(pushed.uid, "chap-3") +end + +do + local ok, err + src:putProgressAsync(IDENTITY, { + chapter_idx = 1, + extra = { chapter_uid = "chap-1", chapter_idx = 1 }, + }, function(value, e) ok, err = value, e end) + Assert.is_true(ok) + Assert.is_nil(err) +end + +Stubs.flush() diff --git a/tests/copymanga/protocol_spec.lua b/tests/copymanga/protocol_spec.lua new file mode 100644 index 0000000..46cda02 --- /dev/null +++ b/tests/copymanga/protocol_spec.lua @@ -0,0 +1,69 @@ +--[[-- +拷贝漫画 chapter2 图片排序用例。 + +@module tests.moonsource_copymanga.protocol_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type + +local Assert = require("support.assert") +local Protocol = require("moonsource_copymanga.protocol") + +do + local images, err = Protocol.chapterImages({ + results = { + chapter = { + contents = { + { url = "https://img.example/002.c800x.webp" }, + { url = "https://img.example/001.c800x.webp" }, + }, + words = { 1, 0 }, + }, + }, + }) + Assert.is_nil(err) + Assert.len(images, 2) + Assert.eq(images[1], "https://img.example/001.c800x.jpg") + Assert.eq(images[2], "https://img.example/002.c800x.jpg") +end + +do + local images, err = Protocol.chapterImages({ + chapter = { + contents = { + { url = "https://img.example/a.webp.c1500x.webp" }, + { url = "https://img.example/b.jpg.c2000x.jpg" }, + }, + }, + }) + Assert.is_nil(err) + Assert.eq(images[1], "https://img.example/a.jpg.c800x.jpg") + Assert.eq(images[2], "https://img.example/b.jpg.c800x.jpg") +end + +do + local images, err = Protocol.chapterImages({ + chapter = { + contents = { + { url = "https://img.example/001.webp" }, + { url = "https://img.example/002.webp" }, + }, + }, + }) + Assert.is_nil(err) + Assert.eq(images[1], "https://img.example/001.webp") + Assert.eq(images[2], "https://img.example/002.webp") +end + +do + local images, err = Protocol.chapterImages({}) + Assert.is_nil(images) + Assert.eq(err, "章节图片解析失败") +end + +do + local images, err = Protocol.chapterImages({ + chapter = { contents = { { url = "not-a-url" } }, words = { 0 } }, + }) + Assert.is_nil(images) + Assert.eq(err, "章节图片解析失败") +end diff --git a/tests/copymanga/setting_spec.lua b/tests/copymanga/setting_spec.lua new file mode 100644 index 0000000..d895ac6 --- /dev/null +++ b/tests/copymanga/setting_spec.lua @@ -0,0 +1,52 @@ +--[[-- +站点选择保留已有配置,自定义非法地址不保存;登录离线立即反馈。 + +@module tests.moonsource_copymanga.setting_spec +--]] + +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +Themed.install() +local cfg = { base_url = "https://api.example", token = "keep" } +local saves, reloads = 0, 0 +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() saves = saves + 1 end, +} +package.loaded["source.registry"] = { reload = function() reloads = reloads + 1 end } +package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end } +local Setting = require("moonsource_copymanga.setting") +local rows = Setting.rows() +rows[1](500).callback() +local sheet = Themed.last("sheet") +Assert.eq(sheet.items[1].text, "https://www.mangacopy.com") +Assert.eq(sheet.items[2].text, "https://www.copy4000.com") +Assert.eq(sheet.items[3].text, "https://api.manga2026.xyz") +Themed.choose(sheet, 2) +Assert.eq(cfg.base_url, "https://www.copy4000.com") +Assert.eq(cfg.token, "keep") +Assert.eq(saves, 1) +Assert.eq(reloads, 1) + +rows[1](500).callback() +Assert.eq(Themed.last("sheet").items[2].variant, "primary") +Themed.choose(Themed.last("sheet"), 4) +Themed.last("input").callback("https://site.example/path") +Assert.eq(cfg.base_url, "https://www.copy4000.com") +Assert.eq(saves, 1) +Assert.eq(Themed.last("toast").text, "站点地址无效") +Themed.last("input").callback(" https://api.example/ ") +Assert.eq(cfg.base_url, "https://api.example") +Assert.eq(cfg.token, "keep") + +rows[1](500).callback() +Themed.choose(Themed.last("sheet"), 3) +Assert.eq(cfg.base_url, "https://api.manga2026.xyz") +Assert.eq(cfg.token, "keep") + +local network = require("ui/network/manager") +network.isConnected = function() return false end +rows[2](500).callback() +Themed.last("input").callback("user", "pass") +Assert.eq(Themed.last("toast").text, "网络不可用,请先连接 Wi-Fi") +Assert.is_nil(Themed.last("progress_dialog")) diff --git a/tests/copymanga/sync_spec.lua b/tests/copymanga/sync_spec.lua new file mode 100644 index 0000000..fec2181 --- /dev/null +++ b/tests/copymanga/sync_spec.lua @@ -0,0 +1,91 @@ +--[[-- +拷贝漫画书架同步:复用 Shelf 的本地加删上行与远端对账。 + +@module tests.moonsource_copymanga.sync_spec +--]] + +local Assert = require("support.assert") + +local fake_client = {} +local calls = {} +local finalized = {} + +local function stub(name, factory) + package.preload[name] = factory + package.loaded[name] = nil +end + +stub("book.books_db", function() + return { + pendingDeleteIds = function() return { "gone-comic" } end, + pendingShelfAddIds = function() return { "new-comic" } end, + markSynced = function(_source_id, stable_id) + calls[#calls + 1] = "synced:" .. stable_id + return true + end, + get = function() return nil end, + remove = function(_, stable_id) + finalized[#finalized + 1] = stable_id + return true + end, + reconcile = function() + calls[#calls + 1] = "reconcile" + return true, 0 + end, + } +end) +stub("utils.settings", function() + return { + getSource = function() return { token = "tok" } end, + saveSource = function() end, + } +end) +stub("moonsource_copymanga.auth", function() + return { hasSession = function() return true end } +end) +stub("moonsource_copymanga.client", function() + return { + new = function() return fake_client end, + headers = function() return {} end, + normalizeBaseUrl = function(url) return url end, + } +end) + +fake_client.removeFromShelfAsync = function(_client, stable_id, cb) + calls[#calls + 1] = "remove:" .. stable_id + cb({ code = 200 }) + return { cancel = function() end } +end +fake_client.addToShelfAsync = function(_client, stable_id, cb) + calls[#calls + 1] = "add:" .. stable_id + cb({ code = 200 }) + return { cancel = function() end } +end +fake_client.shelfSyncAsync = function(_client, cb) + calls[#calls + 1] = "shelf" + cb({}) + return { cancel = function() end } +end + +package.loaded["moonsource_copymanga.source"] = nil +local src = require("moonsource_copymanga.source").new() + +local result, err +src:syncBooksAsync({}, function(r, e) result, err = r, e end) +Assert.is_nil(err) +Assert.eq(calls[1], "remove:gone-comic") +Assert.eq(calls[2], "shelf") +Assert.eq(calls[3], "add:new-comic") +Assert.eq(calls[4], "synced:new-comic") +Assert.eq(calls[5], "shelf") +Assert.eq(calls[6], "reconcile") +Assert.eq(finalized[1], "gone-comic") +Assert.eq(result.pushed, 2) + +calls = {} +src:syncBooksAsync({ dirty_only = true }, function(r, e) result, err = r, e end) +Assert.is_nil(err) +Assert.eq(calls[1], "remove:gone-comic") +Assert.eq(calls[2], "add:new-comic") +Assert.eq(calls[3], "synced:new-comic") +Assert.eq(result.pushed, 2) diff --git a/tests/copymanga/toc_spec.lua b/tests/copymanga/toc_spec.lua new file mode 100644 index 0000000..3208ab6 --- /dev/null +++ b/tests/copymanga/toc_spec.lua @@ -0,0 +1,70 @@ +--[[-- +拷贝漫画目录缓存:uid ↔ idx 与全书 fraction。 + +@module tests.moonsource_copymanga.toc_spec +--]] + +local Assert = require("support.assert") + +local store = {} +local now = 1000 +local original_time = os.time +os.time = function() return now end +package.preload["book.books_db"] = function() + return { + getToc = function(source_id, stable_id, max_age) + local row = store[source_id .. "\31" .. stable_id] + if not row or (max_age and now - row.at >= max_age) then return nil end + return row.payload, row.at + end, + setToc = function(source_id, stable_id, payload) + store[source_id .. "\31" .. stable_id] = { payload = payload, at = now } + return true + end, + } +end +package.preload["json"] = function() + return { + decode = require("support.json_stub").decode, + encode = require("support.json_stub").encode, + } +end + +package.loaded["source.toc"] = nil +local Toc = require("source.toc") + +local list = { + { idx = 1, uid = "u1", title = "第一话" }, + { idx = 2, uid = "u2", title = "第二话" }, + { idx = 3, uid = "u3", title = "第三话" }, +} + +do + Assert.is_true(Toc.put("copymanga", "comic-a", list)) + Assert.eq(Toc.uid("copymanga", "comic-a", 2), "u2") + Assert.eq(Toc.index("copymanga", "comic-a", "u3"), 3) + Assert.is_nil(Toc.uid("copymanga", "comic-a", 99)) + Assert.is_nil(Toc.index("copymanga", "comic-a", "missing")) + Assert.is_nil(Toc.index("copymanga", "comic-a", nil)) + -- 数字 uid 与字符串 uid 同一键 + local numbered = { { idx = 1, uid = 10, title = "话" } } + Assert.is_true(Toc.put("copymanga", "comic-n", numbered)) + Assert.eq(Toc.index("copymanga", "comic-n", 10), 1) + Assert.eq(Toc.index("copymanga", "comic-n", "10"), 1) +end + +do + Assert.eq(Toc.wholeFraction("copymanga", "comic-a", 1, 0), 0) + Assert.eq(Toc.wholeFraction("copymanga", "comic-a", 2, 0), 1 / 3) + Assert.eq(Toc.wholeFraction("copymanga", "comic-a", 3, 0.5), (2 + 0.5) / 3) + Assert.is_nil(Toc.wholeFraction("copymanga", "missing", 1, 0)) +end + +do + Toc.clear() + Assert.eq(Toc.index("copymanga", "comic-a", "u1"), 1) +end + +now = now + 6 * 60 * 60 +Assert.eq(Toc.read("copymanga", "comic-a")[1].uid, "u1", "目录不做时间保鲜") +os.time = original_time diff --git a/tools/package.sh b/tools/package.sh new file mode 100755 index 0000000..8c53048 --- /dev/null +++ b/tools/package.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# 打包本仓库的书源插件:moonsource-<名字>.koplugin-.zip,同时生成 SHA256SUMS。 +# 用法:tools/package.sh [OUT_DIR] (OUT_DIR 默认 dist/) +# 打包时把 <包名>/version.lua 里的版本占位符换成发布版本;剔除 *.md、.DS_Store、*~。 +set -eu +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +VERSION="${1:?用法:tools/package.sh [OUT_DIR]}" +OUT="${2:-$ROOT/dist}" +case "$OUT" in /*) ;; *) OUT="$PWD/$OUT" ;; esac + +NAME="$(cd "$ROOT" && ls -d moonsource-*.koplugin | head -n 1)" +[ -f "$ROOT/$NAME/main.lua" ] || { echo "找不到插件目录:$NAME" >&2; exit 1; } +PKG="$(echo "${NAME%.koplugin}" | tr - _)" + +mkdir -p "$OUT" +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT +rsync -a --exclude '*.md' --exclude '.DS_Store' --exclude '*~' "$ROOT/$NAME/" "$STAGE/$NAME/" +sed "s/@VERSION@/$VERSION/" "$ROOT/$NAME/$PKG/version.lua" > "$STAGE/$NAME/$PKG/version.lua" +ZIP="$OUT/$NAME-$VERSION.zip" +rm -f "$ZIP" +(cd "$STAGE" && zip -qr "$ZIP" "$NAME") +echo "Packaged $ZIP" + +(cd "$OUT" && { command -v sha256sum >/dev/null && sha256sum ./*.zip || shasum -a 256 ./*.zip; } | sed 's# \./# #' > SHA256SUMS) diff --git a/tools/release.sh b/tools/release.sh new file mode 100755 index 0000000..568693e --- /dev/null +++ b/tools/release.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# 发布本书源:校验更新日志 → 本地打包 → 打轻量标签 v<版本> → 推送当前分支和标签。 +# Release 由 .github/workflows/release.yml 在标签推上去之后创建,日志取 CHANGELOG.md 里精确的「## <版本>」一节。 +# 用法:tools/release.sh +set -eu +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" +VERSION="${1:?用法:tools/release.sh }" + +case "$VERSION" in + v*) echo "版本不要带 v:$VERSION" >&2; exit 1 ;; +esac +printf '%s\n' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([.+-].*)?$' \ + || { echo "版本应为 MAJOR.MINOR.PATCH:$VERSION" >&2; exit 1; } + +grep -qx "## ${VERSION}" CHANGELOG.md \ + || { echo "CHANGELOG.md 缺少单独一行「## ${VERSION}」" >&2; exit 1; } + +if [ -n "$(git status --porcelain)" ]; then + echo "工作区不干净,先提交再发布" >&2 + exit 1 +fi + +tools/package.sh "$VERSION" dist + +TAG="v${VERSION}" +if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then + HAVE="$(git rev-parse "${TAG}^{}")" + HEAD="$(git rev-parse HEAD)" + if [ "$HAVE" != "$HEAD" ]; then + echo "标签 ${TAG} 已经指向别的提交" >&2 + exit 1 + fi +else + git tag "$TAG" +fi + +BRANCH="$(git rev-parse --abbrev-ref HEAD)" +git push origin "$BRANCH" +git push origin "$TAG" +echo "已推送 ${TAG}。Actions 会打包并创建 Release。" diff --git a/tools/run-tests.sh b/tools/run-tests.sh new file mode 100755 index 0000000..ec1706e --- /dev/null +++ b/tools/run-tests.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# 离线单元测试:借用月读仓库的测试运行器与桩,把本仓库的插件目录和 tests/ 加进 LUA_PATH。 +# 用法:MOON_DIR=/path/to/moon tools/run-tests.sh [spec 文件…] +set -euo pipefail +here="$(cd "$(dirname "$0")/.." && pwd)" +: "${MOON_DIR:?请把 MOON_DIR 设为月读仓库路径}" +paths="$here/tests/?.lua;$here/tests/?/init.lua" +for plugin in "$here"/moonsource-*.koplugin; do + paths="$paths;$plugin/?.lua" +done +export LUA_PATH="$paths;;" +if [ "$#" -eq 0 ]; then + set -- $(find "$here/tests" -name '*_spec.lua' | sort) +fi +cd "$MOON_DIR" +exec luajit tests/run.lua "$@"