From 28215d4989d1b42608253025d66637b2579ac0c7 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-iread.koplugin/_meta.lua | 5 + moonsource-iread.koplugin/main.lua | 9 + moonsource-iread.koplugin/moon_source.lua | 17 + .../moonsource_iread/README.md | 19 + .../moonsource_iread/_meta.lua | 15 + .../moonsource_iread/client.lua | 385 ++++++++++ .../moonsource_iread/l10n/en.lua | 33 + .../moonsource_iread/l10n/zh_TW.lua | 33 + .../moonsource_iread/loadmeta.lua | 5 + .../moonsource_iread/mapper.lua | 78 ++ .../moonsource_iread/setting.lua | 183 +++++ .../moonsource_iread/source.lua | 366 ++++++++++ .../moonsource_iread/version.lua | 4 + tests/iread/async_spec.lua | 237 ++++++ tests/iread/iread_spec.lua | 205 ++++++ tests/iread/setting_spec.lua | 95 +++ tests/iread/source_spec.lua | 233 ++++++ tools/package.sh | 25 + tools/release.sh | 41 ++ tools/run-tests.sh | 16 + 25 files changed, 2822 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-iread.koplugin/_meta.lua create mode 100644 moonsource-iread.koplugin/main.lua create mode 100644 moonsource-iread.koplugin/moon_source.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/README.md create mode 100644 moonsource-iread.koplugin/moonsource_iread/_meta.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/client.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/l10n/en.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/l10n/zh_TW.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/loadmeta.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/mapper.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/setting.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/source.lua create mode 100644 moonsource-iread.koplugin/moonsource_iread/version.lua create mode 100644 tests/iread/async_spec.lua create mode 100644 tests/iread/iread_spec.lua create mode 100644 tests/iread/setting_spec.lua create mode 100644 tests/iread/source_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..0b70808 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 更新日志 + +## 0.0.1 + +- 「iRead」书源拆成独立仓库,独立发版、独立更新;原来所有书源同版本一起更新的做法取消。 +- 检查更新与自动更新只管本书源:月读「书库 → 更新」里每个书源各有一项,只提示、不静默安装,装完重启 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..d9a85c1 --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# 月读书源:iRead + +给月读增加「iRead」在线书源的 KOReader 插件。本仓库只含这一个插件,独立维护、独立发版,全部书源见 [moon-source 组织](https://git.garfieldho.me/moon-source)。 + +## 免责声明 + +- 本仓库与「iRead」官方**没有任何关联**,所有商标、书名、内容归原权利人所有。 +- 插件只是在用户自己的账号、自己的设备上,按用户本人已有的权限读取内容;不提供、不分发任何书籍内容,也不绕过付费。 +- 使用可能违反对应平台的用户协议,账号可能被限制或封禁。是否使用、风险如何,由使用者自行判断并承担。 +- 权利人认为本仓库内容有问题,请通过仓库 issue 联系,核实后会及时处理。 + +## 安装 + +1. 先装好月读。 +2. 从 [Release](../../releases) 下载 `moonsource-iread.koplugin-<版本>.zip`,解压出 `moonsource-iread.koplugin` 目录,整个复制到 KOReader 的 `plugins/` 下。 +3. 重启 KOReader,在月读的书源列表里启用。 + +书源 id 是 `iread`,与旧版(合并仓库、内置书源)相同,书架、进度、登录配置、缓存沿用原有数据,无需迁移。 + +## 更新 + +在月读的「书库 → iRead 更新」里有「检查书源插件更新」和「自动检查书源插件更新」(默认开,每 24 小时一次,只提示、不静默安装)。 +本插件只检查并更新自己(本仓库的 Release),校验值取自 Release 的 `SHA256SUMS`,装完重启 KOReader。 + +> 从旧的合并仓库 `GarfieldTony/moon-source` 迁移:旧仓库的更新入口已停用,请直接从本仓库下载最新包覆盖安装。 + +## 发布 + +推送 `vX.Y.Z` 标签(带 `-` 的如 `v1.2.0-rc.1` 为预发布),Forgejo Actions 会打包 `moonsource-iread.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/iread/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-iread.koplugin/_meta.lua b/moonsource-iread.koplugin/_meta.lua new file mode 100644 index 0000000..83b6bff --- /dev/null +++ b/moonsource-iread.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:iRead"), + description = _("给月读增加「iRead」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-iread.koplugin/main.lua b/moonsource-iread.koplugin/main.lua new file mode 100644 index 0000000..4264e25 --- /dev/null +++ b/moonsource-iread.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_iread", + is_doc_only = false, +} diff --git a/moonsource-iread.koplugin/moon_source.lua b/moonsource-iread.koplugin/moon_source.lua new file mode 100644 index 0000000..728d713 --- /dev/null +++ b/moonsource-iread.koplugin/moon_source.lua @@ -0,0 +1,17 @@ +--[[-- +月读第三方书源描述:iRead。契约见月读 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_iread.source").meta() end, + new = function() return require("moonsource_iread.source").new() end, + setting = lazy("moonsource_iread.setting"), +} diff --git a/moonsource-iread.koplugin/moonsource_iread/README.md b/moonsource-iread.koplugin/moonsource_iread/README.md new file mode 100644 index 0000000..70d67f7 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/README.md @@ -0,0 +1,19 @@ +# iRead(爱阅读) + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 个人 Token 登录 | 支持 | 保存前校验;与 Cookie 互斥 | +| 浏览器登录与 Cookie 导入 | 支持 | 手动粘贴或扩展回传;完整扩展握手未实测 | +| 设备密码与扫码登录 | 不支持 | 在 iRead 官网完成账号登录 | +| 搜索与发现 | 支持 | 游客公共书源、账号配置书源及动态发现入口 | +| 发现分页 | 部分支持 | 仅支持已核实的页面占位符;无占位符只取一批,不执行规则 JavaScript | +| 书架拉取 | 支持 | 读取个人书架 | +| 书架新增与移出 | 已实现,未实测 | 收藏开关写前查架、写后回读,失败保留待同步状态 | +| 目录与文字正文 | 支持 | 取决于服务端规则可用性;上游失效或空正文明确失败 | +| 漫画与图片正文 | 不支持 | 未实现图片落地,不把空正文作为成功缓存 | +| 付费内容 | 未验证 | 取决于上游规则、登录和购买权限,不保证所有付费书源可读 | +| 章节与全本缓存 | 支持 | 已缓存章节可离线阅读 | +| 阅读进度同步 | 部分支持 | 仅章节位置;同章保留远端原位置,不伪造跨排版精确坐标 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 书评、章评、段评与回复 | 不支持 | 当前 Web 契约未找到可验证接口,不代表上游网站没有评论 | +| 账号切换与凭据续期 | 部分支持 | 新凭据须先退出旧登录并清理本地数据,未同步记录会丢失 | diff --git a/moonsource-iread.koplugin/moonsource_iread/_meta.lua b/moonsource-iread.koplugin/moonsource_iread/_meta.lua new file mode 100644 index 0000000..fafb247 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +@module moonsource_iread._meta +--]] + +local _ = require("l10n").get("moonsource_iread") + +return { + id = "iread", + name = _("iRead"), + type = "chapter", + description = _("iRead 书架与在线阅读"), + abilities = { _("搜索与发现"), _("书架同步"), _("进度同步") }, +} diff --git a/moonsource-iread.koplugin/moonsource_iread/client.lua b/moonsource-iread.koplugin/moonsource_iread/client.lua new file mode 100644 index 0000000..aff5ca1 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/client.lua @@ -0,0 +1,385 @@ +--[[-- +iRead(iread.ankio.net)HTTP 客户端(仅异步)。 + +鉴权是个人 Token(`Authorization: Bearer <64 位十六进制>`,在网站「个人 Token」页创建);接口一律 POST 表单, +回包是 `{ code, msg, data }`,`code == 200` 才算成功。注意服务端对无效 Token 不报 401,而是当游客处理, +所以书架为空时要另调 /user/home 确认登录态,免得把「Token 失效」当成「书架被清空」。 + +书架行(BookDetailModel)就是服务端的书记录:章节、正文、进度接口都要把整行原样带回去, +所以这里的请求都以书架行为参数。 + +@module koplugin.book.moonsource_iread.client +--]] + +local JSON = require("json") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_iread") + +local Client = {} + +local SOURCE_ID = "iread" +Client.BASE = "https://iread.ankio.net" + +---@class IReadCredential +---@field token string|nil 个人 Token(Bearer) +---@field cookie string|nil 网页登录 Cookie 请求头 + +--- 已保存的登录凭据,Token 优先;没登录返回 nil。 +---@return IReadCredential|nil +function Client.credential() + local cfg = require("utils.settings").getSource(SOURCE_ID) + if type(cfg.token) == "string" and cfg.token ~= "" then return { token = cfg.token } end + if type(cfg.cookie) == "string" and cfg.cookie ~= "" then return { cookie = cfg.cookie } end + return nil +end + +--- 发请求用的凭据是不是当前已保存的那份(校验新凭据时的回包不能动已保存的登录态)。 +---@param cred IReadCredential +---@return boolean +local function isCurrent(cred) + local saved = Client.credential() + if not saved then return cred.token == nil and cred.cookie == nil end + return saved.token == cred.token and saved.cookie == cred.cookie +end + +--- 嵌套表按 PHP 的 `a[b]` 写法摊平成表单键(数组用 0 基下标,PHP 侧才是列表);布尔 / 数字转字符串,nil 丢弃。 +---@param out table +---@param key string +---@param value any +local function flatten(out, key, value) + if type(value) == "table" then + local is_list = #value > 0 + for k, v in pairs(value) do + flatten(out, key .. "[" .. (is_list and (k - 1) or tostring(k)) .. "]", v) + end + elseif value ~= nil and value ~= JSON.util.null then + out[key] = tostring(value) + end +end + +---@param form table +---@return string +local function encode(form) + local flat = {} + for key, value in pairs(form) do flatten(flat, key, value) end + return Text.formEncode(flat) +end + +--- 解回包:返回 data。401 / 403 视为登录失效。 +---@param raw string|nil +---@param err any +---@param cred IReadCredential 发请求时用的凭据 +---@return any|nil data, string|nil err, table|nil wire 整包(分页接口的 total / hasMore 在 data 外面) +function Client.decode(raw, err, cred) + if err then return nil, tostring(err) end + if not raw then return nil, _("请求失败") end + local ok, wire = pcall(JSON.decode, raw, JSON.decode.simple) + if not ok or type(wire) ~= "table" then return nil, _("响应无效") end + local code = tonumber(wire.code) + if code == 200 then + return wire.data == nil and {} or wire.data, nil, wire + end + if (code == 401 or code == 403) and (cred.token or cred.cookie) and isCurrent(cred) then + return nil, require("source.auth").expire(SOURCE_ID, _("请按这个做:\n1. 点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → iRead → iRead 账号」。\n2. 用电脑浏览器打开 https://iread.ankio.net/#/system/token ,登录你的账号。\n3. 在页面上新建一个个人 Token,复制它。\n4. 回到月读的输入框,把 Token 贴进去,点「登录」。\n\n如果平时用的是浏览器扩展,不要新建 Token,改做下面这些:\n") + .. require("source.cookie_login").relogin(_("iRead"), "https://iread.ankio.net/#/system/token")) + end + return nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("请求失败") +end + +---@param path string +---@param form table +---@param cred IReadCredential +---@param ratio number 超时倍率 +---@param cb fun(data: any|nil, err: string|nil, res: table|nil, wire: table|nil) +---@param session string|nil 服务端会话 Cookie(搜索结果存在会话里,轮询必须带回) +---@return { cancel: fun() } +local function post(path, form, cred, ratio, cb, session) + local cookie = session and require("source.cookie_login").parse((cred.cookie or "") .. "; " .. session) + or cred.cookie + return Request.post(Client.BASE .. path, encode(form), { + accept = "application/json", + headers = { Cookie = cookie, Authorization = cred.token and ("Bearer " .. cred.token), + ["X-Requested-With"] = "XMLHttpRequest" }, + content_type = "application/x-www-form-urlencoded", + timeout = require("http.timeout").net(ratio), + }, function(raw, err, res) + local data, decode_err, wire = Client.decode(raw, err, cred) + cb(data, decode_err, res, wire) + end) +end + +--- 读取接口允许游客;已登录时使用用户配置的书源。 +---@param path string +---@param form table +---@param ratio number +---@param cb fun(data: any|nil, err: string|nil, res: table|nil) +---@param session string|nil +---@return { cancel: fun() } +local function call(path, form, ratio, cb, session) + local cred = Client.credential() or {} + return post(path, form, cred, ratio, function(data, err, res, wire) + if not isCurrent(cred) then cb(nil, _("登录状态已变化,请重试")); return end + cb(data, err, res, wire) + end, session) +end + +--- 校验凭据并取账号信息(设置页用,凭据由调用方显式给)。 +---@param cred IReadCredential +---@param cb fun(user: table|nil, err: string|nil) +---@return { cancel: fun() } +function Client.userAsync(cred, cb) + return post("/user/home", {}, cred, 0.5, function(data, err) + if type(data) ~= "table" or type(data.nickname) ~= "string" or data.nickname == "" then + cb(nil, err or _("iRead 账号信息为空")); return + end + if isCurrent(cred) then require("source.auth").ok(SOURCE_ID) end + cb(data) + end) +end + +--- 列表响应必须是连续数组;坏行不能被 ipairs 静默丢掉并参与书架对账。 +---@param rows any +---@param field string +---@return boolean +local function validRows(rows, field) + if type(rows) ~= "table" then return false end + local count = 0 + for key, row in pairs(rows) do + if type(key) ~= "number" or key < 1 or key % 1 ~= 0 + or type(row) ~= "table" or type(row[field]) ~= "string" or row[field] == "" then return false end + count = count + 1 + end + return count == #rows +end + +--- 个人书架(服务端书记录原行)。空书架要另验登录态。 +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.shelfAsync(cb) + local cred = Client.credential() + if not cred then return require("source.base").defer(cb, nil, _("未登录 iRead")) end + local job, cancelled, pending = nil, false, true + local first = post("/book/list", {}, cred, 0.5, function(data, err) + pending = false + if cancelled then return end + if not isCurrent(cred) then cb(nil, _("登录状态已变化,请重试")); return end + if not validRows(data, "name") then cb(nil, err or _("响应无效")); return end + if #data > 0 then + require("source.auth").ok(SOURCE_ID) + cb(data); return + end + job = Client.userAsync(cred, function(user, user_err) + if cancelled then return end + if not isCurrent(cred) then cb(nil, _("登录状态已变化,请重试")); return end + if not user then cb(nil, user_err); return end + cb({}) + end) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 目录:章节对象数组,顺序即阅读顺序。服务端分页(每页最多 200),翻到 hasMore 为假。 +---@param row table 书架行(必须含 id 字段) +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.chaptersAsync(row, cb) + local all, job, cancelled = {}, nil, false + local function page(n) + job = call("/book/chapters", { id = row.id, page = n, pageSize = 200 }, 1, function(data, err, _res, wire) + if cancelled then return end + if not validRows(data, "title") then cb(nil, err or _("响应无效")); return end + for _idx, chapter in ipairs(data) do all[#all + 1] = chapter end + if #data > 0 and wire and wire.hasMore then + -- 服务端一直说 hasMore 时不能无限翻:最多 100 页,超了报错,不交残缺目录。 + if n >= 100 then cb(nil, _("响应无效")); return end + page(n + 1); return + end + if #all == 0 then cb(nil, _("iRead 目录为空")); return end + cb(all) + end) + end + page(1) + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 一章正文(纯文本)。index 是 0 基章序号。 +---@param row table 书架行(必须含 id 字段) +---@param index integer +---@param cb fun(text: string|nil, err: string|nil) +---@return { cancel: fun() } +function Client.contentAsync(row, index, cb) + return call("/book/chapter", { id = row.id, index = index }, 1, + function(data, err) + local text = type(data) == "table" and data.content + if type(text) ~= "string" or text == "" then cb(nil, err or _("iRead 章节内容为空")); return end + cb(text) + end) +end + +--- 上报阅读位置:服务端用整行覆盖记录,所以带回原行,只改位置字段。 +---@param row table 书架行(必须含 id 字段) +---@param pos { index: integer, title: string|nil, offset: integer } +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Client.saveProgressAsync(row, pos, cb) + if not Client.credential() then return require("source.base").defer(cb, nil, _("未登录 iRead")) end + local body = { id = row.id, durChapterIndex = pos.index, durChapterPos = pos.offset, durChapterTitle = pos.title or "" } + local cancelled, job, pending = false, nil, true + local first = call("/book/process", body, 0.5, function(data, err) + pending = false + if cancelled then return end + if data == nil then cb(nil, err); return end + job = Client.shelfAsync(function(rows, reason) + if cancelled then return end + if not rows then cb(nil, reason); return end + for _idx, saved in ipairs(rows) do + if saved.name == row.name and tonumber(saved.durChapterIndex) == pos.index + and tonumber(saved.durChapterPos) == pos.offset then cb(true); return end + end + cb(nil, _("iRead 阅读进度更新未生效")) + end) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +local SEARCH_INTERVAL = 2 +local SEARCH_TRIES = 30 + +--- 搜索:官网的协议是「提交 → 轮询」,两步要用同一个会话 Cookie(否则取结果 500)。POST /book/search 返回 task(各书源并行搜), +--- 再每 2 秒 POST /book/search/result 取增量 result[] 直到 remaining 为 0。回调完整行数组(同书架行)。 +---@param form table 提交表单(搜索是 bookname,发现是 type / url / id) +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +local function runAsync(form, cb) + local cred = Client.credential() or {} + local UIManager = require("ui/uimanager") + local job, tick, done = nil, nil, false + local rows, seen, tries = {}, {}, 0 + local function finish(data, err) + done = true + cb(data, err) + end + local function poll(task, session) + if done then return end + if not isCurrent(cred) then finish(nil, _("登录状态已变化,请重试")); return end + tries = tries + 1 + local pending = true + local inner = post("/book/search/result", { task = task }, cred, 0.5, function(data, err) + pending = false + if done then return end + if not isCurrent(cred) then finish(nil, _("登录状态已变化,请重试")); return end + local remaining = type(data) == "table" and tonumber(data.remaining) + if not remaining or remaining < 0 or remaining % 1 ~= 0 or not validRows(data.result, "name") then + finish(nil, err or _("响应无效")); return + end + for _idx, row in ipairs(data.result) do + if not seen[row.name] then + seen[row.name] = true + rows[#rows + 1] = row + end + end + if remaining == 0 then finish(rows); return end + if tries >= SEARCH_TRIES then finish(nil, _("iRead 搜索超时,请重试")); return end + tick = function() poll(task, session) end + UIManager:scheduleIn(SEARCH_INTERVAL, tick) + end, session) + if pending then job = inner end + end + local pending = true + local first = post("/book/search", form, cred, 0.5, function(data, err, res) + pending = false + if done then return end + if not isCurrent(cred) then finish(nil, _("登录状态已变化,请重试")); return end + if type(data) ~= "table" or type(data.task) ~= "string" or data.task == "" then + finish(nil, err or _("响应无效")); return + end + local cookies = {} + for _idx, value in ipairs(Request.headerAll(res, "Set-Cookie")) do + cookies[#cookies + 1] = value:match("^([^;]+)") + end + poll(data.task, table.concat(cookies, "; ")) + end) + if pending then job = first end + return { + cancel = function() + done = true + if tick then UIManager:unschedule(tick) end + if job then job.cancel() end + end, + } +end + +---@param keyword string +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.searchAsync(keyword, cb) + return runAsync({ bookname = keyword }, cb) +end + +--- 书源「发现」页的一个入口(规则里的 url 模板),回包同搜索。 +---@param source_id integer +---@param url string +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.exploreAsync(source_id, url, cb) + return runAsync({ type = "explore", url = url, id = source_id }, cb) +end + +--- 服务端当次挑出的一个书源的发现规则(每次调用换一个)。 +---@param cb fun(rules: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client.exploreRulesAsync(cb) + return call("/kindle/exploreRules", {}, 0.5, function(rules, err) + if not validRows(rules, "bookSourceName") then cb(nil, err or _("响应无效")); return end + for _idx, rule in ipairs(rules) do + if type(rule.id) ~= "number" or rule.id < 1 or rule.id % 1 ~= 0 + or rule.exploreUrl ~= nil and type(rule.exploreUrl) ~= "table" then + cb(nil, _("响应无效")); return + end + -- 分类里常夹着没有 url 的分隔标题(如 "↑ *** ↑"),丢掉,不当作整包无效 + local entries = {} + for _entry_idx, entry in ipairs(rule.exploreUrl or {}) do + if type(entry) == "table" and type(entry.title) == "string" and entry.title ~= "" + and type(entry.url) == "string" and entry.url ~= "" then + entries[#entries + 1] = entry + end + end + rule.exploreUrl = entries + end + cb(rules) + end) +end + +--- 切换收藏状态。调用方必须先读书架判断是否需要切换,并在写后确认状态。 +--- 已在书库的书(row.id > 0)只传 id;未入库的传完整 hit 数据。 +---@param row table +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Client.favouriteAsync(row, cb) + if not Client.credential() then return require("source.base").defer(cb, nil, _("未登录 iRead")) end + local form + if row.id and tonumber(row.id) > 0 then + form = { id = row.id } + else + form = { id = row.id or 0, sourceId = row.sourceId or 0, bookUrl = row.bookUrl or "", + tocUrl = row.tocUrl or "", name = row.name or "", author = row.author or "", + coverUrl = row.coverUrl or "", intro = row.intro or "", kind = row.kind or "", + originName = row.originName or row.origin or "", latestChapterTitle = row.latestChapterTitle or "", + wordCount = row.wordCount or "", totalChapterNum = row.totalChapterNum or 0 } + end + return call("/book/favourite", form, 0.5, function(data, err) cb(data ~= nil or nil, err) end) +end + +return Client diff --git a/moonsource-iread.koplugin/moonsource_iread/l10n/en.lua b/moonsource-iread.koplugin/moonsource_iread/l10n/en.lua new file mode 100644 index 0000000..90ed5de --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/l10n/en.lua @@ -0,0 +1,33 @@ +return { + ["登录状态已变化,请重试"] = "The login session changed. Please retry.", + ["已登录:%1"] = "Signed in: %1", + ["章节目录保存失败"] = "Failed to save chapter list", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "Press F12, open Network, refresh, and copy the entire Cookie request header", + ["缺少阅读章节位置"] = "Missing Legado chapter position", + ["iRead"] = "iRead", + ["iRead 账号"] = "iRead account", + ["iRead 账号信息为空"] = "iRead account info is empty", + ["iRead 个人 Token"] = "iRead personal token", + ["iRead 登录 Cookie"] = "iRead sign-in cookie", + ["无法确认是否为同一 iRead 账号,请先退出当前账号再登录"] = "Cannot verify that this is the same iRead account. Sign out of the current account before signing in.", + ["iRead 搜索超时,请重试"] = "iRead search timed out. Please retry.", + ["iRead 书架更新未生效"] = "The iRead shelf update was not applied.", + ["iRead 阅读进度更新未生效"] = "The iRead reading progress update was not applied.", + ["iRead 图片正文暂不支持,请使用网页版阅读"] = "iRead image content is not supported yet. Please use the website to read it.", + ["请按这个做:\n1. 点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → iRead → iRead 账号」。\n2. 用电脑浏览器打开 https://iread.ankio.net/#/system/token ,登录你的账号。\n3. 在页面上新建一个个人 Token,复制它。\n4. 回到月读的输入框,把 Token 贴进去,点「登录」。\n\n如果平时用的是浏览器扩展,不要新建 Token,改做下面这些:\n"] = "Do this:\n1. Tap Sign in again on this message. If there is no button, open Settings → Library → Account → iRead → iRead account.\n2. On a computer, open https://iread.ankio.net/#/system/token and sign in.\n3. Create a personal token on that page and copy it.\n4. Paste the token into the box in 月读 and tap Sign in.\n\nIf you normally use the browser extension, do not create a token. Do the following instead:\n", + ["iRead 目录为空"] = "iRead table of contents is empty", + ["iRead 章节内容为空"] = "iRead chapter is empty", + ["打开 iread.ankio.net/#/system/token ,新建个人 Token 后粘贴到这里"] = "Open iread.ankio.net/#/system/token, create a personal token, and paste it here", + ["未登录 iRead"] = "Not signed in to iRead", + ["未登录 · 点此填写 Token"] = "Not signed in · tap to enter token", + ["没有读到 Token"] = "No token found", + ["确定退出 iRead 账号?"] = "Sign out of iRead?", + ["请先搜索这本书再加入书库"] = "Search for this book first, then add it to your library", + ["这本书不在 iRead 书架上"] = "This book is not on the iRead shelf", + ["换一批书源"] = "Switch source", + ["iRead 暂无发现入口"] = "iRead has no discover entries", + ["iRead 书架与在线阅读"] = "iRead shelf and online reading", + ["书架同步"] = "Shelf sync", + ["搜索与发现"] = "Search and discover", + ["进度同步"] = "Progress sync", +} diff --git a/moonsource-iread.koplugin/moonsource_iread/l10n/zh_TW.lua b/moonsource-iread.koplugin/moonsource_iread/l10n/zh_TW.lua new file mode 100644 index 0000000..6375755 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/l10n/zh_TW.lua @@ -0,0 +1,33 @@ +return { + ["登录状态已变化,请重试"] = "登入狀態已改變,請重試", + ["已登录:%1"] = "已登入:%1", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie"] = "按鍵盤 F12,點「網路」,重新整理網頁,複製請求標頭裡的整段 Cookie", + ["缺少阅读章节位置"] = "缺少閱讀章節位置", + ["iRead"] = "iRead", + ["iRead 账号"] = "iRead 帳號", + ["iRead 账号信息为空"] = "iRead 帳號資訊為空", + ["iRead 个人 Token"] = "iRead 個人 Token", + ["iRead 登录 Cookie"] = "iRead 登入 Cookie", + ["无法确认是否为同一 iRead 账号,请先退出当前账号再登录"] = "無法確認是否為同一 iRead 帳號,請先登出目前帳號再登入", + ["iRead 搜索超时,请重试"] = "iRead 搜尋逾時,請重試", + ["iRead 书架更新未生效"] = "iRead 書架更新未生效", + ["iRead 阅读进度更新未生效"] = "iRead 閱讀進度更新未生效", + ["iRead 图片正文暂不支持,请使用网页版阅读"] = "iRead 圖片正文暫不支援,請使用網頁版閱讀", + ["请按这个做:\n1. 点这个提示上的「重新登录」。没有按钮就打开「设置 → 书库 → 账号 → iRead → iRead 账号」。\n2. 用电脑浏览器打开 https://iread.ankio.net/#/system/token ,登录你的账号。\n3. 在页面上新建一个个人 Token,复制它。\n4. 回到月读的输入框,把 Token 贴进去,点「登录」。\n\n如果平时用的是浏览器扩展,不要新建 Token,改做下面这些:\n"] = "請按這個做:\n1. 點這個提示上的「重新登入」。沒有按鈕就打開「設定 → 書庫 → 帳號 → iRead → iRead 帳號」。\n2. 用電腦瀏覽器打開 https://iread.ankio.net/#/system/token ,登入你的帳號。\n3. 在頁面上新建一個個人 Token,複製它。\n4. 回到月讀的輸入框,把 Token 貼進去,點「登入」。\n\n如果平時用的是瀏覽器擴充功能,不要新建 Token,改做下面這些:\n", + ["iRead 目录为空"] = "iRead 目錄為空", + ["iRead 章节内容为空"] = "iRead 章節內容為空", + ["打开 iread.ankio.net/#/system/token ,新建个人 Token 后粘贴到这里"] = "打開 iread.ankio.net/#/system/token ,新建個人 Token 後貼到這裡", + ["未登录 iRead"] = "未登入 iRead", + ["未登录 · 点此填写 Token"] = "未登入 · 點此填寫 Token", + ["没有读到 Token"] = "沒有讀到 Token", + ["确定退出 iRead 账号?"] = "確定登出 iRead 帳號?", + ["请先搜索这本书再加入书库"] = "請先搜尋這本書再加入書庫", + ["这本书不在 iRead 书架上"] = "這本書不在 iRead 書架上", + ["换一批书源"] = "換一批書源", + ["iRead 暂无发现入口"] = "iRead 暫無發現入口", + ["iRead 书架与在线阅读"] = "iRead 書架與線上閱讀", + ["书架同步"] = "書架同步", + ["搜索与发现"] = "搜尋與發現", + ["进度同步"] = "進度同步", +} diff --git a/moonsource-iread.koplugin/moonsource_iread/loadmeta.lua b/moonsource-iread.koplugin/moonsource_iread/loadmeta.lua new file mode 100644 index 0000000..ea61720 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_iread._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-iread.koplugin/moonsource_iread/mapper.lua b/moonsource-iread.koplugin/moonsource_iread/mapper.lua new file mode 100644 index 0000000..d092eac --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/mapper.lua @@ -0,0 +1,78 @@ +--[[-- +iRead 数据映射(纯函数)。 + +书的身份是书名:服务端按(用户, 书名)唯一,换书源时 bookUrl / sourceId 会变而书名不变。 + +@module koplugin.book.moonsource_iread.mapper +--]] + +local Text = require("utils.text") + +local Mapper = {} + +local SOURCE_ID = "iread" + +---@param row table +---@return string|nil +local function cover(row) + local url = row.customCoverUrl + if type(url) ~= "string" or url == "" then url = row.coverUrl end + if type(url) ~= "string" or url == "" then return nil end + if url:sub(1, 2) == "//" then url = "https:" .. url end + return url +end + +--- 书架行 → Book[]。 +---@param rows table[] +---@return Book[] +function Mapper.shelfList(rows) + local out = {} + for _idx, row in ipairs(rows) do + if type(row.name) == "string" and row.name ~= "" then + out[#out + 1] = { + source_id = SOURCE_ID, + stable_id = row.name, + title = row.name, + authors = row.author, + category = row.kind, + intro = row.intro and Text.stripHtml(row.intro), + cover = cover(row), + meta = { source = { iread = row } }, + } + end + end + return out +end + +--- 书架行里的阅读位置(序号 0 基)。没读过返回 nil。 +---@param row table|nil +---@return { index: integer, title: string|nil, offset: integer }|nil +function Mapper.readPos(row) + local index = row and tonumber(row.durChapterIndex) + if not index then return nil end + local offset = tonumber(row.durChapterPos) or 0 + if index == 0 and offset == 0 and (tonumber(row.durChapterTime) or 0) <= 0 then return nil end + local title = row.durChapterTitle + return { index = index, title = type(title) == "string" and title ~= "" and title or nil, offset = offset } +end + +--- 目录:按服务端顺序,uid 是 0 基章序号(开章接口只要书 id 与序号)。 +---@param rows table[] +---@return BookChapter[] +function Mapper.toc(rows) + local toc = {} + for i, row in ipairs(rows) do + toc[i] = { idx = i, uid = tostring(i - 1), title = row.title } + end + return toc +end + +--- 正文:服务端给纯文本;规则偶尔带 HTML 标签,剥掉免得标签原样显示。 +---@param content string +---@return string +function Mapper.text(content) + if content:find("<%s*/?%a[^>]*>") then return Text.stripHtml(content) end + return content +end + +return Mapper diff --git a/moonsource-iread.koplugin/moonsource_iread/setting.lua b/moonsource-iread.koplugin/moonsource_iread/setting.lua new file mode 100644 index 0000000..2bffef1 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/setting.lua @@ -0,0 +1,183 @@ +--[[-- +iRead 源设置:登录。 + +两种进法:远程管理里的「浏览器登录」(浏览器扩展交网页 Cookie),或在 iread.ankio.net 创建「个人 Token」粘贴进来。 +两条路都先向服务端校验,通过才保存并重载源;Token 优先于 Cookie,换一种登录会清掉另一种。 + +@module koplugin.book.moonsource_iread.setting +--]] + +local _ = require("l10n").get("moonsource_iread") +local T = require("ffi/util").template + +local SOURCE_ID = "iread" +local Setting = {} + +---@return boolean +local function loggedIn() + return require("moonsource_iread.client").credential() ~= nil +end + +---@return string, boolean +function Setting.rowStatus() + local on = loggedIn() + return on and _("已登录") or _("未登录 · 点此填写 Token"), on +end + +--- 接受裸 Token,或带 `Bearer ` 前缀的整段。 +---@param input string +---@return string +function Setting.parseToken(input) + return (require("utils.text").trim(input):gsub("^[Bb]earer%s+", "")) +end + +---- 保留本站和有效父域 Cookie,不收 ankio.net 下其他站点的登录态。 +---@param payload table +---@return string +function Setting.fromPayload(payload) + local cookies = {} + for _idx, cookie in ipairs(type(payload.cookies) == "table" and payload.cookies or {}) do + local host = type(cookie) == "table" and type(cookie.domain) == "string" + and cookie.domain:gsub("^%.", ""):lower() + if host == "ankio.net" or host == "iread.ankio.net" then cookies[#cookies + 1] = cookie end + end + return require("source.cookie_login").fromPayload({ cookies = cookies }, "ankio.net") +end + +--- 校验凭据,通过才保存(Token 与 Cookie 互斥)并重载源。 +---@param cred IReadCredential +---@param cb fun(user: table|nil, err: string|nil) +---@return { cancel: fun() } +function Setting.save(cred, cb) + local client = require("moonsource_iread.client") + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + local previous_token, previous_cookie = cfg.token, cfg.cookie + local previous = client.credential() + local cancelled = false + local job = client.userAsync(cred, function(user, err) + if cancelled then return end + if cfg.token ~= previous_token or cfg.cookie ~= previous_cookie then + cb(nil, _("登录状态已变化,请重试")); return + end + if not user then return cb(nil, err or _("登录失败")) end + if previous and (cred.token ~= previous.token or cred.cookie ~= previous.cookie) then + local cleared = require("source.logout").clear(SOURCE_ID, function() + cfg.token, cfg.cookie = nil, nil + settings.saveSource(SOURCE_ID, cfg) + end) + if not cleared then cb(nil, _("准备本地同步失败")); return end + end + cfg.token, cfg.cookie = cred.token, cred.cookie + settings.saveSource(SOURCE_ID, cfg) + require("source.auth").ok(SOURCE_ID) + require("source.registry").reload() + cb(user) + end) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +--- 浏览器扩展登录(features/cookie)。 +Setting.browser = { + domain = "iread.ankio.net", + scope = "cookie", + login = "https://iread.ankio.net/#/system/token", + check = "https://iread.ankio.net/#/system/token", + icon = "https://iread.ankio.net/static/icons/favicon-32x32.png", + isAuthorized = function() + return loggedIn() and not require("source.auth").expired(SOURCE_ID) + end, + apply = function(payload, cb) + local cookie = Setting.fromPayload(payload) + if cookie == "" then return cb(false, _("没有读到 Cookie")) end + return Setting.save({ cookie = cookie }, function(user, err) cb(user ~= nil, err) end) + end, +} + +---@param cred IReadCredential +local function verify(cred) + local Toast = require("ui.themes.widgets.toast") + require("ui/network/manager"):runWhenConnected(function() + local job + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = _("iRead"), text = _("正在校验登录…"), dismissable = false, + on_cancel = function() if job then job.cancel() end end, + } + waiting:show() + job = Setting.save(cred, function(user, err) + waiting:close() + if not user then + Toast:new{ text = err or _("登录失败"), timeout = 3 }:show() + return + end + Toast:new{ text = T(_("已登录:%1"), user.nickname), timeout = 2 }:show() + end) + end) +end + +local function showLogin() + require("ui.themes.widgets.input"):new{ + title = _("iRead 个人 Token"), + fields = { { text = "", hint = _("打开 iread.ankio.net/#/system/token ,新建个人 Token 后粘贴到这里") } }, + ok_text = _("登录"), + callback = function(value) + local token = Setting.parseToken(value or "") + if token == "" then + require("ui.themes.widgets.toast"):new{ text = _("没有读到 Token"), timeout = 3 }:show() + return + end + verify({ token = token }) + end, + }:show() +end + +local function showCookieLogin() + require("ui.themes.widgets.input"):new{ + title = _("iRead 登录 Cookie"), + fields = { { text = "", hint = _("按键盘 F12,点「网络」,刷新网页,复制请求标头里的整段 Cookie") } }, + ok_text = _("登录"), + callback = function(value) + local cookie = require("source.cookie_login").parse(value or "") + if cookie == "" then + require("ui.themes.widgets.toast"):new{ text = _("没有读到 Cookie"), timeout = 3 }:show() + return + end + verify({ cookie = cookie }) + end, + }:show() +end + +---@return table[] +function Setting.rows() + local Row = require("ui.themes.widgets.row") + local CookieLogin = require("source.cookie_login") + local rows = { + function(iw) + local status, status_on = Setting.rowStatus() + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "account_circle", + title = _("iRead 账号"), status = status, status_on = status_on, + callback = function() showLogin() end }) + end, + CookieLogin.browserRow(), + function(iw) + return Row.widget({ width = iw, chevron = true, kind = "nav", icon = "content_paste", + title = _("粘贴 Cookie"), callback = showCookieLogin }) + end, + } + if not loggedIn() then return rows end + rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出 iRead 账号?"), function() + local settings = require("utils.settings") + local cfg = settings.getSource(SOURCE_ID) + cfg.token, cfg.cookie = nil, nil + settings.saveSource(SOURCE_ID, cfg) + end) + return rows +end + +--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。 +Setting.login = showLogin + +return Setting diff --git a/moonsource-iread.koplugin/moonsource_iread/source.lua b/moonsource-iread.koplugin/moonsource_iread/source.lua new file mode 100644 index 0000000..2c8bdf0 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/source.lua @@ -0,0 +1,366 @@ +--[[-- +iRead(iread.ankio.net)数据源。 + +个人 Token 鉴权(setting.lua)。书架是服务端的收藏记录,书城搜索的书加入书库时经 /book/favourite 收藏,本地删除会上行; +目录 / 正文按章落盘走公共 source/chapter;进度只到章,开书拉取、关书上报。笔记和统计没有接口。 +服务端的书记录(bookUrl / sourceId 等)是目录、正文接口的必要参数,随书籍元数据保存;拉进度强制拉新行,写进度用缓存行(只带 id 与位置)。 + +@module koplugin.book.moonsource_iread.source +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_iread.client") +local Mapper = require("moonsource_iread.mapper") +local Shelf = require("source.shelf") +local SourceBase = require("source.base") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_iread") + +local IRead = {} + +---@return BookSourceMeta +function IRead.meta() + return require("moonsource_iread.loadmeta")() +end + +---@class IReadSource : SourceBase +---@field rows table|nil 书名 → 最近一次书架行 +---@field found table|nil 书名 → 最近一次搜索行(收藏时整行带回) +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return IReadSource +function IRead.new() + local meta = IRead.meta() + return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source) +end + +---@return boolean +function Source:configured() + return Client.credential() ~= nil +end + +---@param rows table[] +---@param stable_id string +---@return table|nil +local function findRow(rows, stable_id) + for _idx, row in ipairs(rows) do + if row.name == stable_id then return row end + end + return nil +end + +---@param self IReadSource +---@param stable_id string +---@return table|nil +local function cachedRow(self, stable_id) + local row = self.rows and self.rows[stable_id] or self.found and self.found[stable_id] + if row then return row end + local book = require("book.books_db").get(self.id, stable_id) + local stored = book and book.meta and book.meta.source and book.meta.source.iread + if type(stored) == "table" and stored.name == stable_id then return stored end + return nil +end + +--- 拉书架并刷新行缓存。 +---@param cb fun(rows: table[]|nil, err: string|nil) +---@return { cancel: fun() } +function Source:fetchShelf(cb) + local cancelled = false + local job = Client.shelfAsync(function(rows, err) + if cancelled then return end + if not rows then cb(nil, err); return end + local cache = {} + for _idx, row in ipairs(rows) do cache[row.name] = row end + self.rows = cache + cb(rows) + end) + return { cancel = function() + cancelled = true + job.cancel() + end } +end + +--- 书架远端:Shelf.syncAsync 要的三个冒号方法。收藏接口是开关,加入前先确认远端还没有这本书。 +local Remote = {} + +function Remote:shelfSyncAsync(cb) return self.source:fetchShelf(cb) end + +--- 收藏接口是开关;写后读回书架才确认,不把 HTTP 成功当成成员关系已改变。 +local function changeShelf(source, row, added, cb) + local cancelled, job, pending = false, nil, true + local first = Client.favouriteAsync(row, function(ok, err) + pending = false + if cancelled then return end + if not ok then cb(nil, err); return end + job = source:fetchShelf(function(rows, reason) + if cancelled then return end + if not rows then cb(nil, reason); return end + if (findRow(rows, row.name) ~= nil) ~= added then + cb(nil, _("iRead 书架更新未生效")); return + end + cb(true) + end) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 搜索行随元数据持久化,重启或书城缓存命中后仍可推送本地新加书。 +function Remote:addToShelfAsync(stable_id, cb) + local cancelled, job, pending = false, nil, true + local first = self.source:fetchShelf(function(rows, err) + pending = false + if cancelled then return end + if not rows then cb(nil, err); return end + if findRow(rows, stable_id) then cb(true); return end + local row = cachedRow(self.source, stable_id) + if not row then cb(nil, _("请先搜索这本书再加入书库")); return end + job = changeShelf(self.source, row, true, cb) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +--- 远端已经没有这本书就算删除完成(收藏接口是开关,不能盲调)。 +function Remote:removeFromShelfAsync(stable_id, cb) + local cancelled, job, pending = false, nil, true + local first = self.source:fetchShelf(function(rows, err) + pending = false + if cancelled then return end + if not rows then cb(nil, err); return end + local row = findRow(rows, stable_id) + if not row then cb(true); return end + job = changeShelf(self.source, row, false, cb) + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +function Source:syncBooksAsync(opts, cb) + if not self:configured() then return SourceBase.skipped(cb, "iread not logged in") end + local remote = setmetatable({ source = self }, { __index = Remote }) + return Shelf.syncAsync(self.id, remote, Mapper.shelfList, opts, cb) +end + +--- 书城搜索:回包形状同 listStoreAsync。搜索行同书架行,缓存起来供目录 / 正文接口使用。 +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +---@return { cancel: fun() } +function Source:searchAsync(keyword, cb) + return Client.searchAsync(keyword, function(rows, err) + if not rows then cb(nil, err); return end + self.found = self.found or {} + for _idx, row in ipairs(rows) do self.found[row.name] = row end + cb({ data = Mapper.shelfList(rows) }) + end) +end + +--- 书城浏览:服务端每次随机给一个书源的「发现」入口(榜单 / 分类),入口就是 chip,节点是「书源 id:入口序号」; +--- 书源规则缓存在实例上,「换一批」重取规则。结果行与搜索同形,进 self.found 供加书架。 +---@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) + local limit = opts.limit or 60 + local handle = {} + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + local function explore(rule, node) + local chips, picked = {}, nil + for idx, entry in ipairs(rule.exploreUrl) do + if entry.url and entry.url ~= "" then + local id = rule.id .. ":" .. idx + chips[#chips + 1] = { id = id, title = entry.title } + if id == node then picked = entry end + end + end + local categories = Browse.group(chips, node) + categories.title = _("分类") + local groups = { categories, { chips = { { id = "next", title = _("换一批书源") } } } } + if not picked then + cb({ data = {}, groups = groups }) + return + end + local paginated = picked.url:find("{{page}}", 1, true) ~= nil + handle.inner = Browse.pages(function(page, done) + local url = paginated and picked.url:gsub("{{page}}", tostring(page)) or picked.url + return Client.exploreAsync(rule.id, url, function(rows, err) + if handle.cancelled then return end + if not rows then done(nil, err); return end + self.found = self.found or {} + for _idx, row in ipairs(rows) do self.found[row.name] = row end + done(Mapper.shelfList(rows), nil, paginated) + end) + end, limit, groups, cb) + end + local sid = tonumber((opts.node or ""):match("^(%d+):")) + local cached = sid and self.explore_rules and self.explore_rules[sid] + if cached then + explore(cached, opts.node) + return handle + end + local pending = true + local first = Client.exploreRulesAsync(function(rules, err) + pending = false + if handle.cancelled then return end + if not rules then cb(nil, err); return end + local rule + for _idx, candidate in ipairs(rules) do + if type(candidate.exploreUrl) == "table" and #candidate.exploreUrl > 0 then rule = candidate end + end + if not rule then cb(nil, _("iRead 暂无发现入口")); return end + self.explore_rules = self.explore_rules or {} + self.explore_rules[rule.id] = rule + explore(rule, nil) + end) + if pending then handle.inner = first end + return handle +end + +--- 取书架行再交给 fn(row)(返回它发起的任务,取消时一并取消);fresh 为真强制重拉书架 +--- (拉云端进度要读最新行)。 +---@param identity BookIdentity +---@param fresh boolean +---@param cb function +---@param fn fun(row: table): { cancel: fun() }|nil +---@return { cancel: fun() } +function Source:withRow(identity, fresh, cb, fn) + local cached = not fresh and cachedRow(self, identity.stable_id) + -- 搜索命中尚未入库时 id 为 0,服务端按「请传入书库id」拒绝,必须回书架取真实行 + if cached and (tonumber(cached.id) or 0) > 0 then return fn(cached) or SourceBase.defer(function() end) end + local cancelled, job, pending = false, nil, true + local first = self:fetchShelf(function(rows, err) + pending = false + if cancelled then return end + if not rows then cb(nil, err); return end + local row = findRow(rows, identity.stable_id) + if not row then cb(nil, _("这本书不在 iRead 书架上")); return end + job = fn(row) or job + end) + if pending then job = first end + return { cancel = function() + cancelled = true + if job then job.cancel() end + end } +end + +function Source:getProgressAsync(identity, cb) + if not self:configured() then return SourceBase.defer(cb, nil, nil, { empty = true }) end + return self:withRow(identity, true, cb, function(row) + local read = Mapper.readPos(row) + if not read then cb(nil, nil, { empty = true }); return nil end + return self:loadTocAsync(identity, function(toc, reason) + if not toc then cb(nil, reason); return end + local idx = math.min(read.index + 1, #toc) + cb({ + chapter_idx = idx, + chapter_title = read.title or toc[idx].title, + fraction = (idx - 1) / #toc, + extra = { chapter_uid = toc[idx].uid, chapter_idx = idx }, + }) + end) + end) +end + +function Source:putProgressAsync(identity, pos, cb) + if not self:configured() then return SourceBase.defer(cb, nil, _("未登录 iRead")) end + -- 上报只带书 id 与位置字段,缓存行够用;写后 saveProgressAsync 自己读回书架确认。 + return self:withRow(identity, false, cb, function(row) + local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx) + if not idx then cb(nil, _("缺少阅读章节位置")); return nil end + local toc = Toc.read(self.id, identity.stable_id) + local chapter = toc and toc[idx] + local read = Mapper.readPos(row) + return Client.saveProgressAsync(row, { + index = idx - 1, + title = chapter and chapter.title, + offset = read and read.index == idx - 1 and read.offset or 0, + }, cb) + end) +end + +--- 书库里已有的元数据。 +function Source:getDetailAsync(identity, cb) + return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id)) +end + +--- 强制拉目录并写回;失败由调用方继续用旧缓存。 +---@param identity BookIdentity +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@return { cancel: fun() }|nil +local function fetchTocAsync(self, identity, cb) + return self:withRow(identity, false, cb, function(row) + return Client.chaptersAsync(row, function(rows, err) + if not rows then cb(nil, err); return end + local toc = Mapper.toc(rows) + if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end + cb(toc) + end) + 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(self.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 + +---@return ChapterFetchContent +function Source:contentFetcher() + return function(identity, chapter, done) + return self:withRow(identity, false, done, function(row) + return Client.contentAsync(row, tonumber(chapter.uid), function(text, err) + if not text then done(nil, err); return end + if text:find("<[Ii][Mm][Gg][%s>]") then + done(nil, _("iRead 图片正文暂不支持,请使用网页版阅读")); return + end + local content = Mapper.text(text) + if content == "" then done(nil, _("iRead 章节内容为空")); return end + done({ title = chapter.title, html = require("utils.text").chapterHtml(chapter.title, content) }) + end) + end) + end +end + +function Source:openBookAsync(identity, opts, cb) + local Chapter = require("source.chapter") + local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi + return open(self, identity, identity.book, opts, { + loadToc = function(ref, done) return self:loadTocAsync(ref, done) end, + fetchContent = self:contentFetcher(), + }, cb) +end + +function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb) + return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, { + fetchContent = self:contentFetcher(), + }, cb) +end + +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + return require("source.chapter").cacheAllAsync(self, identity, self:contentFetcher(), on_progress, cb, 0, range) +end + +return IRead diff --git a/moonsource-iread.koplugin/moonsource_iread/version.lua b/moonsource-iread.koplugin/moonsource_iread/version.lua new file mode 100644 index 0000000..25b37f6 --- /dev/null +++ b/moonsource-iread.koplugin/moonsource_iread/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/iread/async_spec.lua b/tests/iread/async_spec.lua new file mode 100644 index 0000000..5edff95 --- /dev/null +++ b/tests/iread/async_spec.lua @@ -0,0 +1,237 @@ +--[[-- +iRead 同步回调下的取消、搜索轮询、坏响应及登录态隔离。 + +@module tests.moonsource_iread.async_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local JSON = require("support.json_stub") +local Stubs = require("support.stubs") +local simple = {} +package.loaded.json = { + decode = setmetatable({ simple = simple }, { + __call = function(_decoder, raw, opts) + local data = JSON.decode(raw) + if opts ~= simple and raw:find('"intro":null', 1, true) then + data.data[1].intro = function() end + end + return data + end, + }), + encode = JSON.encode, + util = { null = function() end }, +} +local cfg = { token = "old-token" } +package.loaded["utils.settings"] = { getSource = function() return cfg end } +local requests, replies = {}, {} +local queue = {} +package.loaded["http.request"] = { + post = function(url, body, opts, cb) + local request = { url = url, body = body, opts = opts, cb = cb } + requests[#requests + 1] = request + local reply = table.remove(replies, 1) + if reply then cb(JSON.encode({ code = 200, data = reply }), nil, { cookies = { "sid=new; Path=/" } }) end + request.cancel = function() request.cancelled = true end + return request + end, + get = function(url, opts, cb) + local request = { url = url, opts = opts, cb = cb } + requests[#requests + 1] = request + -- 延迟回调,与真实网络行为一致 + local reply = table.remove(replies, 1) + local wrapped = function() + if reply then cb(JSON.encode({ code = 200, data = reply }), nil, nil) end + end + queue[#queue + 1] = wrapped + request.cancel = function() request.cancelled = true end + return request + end, + headerAll = function(res) return res and res.cookies or {} end, +} +local Client = require("moonsource_iread.client") +local Auth = require("source.auth") +local result, reason, calls +local function done(value, err) result, reason, calls = value, err, (calls or 0) + 1 end +local function reset() + requests, replies, result, reason, calls = {}, {}, nil, nil, 0 + cfg.token, cfg.cookie = "old-token", nil + Stubs.reset() + queue = {} + Auth.reset() +end +local function reply(request, data, code) + request.cb(JSON.encode({ code = code or 200, data = data })) +end + +reset() +Client.shelfAsync(done) +requests[1].cb('{"code":200,"data":[{"name":"书","intro":null,"author":null}]}') +Assert.is_nil(result[1].intro, "LuaJSON 的 null 应解成 nil,不能把函数哨兵写进书籍元数据") + +reset() +Client.exploreRulesAsync(done) +reply(requests[1], { { id = 1, bookSourceName = "测试书源", exploreUrl = "bad" } }) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Client.exploreRulesAsync(done) +reply(requests[2], { { id = 1, bookSourceName = "测试书源", exploreUrl = { + { title = "分组", url = "" }, { title = "↑ *** ↑" }, { title = "分类", url = "https://example.test?page={{page}}" }, +} } }) +Assert.len(result[1].exploreUrl, 1) +Assert.eq(result[1].exploreUrl[1].title, "分类") + +reset() +replies = { {} } +local handle = Client.shelfAsync(done) +local pending = requests[2] +Assert.matches(pending.url, "/user/home$") +handle:cancel() +Assert.is_true(pending.cancelled) +reply(pending, { nickname = "测试" }) +Assert.eq(calls, 0) +reply(pending, { nickname = "测试" }) +Assert.eq(calls, 0) + +reset() +replies = { {} } +Client.shelfAsync(done) +reply(requests[2], {}) +Assert.is_nil(result) +Assert.eq(reason, "iRead 账号信息为空") +Assert.eq(calls, 1) + +reset() +cfg.token = nil +replies = { { task = "guest-task" }, { result = { { name = "公开书" } }, remaining = 0 } } +Client.searchAsync("公开书", done) +Assert.len(result, 1) +Assert.is_nil(requests[1].opts.headers.Authorization) +Assert.is_nil(requests[1].opts.headers.Cookie) +Assert.eq(requests[1].opts.headers["X-Requested-With"], "XMLHttpRequest") +Client.userAsync({}, done) +reply(requests[3], {}, 401) +Assert.is_true(not Auth.expired("iread"), "游客未登录不能污染已有源的失效提示") + +reset() +Client.shelfAsync(done) +cfg.token = "new-token" +reply(requests[1], {}) +Assert.len(requests, 1, "旧书架回调不能拿新凭证校验空书架") +Assert.is_nil(result) +Assert.eq(reason, "登录状态已变化,请重试") + +reset() +Auth.expire("iread", "expired") +Client.chaptersAsync({ id = 1, name = "书" }, done) +reply(requests[1], { bad = true }) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Assert.is_true(Auth.expired("iread"), "坏响应不能清除失效标记") +Client.shelfAsync(done) +reply(requests[2], { { author = "缺少书名" } }) +Assert.is_nil(result) +Assert.eq(reason, "响应无效") +Client.shelfAsync(done) +requests[3].cb(nil, "network failed") +Assert.eq(reason, "network failed") +Assert.eq(cfg.token, "old-token") + +reset() +Client.shelfAsync(done) +cfg.token = "new-token" +reply(requests[1], {}, 401) +Assert.is_true(not Auth.expired("iread"), "旧凭证失败不能注销新凭证") +Assert.eq(reason, "登录状态已变化,请重试") + +reset() +replies = { { task = "task-1" } } +handle = Client.searchAsync("书", done) +pending = requests[2] +handle:cancel() +Assert.is_true(pending.cancelled, "同步提交不能覆盖正在轮询的取消句柄") +reply(pending, { result = { { name = "书" } }, remaining = 0 }) +Stubs.flush() +Assert.eq(calls, 0) + +reset() +cfg.token, cfg.cookie = nil, "sid=old; login=test" +replies = { { task = "task-1" } } +Client.searchAsync("书", done) +Assert.eq(requests[2].opts.headers.Cookie, "login=test; sid=new") +Assert.is_nil(requests[2].opts.headers.Authorization) +reply(requests[2], { result = { { name = "书" } }, remaining = 1 }) +Stubs.flush() +Assert.len(requests, 3) +reply(requests[3], { result = { { name = "书" }, { name = "二" } }, remaining = 0 }) +Assert.len(result, 2) +Assert.eq(calls, 1) + +reset() +replies = { { task = "task-1" }, { result = {}, remaining = 1 } } +handle = Client.searchAsync("书", done) +handle:cancel() +Stubs.flush() +Assert.len(requests, 2, "取消后不再调度下一次轮询") +Assert.eq(calls, 0) + +reset() +replies = { { task = "task-1" } } +Client.searchAsync("书", done) +reply(requests[2], { result = {} }) +Assert.is_nil(result) +Assert.eq(reason, "响应无效", "缺少 remaining 不能伪装成搜索完成") + +reset() +replies = { { task = "task-1" } } +Client.searchAsync("书", done) +reply(requests[2], { result = { { name = "书" } }, remaining = 1 }) +Stubs.flush() +requests[3].cb(nil, "network failed") +Assert.is_nil(result) +Assert.eq(reason, "network failed", "中途失败不能返回不完整搜索结果") +Assert.eq(calls, 1) + +reset() +replies = { { task = "task-1" } } +for _index = 1, 30 do replies[#replies + 1] = { result = { { name = "书" } }, remaining = 1 } end +Client.searchAsync("书", done) +Stubs.flush() +Assert.is_nil(result) +Assert.eq(reason, "iRead 搜索超时,请重试") +Assert.eq(calls, 1) +Assert.len(requests, 31) + +reset() +replies = { { task = "task-1" }, { result = {}, remaining = 1 } } +Client.searchAsync("书", done) +cfg.token = "new-token" +Stubs.flush() +Assert.len(requests, 2, "换登录态后不继续旧搜索任务") +Assert.eq(reason, "登录状态已变化,请重试") + +reset() +replies = { {} } +handle = Client.saveProgressAsync({ id = 1, name = "书" }, { index = 2, offset = 0 }, done) +pending = requests[2] +handle:cancel() +Assert.is_true(pending.cancelled) +reply(pending, { { name = "书", durChapterIndex = 2, durChapterPos = 0 } }) +Assert.eq(calls, 0) + +reset() +replies = { {}, { { name = "书", durChapterIndex = 1, durChapterPos = 0 } } } +Client.saveProgressAsync({ id = 1, name = "书" }, { index = 2, offset = 0 }, done) +Assert.is_nil(result) +Assert.eq(reason, "iRead 阅读进度更新未生效") +Assert.eq(calls, 1) + +reset() +Client.chaptersAsync({ id = 7, name = "书" }, done) +Assert.matches(requests[1].body, "page=1") +requests[1].cb('{"code":200,"data":[{"title":"一","index":0}],"hasMore":true}') +Assert.len(requests, 2, "hasMore 为真要继续翻页") +Assert.matches(requests[2].body, "page=2") +requests[2].cb('{"code":200,"data":[{"title":"二","index":1}],"hasMore":false}') +Assert.len(result, 2, "目录要拼全所有页") +Assert.eq(result[2].title, "二") diff --git a/tests/iread/iread_spec.lua b/tests/iread/iread_spec.lua new file mode 100644 index 0000000..6023c32 --- /dev/null +++ b/tests/iread/iread_spec.lua @@ -0,0 +1,205 @@ +--[[-- +iRead:个人 Token 请求形状、回包解码、空书架验登录态、表单摊平与映射离线用例。 + +@module tests.moonsource_iread.source_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 JSONStub = require("support.json_stub") +local json_null = function() end + +package.preload["json"] = function() + return { + decode = setmetatable({ simple = {} }, { __call = function(_decoder, raw) return JSONStub.decode(raw) end }), + encode = JSONStub.encode, + util = { null = json_null }, + } +end + +local cfg = { token = "a1b2" } +package.preload["utils.settings"] = function() + return { getSource = function() return cfg end } +end + +local requests, replies = {}, {} +package.preload["http.request"] = function() + return { + post = function(url, body, opts, cb) + requests[#requests + 1] = { url = url, body = body, opts = opts } + local reply = table.remove(replies, 1) + if type(reply) == "table" then cb(reply.body, nil, reply) else cb(reply) end + return { cancel = function() end } + end, + get = function(url, opts, cb) + requests[#requests + 1] = { url = url, opts = opts } + local reply = table.remove(replies, 1) + if type(reply) == "table" then cb(reply.body, nil, reply) else cb(reply) end + return { cancel = function() end } + end, + header = function(res) return res and res.cookie end, + headerAll = function(res) return res and res.cookie and { res.cookie } or {} end, + } +end + +for _idx, name in ipairs({ "moonsource_iread.client", "moonsource_iread.mapper", "source.auth" }) do + package.loaded[name] = nil +end +local Client = require("moonsource_iread.client") +local Mapper = require("moonsource_iread.mapper") +local Auth = require("source.auth") + +-- 书架:POST 表单 + Bearer Token;有书直接返回。 +do + replies = { '{"code":200,"data":[{"name":"书"}]}' } + local rows + Client.shelfAsync(function(v) rows = v end) + Assert.len(rows, 1) + Assert.len(requests, 1) + Assert.eq(requests[1].url, "https://iread.ankio.net/book/list") + Assert.eq(requests[1].opts.headers.Authorization, "Bearer a1b2") + Assert.eq(requests[1].opts.content_type, "application/x-www-form-urlencoded") +end + +-- 空书架:服务端对无效 Token 也回 200 + 空数组,必须再验登录态,不能当成「书架被清空」。 +do + requests = {} + replies = { '{"code":200,"data":[]}', '{"code":200,"data":{"nickname":"我"}}' } + local rows + Client.shelfAsync(function(v) rows = v end) + Assert.len(rows, 0) + Assert.eq(requests[2].url, "https://iread.ankio.net/user/home") + Assert.not_nil(requests[2].body) + + replies = { '{"code":200,"data":[]}', '{"code":401,"data":"x"}' } + local err + rows = nil + Client.shelfAsync(function(v, e) rows, err = v, e end) + Assert.is_nil(rows) + Assert.matches(err, "iread%.ankio%.net/#/system/token") + Assert.is_true(Auth.expired("iread")) +end + +-- 非 200:带出 msg;游客也可读取接口,但不能修改远端书架或进度。 +do + requests = {} + replies = { '{"code":400,"msg":"书籍数据错误"}' } + local err + Client.saveProgressAsync({ id = 1, name = "书" }, { index = 0, offset = 0 }, function(_ok, e) err = e end) + Assert.eq(err, "书籍数据错误") + + cfg.token = nil + requests = {} + Client.saveProgressAsync({ id = 1, name = "书" }, { index = 0, offset = 0 }, function(_ok, e) err = e end) + Assert.len(requests, 0) + cfg.token = "a1b2" +end + +-- Cookie 登录(浏览器扩展):只发 Cookie,不带 Bearer;Token 优先。 +do + cfg.token, cfg.cookie = nil, "NovaSession=abc" + requests = {} + replies = { '{"code":200,"data":[{"name":"书"}]}' } + Client.shelfAsync(function() end) + Assert.eq(requests[1].opts.headers.Cookie, "NovaSession=abc") + Assert.is_nil(requests[1].opts.headers.Authorization) + cfg.token = "a1b2" + requests = {} + replies = { '{"code":200,"data":[{"name":"书"}]}' } + Client.shelfAsync(function() end) + Assert.eq(requests[1].opts.headers.Authorization, "Bearer a1b2") + cfg.cookie = nil + + local Setting = require("moonsource_iread.setting") + Assert.eq(Setting.fromPayload({ cookies = { + { domain = ".ankio.net", name = "b", value = "2" }, + { domain = "iread.ankio.net", name = "a", value = "1" }, + { domain = "evil.com", name = "x", value = "9" }, + { domain = "iread.ankio.net", name = "bad", value = "v;w" }, + } }), "a=1; b=2") +end + +-- 进度:只传 id + 位置字段;不再发整行。 +do + requests = {} + replies = { + '{"code":200,"data":{}}', + '{"code":200,"data":[{"name":"书","durChapterIndex":4,"durChapterPos":12}]}', + } + local ok + Client.saveProgressAsync({ id = 42, name = "书" }, + { index = 4, title = "第5章", offset = 12 }, function(v) ok = v end) + Assert.is_true(ok) + local body = requests[1].body + Assert.matches(requests[1].url, "/book/process$") + Assert.matches(body, "id=42") + Assert.matches(body, "durChapterIndex=4") + Assert.matches(body, "durChapterPos=12") + Assert.matches(body, "durChapterTitle=%%E7%%AC%%AC5%%E7%%AB%%A0") + -- 不再发原行的其他字段(sourceId、variable 等) + Assert.is_nil(body:find("sourceId", 1, true)) + Assert.is_nil(body:find("variable", 1, true)) +end + +-- 正文:只传 id 和 index;空正文报错。 +do + requests = {} + replies = { '{"code":200,"data":{"title":"一","content":"第一段\\n第二段"}}' } + local text + Client.contentAsync({ id = 10 }, 3, function(v) text = v end) + Assert.eq(text, "第一段\n第二段") + Assert.matches(requests[1].url, "/book/chapter$") + Assert.matches(requests[1].body, "id=10") + Assert.matches(requests[1].body, "index=3") + + replies = { '{"code":200,"data":{"content":""}}' } + local err + Client.contentAsync({ id = 10 }, 0, function(_, e) err = e end) + Assert.eq(err, "iRead 章节内容为空") +end + +-- 映射:书名是身份,自定义封面优先、// 补协议;没书名的行丢弃。 +do + local books = Mapper.shelfList({ + { name = "书", author = "作者", coverUrl = "//img/a.jpg", kind = "玄幻" }, + { name = "二", customCoverUrl = "http://img/b.jpg", coverUrl = "x" }, + { author = "无名" }, + }) + Assert.len(books, 2) + Assert.eq(books[1].stable_id, "书") + Assert.eq(books[1].cover, "https://img/a.jpg") + Assert.eq(books[2].cover, "http://img/b.jpg") +end + +-- 阅读位置:第 0 章 0 偏移且没时间戳算没读过;目录 uid 是 0 基序号,不存章节原 JSON(开章不用)。 +do + Assert.is_nil(Mapper.readPos({ durChapterIndex = 0, durChapterPos = 0, durChapterTime = 0 })) + Assert.eq(Mapper.readPos({ durChapterIndex = 0, durChapterPos = 0, durChapterTime = 5 }).index, 0) + Assert.eq(Mapper.readPos({ durChapterIndex = 2, durChapterTitle = "第3章" }).title, "第3章") + local toc = Mapper.toc({ { title = "序", url = "a" }, { title = "一", url = "b" } }) + Assert.eq(toc[2].idx, 2) + Assert.eq(toc[2].uid, "1") + Assert.is_nil(toc[2].raw) +end + +-- 正文带 HTML 标签时剥掉,纯文本原样。 +do + Assert.eq(Mapper.text("

甲

乙

"), "甲\n乙") + Assert.eq(Mapper.text("1 < 2"), "1 < 2") +end + +-- 搜索:提交与轮询共用服务端会话 Cookie,否则取结果 500。 +do + requests = {} + replies = { + { body = '{"code":200,"data":{"task":"search/1/x","total":2}}', cookie = "sid=abc; path=/; HttpOnly" }, + '{"code":200,"data":{"remaining":0,"result":[{"name":"书"}]}}', + } + local rows + Client.searchAsync("斗罗", function(v) rows = v end) + Assert.len(rows, 1) + Assert.eq(requests[1].url, "https://iread.ankio.net/book/search") + Assert.matches(requests[1].body, "bookname=") + Assert.eq(requests[2].url, "https://iread.ankio.net/book/search/result") + Assert.eq(requests[2].opts.headers.Cookie, "sid=abc") +end diff --git a/tests/iread/setting_spec.lua b/tests/iread/setting_spec.lua new file mode 100644 index 0000000..1100e55 --- /dev/null +++ b/tests/iread/setting_spec.lua @@ -0,0 +1,95 @@ +--[[-- +iRead 候选登录的取消与竞态、Cookie 域范围及手动粘贴入口。 + +@module tests.moonsource_iread.setting_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch + +local Assert = require("support.assert") +local Themed = require("support.theme_stubs") +Themed.install() +package.loaded["ui.themes.widgets.row"] = { widget = function(spec) return spec end } +local cfg, saved, reloaded = { token = "old-token" }, 0, 0 +local cleared = 0 +package.loaded["source.logout"] = { row = require("source.logout").row, clear = function(_id, clear) + clear(); cleared = cleared + 1; return true +end } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() saved = saved + 1 end, +} +package.loaded["source.registry"] = { reload = function() reloaded = reloaded + 1 end } +local requests = {} +package.loaded["moonsource_iread.client"] = { + credential = function() + if cfg.token then return { token = cfg.token } end + if cfg.cookie then return { cookie = cfg.cookie } end + end, + userAsync = function(cred, cb) + local request = { cred = cred, cb = cb } + requests[#requests + 1] = request + return { cancel = function() request.cancelled = true end } + end, +} +local Setting = require("moonsource_iread.setting") +local calls, result, reason = 0, nil, nil +local function done(user, err) calls, result, reason = calls + 1, user, err end + +local handle = Setting.save({ token = "candidate" }, done) +handle:cancel() +Assert.is_true(requests[1].cancelled) +requests[1].cb({ nickname = "测试" }) +Assert.eq(calls, 0) +Assert.eq(cfg.token, "old-token") +Assert.eq(saved, 0) + +Setting.save({ token = "candidate" }, done) +requests[2].cb(nil, "network failed") +Assert.eq(cfg.token, "old-token") +Assert.eq(reason, "network failed") +Assert.eq(saved, 0) + +Setting.save({ token = "candidate" }, done) +cfg.token = "new-token" +requests[3].cb({ nickname = "测试" }) +Assert.is_nil(result) +Assert.eq(reason, "登录状态已变化,请重试") +Assert.eq(cfg.token, "new-token") +Assert.eq(saved, 0) + +Setting.save({ token = "different-token" }, done) +requests[4].cb({ nickname = "测试" }) +Assert.is_true(result ~= nil) +Assert.is_nil(reason) +Assert.eq(cfg.token, "different-token") +Assert.eq(cleared, 1, "凭据变化时直接清旧源") +Assert.is_nil(Themed.last("confirm")) +cfg.token = nil +saved, reloaded = 0, 0 + +handle = Setting.browser.apply({ cookies = { + { domain = ".ankio.net", name = "parent", value = "ok" }, + { domain = "iread.ankio.net", name = "site", value = "ok" }, + { domain = "other.ankio.net", name = "sibling", value = "no" }, + { domain = "ankio.net.evil.test", name = "evil", value = "no" }, +} }, function(ok, err) result, reason = ok, err end) +Assert.eq(requests[5].cred.cookie, "parent=ok; site=ok") +requests[5].cb({ nickname = "测试" }) +Assert.is_true(result) +Assert.is_nil(reason) +Assert.is_nil(cfg.token) +Assert.eq(cfg.cookie, "parent=ok; site=ok") +Assert.eq(saved, 1) +Assert.eq(reloaded, 1) + +local rows = Setting.rows() +Assert.eq(rows[2](500).title, "浏览器登录") +local cookie_row = rows[3](500) +Assert.eq(cookie_row.title, "粘贴 Cookie") +cookie_row.callback() +local input = Themed.last("input") +Assert.eq(input.title, "iRead 登录 Cookie") +input.callback("Cookie: sid=manual") +Assert.eq(requests[6].cred.cookie, "sid=manual") +Themed.last("progress_dialog").on_cancel() +Assert.is_true(requests[6].cancelled) diff --git a/tests/iread/source_spec.lua b/tests/iread/source_spec.lua new file mode 100644 index 0000000..600602c --- /dev/null +++ b/tests/iread/source_spec.lua @@ -0,0 +1,233 @@ +--[[-- +iRead 搜索元数据持久化、重启后加架、写后确认与源编排取消。 + +@module tests.moonsource_iread.source_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Stubs = require("support.stubs") +local sqlite_ok = pcall(require, "lua-ljsqlite3/init") +if not sqlite_ok then Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") end +package.loaded.json = require("support.json_stub") +local path = Config.dir() .. "/iread_source_spec.sqlite3" +for _index, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(path .. suffix) end +local Paths = require("utils.paths") +package.loaded["utils.paths"] = setmetatable({ dbPath = function() return path end }, { __index = Paths }) +local BookDB = require("book.books_db") +local Store = require("book.store") +local Base = require("source.base") +local row = { id = 9, name = "测试书", bookUrl = "https://example.test/book", sourceId = 7, variable = { key = "value" } } +local requests, shelf_replies = {}, {} +local function pending(kind, cb, data) + local request = { kind = kind, cb = cb, data = data } + requests[#requests + 1] = request + return { cancel = function() request.cancelled = true end } +end +package.loaded["moonsource_iread.client"] = { + credential = function() return { token = "test" } end, + searchAsync = function(_keyword, cb) return Base.defer(cb, { row }) end, + shelfAsync = function(cb) + local job = pending("shelf", cb) + local rows = table.remove(shelf_replies, 1) + if rows then cb(rows) end + return job + end, + favouriteAsync = function(book, cb) + local job = pending("toggle", cb, book) + cb(true) + return job + end, + chaptersAsync = function(book, cb) return pending("toc", cb, book) end, + exploreRulesAsync = function(cb) + local job = pending("rules", cb) + cb({ { id = 7, exploreUrl = { { title = "分类", url = "https://example.test/category" } } } }) + return job + end, + exploreAsync = function(_id, _url, cb) return pending("explore", cb) end, +} +local remote +package.loaded["source.shelf"] = { + syncAsync = function(_id, adapter, _mapper, _opts, cb) + remote = adapter + return Base.defer(cb, { skipped = true }) + end, +} +local IRead = require("moonsource_iread.source") +local source = IRead.new() +local result, reason, calls = nil, nil, 0 +local function done(value, err) result, reason, calls = value, err, calls + 1 end +source:searchAsync("测试", function(res) + Store.rememberMany(res.data) +end) +Stubs.flush() +local stored = BookDB.get("iread", row.name) +Assert.eq(stored.meta.source.iread.bookUrl, row.bookUrl) +Assert.eq(stored.meta.source.iread.variable.key, "value") +Assert.eq(stored.deleted, 1, "保存书城结果不能自动上架") + +source = IRead.new() +local identity = { source_id = "iread", stable_id = row.name } +local handle = source:loadTocAsync(identity, done, true) +Assert.len(requests, 1, "重启后目录可使用随书籍持久化的源记录") +Assert.eq(requests[1].kind, "toc") +Assert.eq(requests[1].data.sourceId, 7) +handle:cancel() +Assert.is_true(requests[1].cancelled) + +source:syncBooksAsync({}, function() end) +Stubs.flush() +requests, shelf_replies, result, reason, calls = {}, { {} }, nil, nil, 0 +handle = remote:addToShelfAsync(row.name, done) +Assert.eq(requests[2].kind, "toggle") +Assert.eq(requests[2].data.bookUrl, row.bookUrl) +Assert.eq(requests[3].kind, "shelf") +Assert.eq(calls, 0, "收藏接口成功不代表书架已改变") +requests[3].cb({ row }) +Assert.is_true(result) +Assert.eq(calls, 1) + +requests, shelf_replies, result, reason, calls = {}, { {} }, nil, nil, 0 +remote:addToShelfAsync(row.name, done) +requests[3].cb({}) +Assert.is_nil(result) +Assert.eq(reason, "iRead 书架更新未生效") + +requests, shelf_replies, result, reason, calls = {}, { { row } }, nil, nil, 0 +remote:addToShelfAsync(row.name, done) +Assert.is_true(result) +Assert.len(requests, 1, "已在架不重复调用开关接口") + +requests, shelf_replies, result, reason, calls = {}, { { row } }, nil, nil, 0 +handle = remote:removeFromShelfAsync(row.name, done) +Assert.eq(requests[3].kind, "shelf") +handle:cancel() +Assert.is_true(requests[3].cancelled, "同步回调不能覆盖写后确认的句柄") +requests[3].cb({}) +Assert.eq(calls, 0) + +requests, shelf_replies, result, reason, calls = {}, { { row } }, nil, nil, 0 +remote:removeFromShelfAsync(row.name, done) +requests[3].cb({}) +Assert.is_true(result) + +requests, shelf_replies, result, reason, calls = {}, { {} }, nil, nil, 0 +remote:removeFromShelfAsync(row.name, done) +Assert.is_true(result) +Assert.len(requests, 1, "已移出不能调用开关而重新加入") + +requests, shelf_replies, result, reason, calls = {}, { { row } }, nil, nil, 0 +handle = source:withRow(identity, true, done, function(book) + return require("moonsource_iread.client").chaptersAsync(book, done) +end) +Assert.eq(requests[2].kind, "toc") +handle:cancel() +Assert.is_true(requests[2].cancelled) + +requests, shelf_replies, result, reason, calls = {}, {}, nil, nil, 0 +source.rows = nil +handle = source:fetchShelf(done) +handle:cancel() +requests[1].cb({ row }) +Assert.is_nil(source.rows) +Assert.eq(calls, 0) + +requests, result, reason, calls = {}, nil, nil, 0 +source:browseAsync({}, done) +Assert.len(result.groups[1].chips, 1) +handle = source:browseAsync({ node = "7:1" }, done) +Assert.eq(requests[2].kind, "explore") +handle:cancel() +local before = calls +requests[2].cb({ row }) +Assert.eq(calls, before) + +local shelf = package.loaded["source.shelf"] +local capture = shelf.syncAsync +package.loaded["source.shelf"] = nil +shelf.syncAsync = require("source.shelf").syncAsync +Assert.is_true(BookDB.setLibraryMembership("iread", row.name, true)) +requests, shelf_replies = {}, { {}, {} } +source:syncBooksAsync({ dirty_only = true }, done) +Stubs.flush() +Assert.eq(result.pushed, 0) +Assert.eq(BookDB.get("iread", row.name).sync_status, 0, "写后回读未确认的新加书必须保留脏状态") +Assert.is_true(BookDB.markDeleted("iread", row.name)) +requests, shelf_replies = {}, { { row }, { row } } +source:syncBooksAsync({ dirty_only = true }, done) +Stubs.flush() +stored = BookDB.get("iread", row.name) +Assert.eq(stored.deleted, 1) +Assert.eq(stored.sync_status, 0, "远端仍在架时不能撕墓碑") +shelf.syncAsync = capture + +local client = require("moonsource_iread.client") +client.credential = function() return nil end +source = IRead.new() +source.explore_rules = { [7] = { + id = 7, exploreUrl = { { title = "分类", url = "https://example.test/list?page={{page}}" } }, +} } +local pages = {} +client.exploreAsync = function(_id, url, cb) + local page = tonumber(url:match("page=(%d+)")) + pages[#pages + 1] = page + local rows = {} + for index = 1, 20 do + rows[index] = { name = "分类书" .. ((page - 1) * 20 + index), bookUrl = "https://example.test/book", sourceId = 7 } + end + return Base.defer(cb, rows) +end +source:browseAsync({ node = "7:1", limit = 45 }, done) +Stubs.flush() +Assert.len(result.data, 45) +Assert.len(pages, 3) +Assert.eq(pages[3], 3) +Assert.eq(result.groups[1].title, "分类") +Assert.eq(result.data[45].stable_id, "分类书45") + +pages = {} +client.exploreAsync = function(_id, url, cb) + local page = tonumber(url:match("page=(%d+)")) + pages[#pages + 1] = page + if page == 1 then return Base.defer(cb, { row }) end + return Base.defer(cb, nil, "network failed") +end +source:browseAsync({ node = "7:1", limit = 45 }, done) +Stubs.flush() +Assert.is_nil(result) +Assert.eq(reason, "network failed", "第二页失败不能把第一页当成完整分类列表") + +source:searchAsync("测试", done) +Stubs.flush() +Assert.len(result.data, 1, "未登录时仍可使用官网公共搜索") +local empty +source:getProgressAsync(identity, function(value, err, meta) + result, reason, empty = value, err, meta.empty +end) +Stubs.flush() +Assert.is_nil(result) +Assert.is_nil(reason) +Assert.is_true(empty, "游客阅读不应触发云端进度登录提示") + +local text +client.contentAsync = function(_book, _index, cb) return Base.defer(cb, text) end +source.found = { [row.name] = row } +local fetch = source:contentFetcher() +text = "测试段落\n第二段" +fetch(identity, { uid = "0", title = "测试章节", raw = "{}" }, done) +Stubs.flush() +Assert.matches(result.html, "测试段落") +text = '' +fetch(identity, { uid = "0", title = "测试章节", raw = "{}" }, done) +Stubs.flush() +Assert.is_nil(result) +Assert.eq(reason, "iRead 图片正文暂不支持,请使用网页版阅读") +text = "

" +fetch(identity, { uid = "0", title = "测试章节", raw = "{}" }, done) +Stubs.flush() +Assert.is_nil(result) +Assert.eq(reason, "iRead 章节内容为空", "不能把剥标签后的空正文缓存成成功") + +require("utils.db").close() +for _index, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(path .. suffix) end 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 "$@"