commit 3598b9f825e01fcf7c350044b3cd60b43531b320 Author: Garfield Date: Fri Nov 27 08:08:02 2026 +0800 :truck: (split): 从月读拆出独立仓库,沿用原书源 id 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..b9ded71 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 更新日志 + +## 0.0.1 + +- 「BookOrbit」书源拆成独立仓库,独立发版、独立更新;原来所有书源同版本一起更新的做法取消。 +- 检查更新与自动更新只管本书源:月读「书库 → 更新」里每个书源各有一项,只提示、不静默安装,装完重启 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..d6af3af --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# 月读书源:BookOrbit + +给月读增加「BookOrbit」在线书源的 KOReader 插件。本仓库只含这一个插件,独立维护、独立发版,全部书源见 [moon-source 组织](https://git.garfieldho.me/moon-source)。 + +## 免责声明 + +- 本仓库与「BookOrbit」官方**没有任何关联**,所有商标、书名、内容归原权利人所有。 +- 插件只是在用户自己的账号、自己的设备上,按用户本人已有的权限读取内容;不提供、不分发任何书籍内容,也不绕过付费。 +- 使用可能违反对应平台的用户协议,账号可能被限制或封禁。是否使用、风险如何,由使用者自行判断并承担。 +- 权利人认为本仓库内容有问题,请通过仓库 issue 联系,核实后会及时处理。 + +## 安装 + +1. 先装好月读。 +2. 从 [Release](../../releases) 下载 `moonsource-bookorbit.koplugin-<版本>.zip`,解压出 `moonsource-bookorbit.koplugin` 目录,整个复制到 KOReader 的 `plugins/` 下。 +3. 重启 KOReader,在月读的书源列表里启用。 + +书源 id 是 `bookorbit`,与旧版(合并仓库、内置书源)相同,书架、进度、登录配置、缓存沿用原有数据,无需迁移。 + +## 更新 + +在月读的「书库 → BookOrbit 更新」里有「检查书源插件更新」和「自动检查书源插件更新」(默认开,每 24 小时一次,只提示、不静默安装)。 +本插件只检查并更新自己(本仓库的 Release),校验值取自 Release 的 `SHA256SUMS`,装完重启 KOReader。 + +> 从旧的合并仓库 `GarfieldTony/moon-source` 迁移:旧仓库的更新入口已停用,请直接从本仓库下载最新包覆盖安装。 + +## 发布 + +推送 `vX.Y.Z` 标签(带 `-` 的如 `v1.2.0-rc.1` 为预发布),Forgejo Actions 会打包 `moonsource-bookorbit.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/bookorbit/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-bookorbit.koplugin/_meta.lua b/moonsource-bookorbit.koplugin/_meta.lua new file mode 100644 index 0000000..8f93c7c --- /dev/null +++ b/moonsource-bookorbit.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:BookOrbit"), + description = _("给月读增加「BookOrbit」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-bookorbit.koplugin/main.lua b/moonsource-bookorbit.koplugin/main.lua new file mode 100644 index 0000000..4a56005 --- /dev/null +++ b/moonsource-bookorbit.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_bookorbit", + is_doc_only = false, +} diff --git a/moonsource-bookorbit.koplugin/moon_source.lua b/moonsource-bookorbit.koplugin/moon_source.lua new file mode 100644 index 0000000..c643579 --- /dev/null +++ b/moonsource-bookorbit.koplugin/moon_source.lua @@ -0,0 +1,17 @@ +--[[-- +月读第三方书源描述:BookOrbit。契约见月读 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_bookorbit.source").meta() end, + new = function() return require("moonsource_bookorbit.source").new() end, + setting = lazy("moonsource_bookorbit.setting"), +} diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/README.md b/moonsource-bookorbit.koplugin/moonsource_bookorbit/README.md new file mode 100644 index 0000000..a6dea4a --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/README.md @@ -0,0 +1,16 @@ +# BookOrbit + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 服务连接 | 支持 | 使用 BookOrbit 的 KOReader 同步账号;可导入官方插件配置 | +| 书库选择 | 支持 | 未选择时读取全部可访问书库 | +| 书架拉取 | 支持 | 分页读取 | +| 加入远端书架 | 不支持 | 本地新增书籍不上传 | +| 删除远端书籍 | 不支持 | 仅清本地缓存并留墓碑,不删除服务器藏书 | +| 详情与封面 | 支持 | 读取书籍元数据及可读文件 | +| 整本下载与阅读 | 支持 | EPUB、AZW3、AZW、MOBI、FB2、DOCX、PDF、DjVu、CBZ、TXT | +| 阅读进度同步 | 支持 | 仅已下载文件;按文件摘要匹配,使用 xpointer 或页码 | +| 划线同步 | 部分支持 | 仅上传已下载书籍的支持类型划线,不拉取远端笔记 | +| 阅读统计同步 | 不支持 | 本地记录保留 | +| 书评、章评、段评与回复 | 不支持 | 当前同步契约未接入;不代表所有服务端版本都没有评论 | +| 离线阅读 | 支持 | 已下载文件可用;连接、下载和同步需要服务器在线 | diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/_meta.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/_meta.lua new file mode 100644 index 0000000..70aed54 --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +@module moonsource_bookorbit._meta +--]] + +local _ = require("l10n").get("moonsource_bookorbit") + +return { + id = "bookorbit", + name = _("BookOrbit"), + type = "book", + description = _("连接 BookOrbit KOReader 接口"), + abilities = { _("书架与整本下载"), _("已下载书籍进度同步"), _("已下载书籍划线上传") }, +} diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/client.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/client.lua new file mode 100644 index 0000000..f7e1b7b --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/client.lua @@ -0,0 +1,125 @@ +--[[-- +BookOrbit HTTP 客户端:KOReader 同步账号认证(x-auth-user / x-auth-key),只回 wire,不做领域转换。 +x-auth-key 是密码的 MD5(同 kosync,服务端也收明文)。接口都在 `/api/v1/koreader/` 下。 +调用方先看 configured(),这里不再判。 + +@module moonsource_bookorbit.client +--]] + +local JSON = require("json") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_bookorbit") +local T = require("ffi/util").template + +---@class BookOrbitClient +---@field server_url string 用户填的地址,不带 /api/v1 +---@field username string +---@field userkey string 密码 MD5 +local Client = {} +Client.__index = Client + +--- 用户填的地址:去空白、尾斜杠,以及照抄来的 `/api/v1`、`/api/v1/koreader` 后缀。 +---@param value string|nil +---@return string +function Client.normalizeUrl(value) + local url = Text.rtrimSlashes(Text.stripWhitespace(value)) + return (url:gsub("/api/v1/koreader$", ""):gsub("/api/v1$", "")) +end + +---@param cfg { server_url: string|nil, username: string|nil, userkey: string|nil } +---@return BookOrbitClient +function Client.new(cfg) + return setmetatable({ + server_url = Client.normalizeUrl(cfg.server_url), + username = Text.trim(cfg.username), + userkey = Text.stripWhitespace(cfg.userkey), + }, Client) +end + +---@return boolean +function Client:configured() + return self.server_url ~= "" and self.username ~= "" and self.userkey ~= "" +end + +---@return table +function Client:headers() + return { ["x-auth-user"] = self.username, ["x-auth-key"] = self.userkey } +end + +---@param path string `/koreader/...` +---@param query table|nil +---@return string +function Client:url(path, query) + local url = self.server_url .. "/api/v1" .. path + if query then return url .. "?" .. Text.formEncode(query) end + return url +end + +--- JSON 请求:2xx 回 cb(data),否则 cb(nil, err, code)。空体按 {} 交回。 +---@param method string +---@param path string +---@param query table|nil +---@param body table|nil JSON 请求体 +---@param cb fun(data: table|nil, err: string|nil, code: integer|nil) +---@return HttpJob +function Client:json(method, path, query, body, cb) + local headers = self:headers() + headers["Accept"] = "application/json" + local payload + if body then + headers["Content-Type"] = "application/json" + payload = JSON.encode(body) + end + return Request.request({ + url = self:url(path, query), method = method, headers = headers, body = payload, timeout = 30, + }, function(res, err) + if err or not res then + cb(nil, err and tostring(err) or _("网络请求失败")) + return + end + local code = tonumber(res.code) + if code == 401 or code == 403 then + cb(nil, _("BookOrbit 用户名或密码错误,或未开启 KOReader 同步"), code) + return + end + if not Request.ok(code) then + cb(nil, T(_("请求失败 (HTTP %1)"), tostring(code)), code) + return + end + local raw = Text.trim(Text.stripBom(res.body or "")) + if raw == "" then + cb({}, nil, code) + return + end + -- 反代可能回 HTML 错误页:解析失败按请求失败处理,不让异常冒到回调链外。 + -- simple:null 解成 nil。默认模式解成 json.util.null 函数,写进书库会绑定失败、整行丢掉。 + local ok, data = pcall(JSON.decode, raw, JSON.decode.simple) + if ok and type(data) == "table" then + cb(data, nil, code) + else + cb(nil, _("响应不是 JSON"), code) + end + end) +end + +--- 下载书库文件原件。Request.download 遇到非 2xx 也会落盘,这里删掉并报错。 +---@param file_id integer +---@param dest string +---@param on_progress fun(bytes: number, total: number|nil) +---@param cb fun(ok: boolean, err: string|nil) +---@return HttpJob +function Client:download(file_id, dest, on_progress, cb) + return Request.download({ + url = self:url("/koreader/plugin/catalog/files/" .. file_id .. "/download"), + headers = self:headers(), timeout = 60, on_progress = on_progress, + }, dest, function(ok, err, res) + if ok and not Request.ok(res and res.code) then + os.remove(dest) + ok, err = false, T(_("请求失败 (HTTP %1)"), tostring(res and res.code)) + end + cb(ok, err and tostring(err)) + end) +end + +return Client diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/l10n/en.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/l10n/en.lua new file mode 100644 index 0000000..f08e69e --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/l10n/en.lua @@ -0,0 +1,29 @@ +return { + ["书架与整本下载"] = "Bookshelf and full-book downloads", + ["已下载书籍划线上传"] = "Upload highlights from downloaded books", + ["已下载书籍进度同步"] = "Sync progress for downloaded books", + ["连接 BookOrbit KOReader 接口"] = "Connect to the BookOrbit KOReader API", + ["下载文件校验失败"] = "Downloaded file failed verification", + ["确定退出 BookOrbit 账号?"] = "Sign out of BookOrbit?", + ["正在下载…"] = "Downloading…", + ["请求失败 (HTTP %1)"] = "Request failed (HTTP %1)", + ["连接正常"] = "Connected", + ["响应不是 JSON"] = "Response is not JSON", + ["正在拉取书架(%1 本)"] = "Fetching shelf (%1 books)", + ["BookOrbit"] = "BookOrbit", + ["BookOrbit 上没有可同步的书库,请检查书库选择"] = "No library to sync on BookOrbit; check the library selection", + ["BookOrbit 不认识本地这个文件,可能服务端的书已更换"] = "BookOrbit does not recognize this local file; the book on the server may have been replaced", + ["BookOrbit 用户名或密码错误,或未开启 KOReader 同步"] = "BookOrbit username or password is wrong, or KOReader sync is not enabled", + ["BookOrbit 设置 → KOReader 里创建的同步账号"] = "Sync account created in BookOrbit Settings → KOReader", + ["从 BookOrbit 插件导入账号"] = "Import account from the BookOrbit plugin", + ["同步账号的密码"] = "Password of the sync account", + ["已导入账号 %1"] = "Imported account %1", + ["无法识别服务器响应"] = "Unrecognized server response", + ["正在连接 BookOrbit…"] = "Connecting to BookOrbit…", + ["请先在设置里填写 BookOrbit 服务器和账号"] = "Fill in the BookOrbit server and account in Settings first", + ["请先填写服务器地址、用户名和密码"] = "Fill in the server address, username and password first", + ["这本书没有 KOReader 能打开的文件"] = "This book has no file KOReader can open", + ["这本书还没下载,无法同步"] = "This book is not downloaded yet; cannot sync", + ["选择书库(不选 = 全部)"] = "Select libraries (none = all)", + ["连接 BookOrbit 服务器"] = "Connect to a BookOrbit server", +} diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/l10n/zh_TW.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/l10n/zh_TW.lua new file mode 100644 index 0000000..33dfa2e --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/l10n/zh_TW.lua @@ -0,0 +1,29 @@ +return { + ["书架与整本下载"] = "書架與整本下載", + ["已下载书籍划线上传"] = "已下載書籍畫線上傳", + ["已下载书籍进度同步"] = "已下載書籍進度同步", + ["连接 BookOrbit KOReader 接口"] = "連接 BookOrbit KOReader 介面", + ["下载文件校验失败"] = "下載檔案校驗失敗", + ["确定退出 BookOrbit 账号?"] = "確定登出 BookOrbit 帳號?", + ["正在下载…"] = "正在下載…", + ["请求失败 (HTTP %1)"] = "請求失敗 (HTTP %1)", + ["连接正常"] = "連線正常", + ["响应不是 JSON"] = "回應不是 JSON", + ["正在拉取书架(%1 本)"] = "正在拉取書架(%1 本)", + ["BookOrbit"] = "BookOrbit", + ["BookOrbit 上没有可同步的书库,请检查书库选择"] = "BookOrbit 上沒有可同步的書庫,請檢查書庫選擇", + ["BookOrbit 不认识本地这个文件,可能服务端的书已更换"] = "BookOrbit 不認識本地這個檔案,可能伺服端的書已更換", + ["BookOrbit 用户名或密码错误,或未开启 KOReader 同步"] = "BookOrbit 使用者名稱或密碼錯誤,或未開啟 KOReader 同步", + ["BookOrbit 设置 → KOReader 里创建的同步账号"] = "BookOrbit 設定 → KOReader 裡建立的同步帳號", + ["从 BookOrbit 插件导入账号"] = "從 BookOrbit 外掛匯入帳號", + ["同步账号的密码"] = "同步帳號的密碼", + ["已导入账号 %1"] = "已匯入帳號 %1", + ["无法识别服务器响应"] = "無法識別伺服器回應", + ["正在连接 BookOrbit…"] = "正在連接 BookOrbit…", + ["请先在设置里填写 BookOrbit 服务器和账号"] = "請先在設定裡填寫 BookOrbit 伺服器和帳號", + ["请先填写服务器地址、用户名和密码"] = "請先填寫伺服器位址、使用者名稱和密碼", + ["这本书没有 KOReader 能打开的文件"] = "這本書沒有 KOReader 能開啟的檔案", + ["这本书还没下载,无法同步"] = "這本書還沒下載,無法同步", + ["选择书库(不选 = 全部)"] = "選擇書庫(不選 = 全部)", + ["连接 BookOrbit 服务器"] = "連接 BookOrbit 伺服器", +} diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/loadmeta.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/loadmeta.lua new file mode 100644 index 0000000..d518668 --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_bookorbit._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/setting.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/setting.lua new file mode 100644 index 0000000..06b2481 --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/setting.lua @@ -0,0 +1,240 @@ +--[[-- +BookOrbit 源设置:服务器地址、KOReader 同步账号、书库选择、测试连接; +装过 BookOrbit 官方插件时可一键导入它的账号。 +配置经月读 utils.settings.getSource / saveSource("bookorbit") 落盘;密码只存 MD5(userkey)。 + +@module moonsource_bookorbit.setting +--]] + +local Client = require("moonsource_bookorbit.client") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_bookorbit") +local T = require("ffi/util").template + +local ID = "bookorbit" + +local Setting = {} + +---@return table +local function config() + return require("utils.settings").getSource(ID) +end + +--- 服务器身份:地址 + 用户名。换了就是另一套书架。 +local function libraryFingerprint(cfg) + return table.concat({ + Client.normalizeUrl(cfg.server_url or ""), + Text.trim(cfg.username or ""), + }, "\0") +end + +---@param text string +local function toast(text) + require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show() +end + +--- 落盘并重建源实例;换服务器 / 用户保留记录,先准备同步。 +---@param cfg table +---@param previous_fingerprint string|nil +---@return boolean +local function save(cfg, previous_fingerprint) + local function commit() + require("utils.settings").saveSource(ID, cfg) + end + if previous_fingerprint and previous_fingerprint ~= libraryFingerprint(cfg) then + if not require("source.logout").replaceLibrary(ID, commit) then + toast(_("准备本地同步失败")) + return false + end + else + commit() + require("source.registry").reload() + end + return true +end + +--- 密码 → x-auth-key(MD5,同 kosync);空串表示清掉。 +---@param value string|nil +---@return string +local function userkey(value) + value = Text.trim(value) + return value == "" and "" or require("ffi/sha2").md5(value) --[[@as string]] +end + +--- 官方插件存在 G_reader_settings["bookorbit"] 里的账号(它的 server_url 带 /api/v1)。 +---@return table|nil +local function officialAccount() + local reader = rawget(_G, "G_reader_settings") + local account = reader and reader:readSetting("bookorbit") + if type(account) ~= "table" then return nil end + local client = Client.new(account) + return client:configured() and client or nil +end + +--- 未配置 / 断网当场提示;否则带忙碌提示调 fn(client, done),fn 结束时必须调 done()。 +---@param fn fun(client: BookOrbitClient, done: fun()) +local function withServer(fn) + local client = Client.new(config()) + if not client:configured() then + toast(_("请先填写服务器地址、用户名和密码")) + return + end + if not require("ui/network/manager"):isConnected() then + toast(_("网络不可用,请先连接 Wi-Fi")) + return + end + local busy = require("ui.themes.widgets.toast"):new{ text = _("正在连接 BookOrbit…"), dismissable = false } + busy:show() + fn(client, function() busy:close() end) +end + +---@param key string +---@param title string +---@param hint string +---@param password boolean +---@param normalize fun(value: string|nil): string +---@param icon string +---@return fun(iw: number): table +local function field(key, title, hint, password, normalize, icon) + return function(iw) + local value = config()[key] or "" + return require("ui.themes.widgets.row").widget({ + width = iw, chevron = true, + kind = "nav", icon = icon, title = title, + status = value ~= "" and (password and "******" or value) or _("未设置"), + status_on = value ~= "", + callback = function() + local cfg = config() + require("ui.themes.widgets.input"):new{ + title = title, + -- 密码只存摘要,回填不了原文。 + fields = { { text = password and "" or (cfg[key] or ""), hint = hint, + text_type = password and "password" or nil } }, + ok_text = _("保存"), + callback = function(input) + local before = libraryFingerprint(cfg) + local next_cfg = require("util").tableDeepCopy(cfg) + next_cfg[key] = normalize(input) + -- 只改密码不算换库;地址 / 用户名变了才撕本地书架。 + save(next_cfg, (key == "server_url" or key == "username") and before or nil) + end, + }:show() + end, + }) + end +end + +--- 多选书库:只同步选中的库;一个都不选 = 全部可访问的书库。 +local function pickLibraries() + withServer(function(client, done) + client:json("GET", "/koreader/plugin/catalog/sections/libraries", nil, nil, function(data, err) + done() + if not data then + toast(err) + return + end + local cfg = config() + local chosen = cfg.libraries or {} + local items = {} + for _idx, lib in ipairs(data.items or {}) do + local id = tostring(lib.id) + items[#items + 1] = { text = lib.title or id, value = id, checked = chosen[id] == true } + end + require("ui.themes.widgets.list"):new{ + title = _("选择书库(不选 = 全部)"), + multi = true, + items = items, + close_callback = function() + local picked = {} + for _idx, item in ipairs(items) do + if item.checked then picked[item.value] = true end + end + cfg.libraries = picked + save(cfg) + end, + }:show() + end) + end) +end + +local function testConnection() + withServer(function(client, done) + client:json("GET", "/koreader/users/auth", nil, nil, function(data, err) + done() + toast(data and data.authorized == "OK" and _("连接正常") or err or _("无法识别服务器响应")) + end) + end) +end + +---@return fun(iw: number): table +local function libraryRow() + return function(iw) + local count = 0 + for _id in pairs(config().libraries or {}) do count = count + 1 end + return require("ui.themes.widgets.row").widget({ + width = iw, chevron = true, + kind = "nav", icon = "library_books", title = _("书库"), + status = count > 0 and T(_("%1 个"), count) or _("全部"), + status_on = true, + callback = pickLibraries, + }) + end +end + +---@param icon string +---@param title string +---@param callback fun() +---@return fun(iw: number): table +local function action(icon, title, callback) + return function(iw) + return require("ui.themes.widgets.row").widget({ + width = iw, kind = "action", icon = icon, title = title, callback = callback, + }) + end +end + +local function importOfficial() + local account = officialAccount() + if not account then return end + local before = libraryFingerprint(config()) + local cfg = require("util").tableDeepCopy(config()) + cfg.server_url, cfg.username, cfg.userkey = account.server_url, account.username, account.userkey + if not save(cfg, before) then return end + toast(T(_("已导入账号 %1"), account.username)) +end + +---@return table[] +function Setting.rows() + local rows = { + field("server_url", _("服务器地址"), "https://books.example.com", false, Client.normalizeUrl, "dns"), + field("username", _("用户名"), _("BookOrbit 设置 → KOReader 里创建的同步账号"), false, Text.trim, "person"), + field("userkey", _("密码"), _("同步账号的密码"), true, userkey, "key"), + libraryRow(), + action("network_check", _("测试连接"), testConnection), + } + local cfg = config() + if (cfg.username or "") ~= "" and (cfg.userkey or "") ~= "" then + rows[#rows + 1] = require("source.logout").row(ID, _("确定退出 BookOrbit 账号?"), function() + local current = config() + current.username, current.userkey = "", "" + -- 只落凭证。reload 会让桌面立刻同步,必须等本地书架清完再 reload。 + require("utils.settings").saveSource(ID, current) + end) + end + if officialAccount() then + table.insert(rows, 1, action("download", _("从 BookOrbit 插件导入账号"), importOfficial)) + end + return rows +end + +--- 远程管理「连接配置」网页上的表单;书库要连服务器挑,仍在设备上选。 +Setting.remote = { + { key = "server_url", label = _("服务器地址"), type = "url", placeholder = "https://books.example.com", + normalize = Client.normalizeUrl }, + { key = "username", label = _("用户名"), normalize = Text.trim }, + { key = "userkey", label = _("密码"), secret = true, normalize = userkey }, +} +--- 这些键变了 = 换库,远程保存后整源清本地书架。 +Setting.replace_on_remote = { "server_url", "username" } + +return Setting diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/source.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/source.lua new file mode 100644 index 0000000..254ebea --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/source.lua @@ -0,0 +1,466 @@ +--[[-- +BookOrbit 书源(整本模式)。走 BookOrbit 给 KOReader 插件开的接口(/api/v1/koreader/...)。 + +身份:书架一行 = 一本书,stable_id = BookOrbit bookId,分类 = 书库名。 +书架:所选书库(未选 = 全部可访问书库)按书名分页拉全量,交书库对账。BookOrbit 没有删书接口, + 本地删除只留墓碑。 +开书:详情里按格式偏好挑一个 KOReader 能开的文件,下载原件到工作目录 `.`。 +进度:kosync 兼容接口,文档摘要 = 本地文件的 partialMD5(服务端按它认文件,与 KOReader 自带 + kosync、BookOrbit 官方插件同一套)。位置:流式文档是 xpointer,固定版式是页码串。 +划线:注解交换接口只做上传(keys 不全、不回 ack):服务端不据此推断删除,网页上的改动也不落到本地。 + +@module moonsource_bookorbit.source +--]] + +local Client = require("moonsource_bookorbit.client") +local SourceBase = require("source.base") +local _ = require("l10n").get("moonsource_bookorbit") +local T = require("ffi/util").template + +local ID = "bookorbit" +local PAGE_SIZE = 100 +local CHUNK = 50 +local PLUGIN_VERSION = "moon-1.0" +-- 服务端已只给 primary / content 文件;按 KOReader 阅读体验排序,有声书等格式不在表里。 +local READABLE = { "epub", "azw3", "azw", "mobi", "fb2", "docx", "pdf", "djvu", "cbz", "txt" } +local MAGIC = { epub = "PK\3\4", cbz = "PK\3\4", pdf = "%PDF" } +local DRAWERS = { lighten = true, underscore = true, strikeout = true, invert = true } +local DATETIME = "^%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d$" + +---@class BookOrbitSource : SourceBase +---@field client BookOrbitClient +local Source = setmetatable({}, { __index = SourceBase }) +Source.__index = Source + +---@return BookSourceMeta +local function meta() + return require("moonsource_bookorbit.loadmeta")() +end + +---@return BookOrbitSource +local function new() + local self = setmetatable(meta(), Source) --[[@as BookOrbitSource]] + self.client = Client.new(require("utils.settings").getSource(ID)) + return self +end + +function Source:configured() + return self.client:configured() +end + +---@return boolean +local function online() + return require("ui/network/manager"):isConnected() +end + +--- 与 KOReader 自带 kosync / BookOrbit 官方插件共用设备 id,服务端设备列表里是同一台; +--- 没有时(或不合服务端格式)自己生成一个存进源配置。 +---@return string +local function deviceId() + local reader = rawget(_G, "G_reader_settings") + local id = reader and reader:readSetting("device_id") + if type(id) == "string" and #id <= 100 and id:match("^[%w%-]+$") then return id end + local settings = require("utils.settings") + local cfg = settings.getSource(ID) + if not cfg.device_id then + cfg.device_id = require("ffi/sha2").md5(table.concat({ os.time(), math.random(), tostring({}) }, ":")) + settings.saveSource(ID, cfg) + end + return cfg.device_id --[[@as string]] +end + +---@return string +local function deviceModel() + local device = package.loaded["device"] + local model = type(device) == "table" and type(device.model) == "string" and device.model or "KOReader" + return model:sub(1, 100) +end + +---@param list any +---@return string|nil +local function authorsOf(list) + if type(list) ~= "table" or #list == 0 then return nil end + return table.concat(list, " / ") +end + +--- 文件头对得上格式才算下载完整;没有魔数的格式只要求非空。 +---@param path string|nil +---@return boolean +local function validFile(path) + local file = path and io.open(path, "rb") + if not file then return false end + local head = file:read(4) + file:close() + if not head then return false end + local magic = MAGIC[(path:match("%.(%w+)$") or ""):lower()] + return magic == nil or head == magic +end + +--- 已登记且完整的本地文件。 +---@param stable_id string +---@return string|nil +local function downloaded(stable_id) + local book = require("book.books_db").get(ID, stable_id) + local path = book and book.path + if validFile(path) then return path end + return nil +end + +--- 服务端认文件用的摘要;没下载就没有。 +---@param stable_id string +---@return string|nil +local function digestOf(stable_id) + local path = downloaded(stable_id) + return path and require("util").partialMD5(path) --[[@as string]] +end + +---@param files table[]|nil +---@return table|nil +local function pickFile(files) + for _fidx, format in ipairs(READABLE) do + for _idx, file in ipairs(files or {}) do + if type(file.format) == "string" and file.format:lower() == format then return file end + end + end + return nil +end + +--- 插件接口要求的设备字段(deviceTime 让服务端按设备时钟生成 datetime)。 +---@param body table +---@return table +local function withDevice(body) + body.deviceId = deviceId() + body.deviceModel = deviceModel() + body.pluginVersion = PLUGIN_VERSION + body.deviceTime = os.date("%Y-%m-%d %H:%M:%S") + return body +end + +--- 书架:书库列表 → 逐库按书名分页拉书 → 对账。没有删书接口,dirty_only 跳过。 +---@param opts { dirty_only?: boolean, on_progress?: fun(text: string|nil, done: integer|nil, total: integer|nil) }|nil +---@param cb fun(result: SyncResult|nil, err: any) +---@return { cancel: fun() } +function Source:syncBooksAsync(opts, cb) + opts = opts or {} + if opts.dirty_only then return SourceBase.skipped(cb, "no remote delete") end + if not self:configured() then + return SourceBase.defer(cb, nil, _("请先在设置里填写 BookOrbit 服务器和账号")) + end + local chosen = require("utils.settings").getSource(ID).libraries or {} + local report = opts.on_progress or function() end + local books, libraries, index, page, cancelled = {}, {}, 1, 1, false + ---@type HttpJob + local job + + local function fetch() + local library = libraries[index] + report(T(_("正在拉取书架(%1 本)"), #books)) + job = self.client:json("GET", "/koreader/plugin/catalog/books", + { libraryId = library.id, page = page, size = PAGE_SIZE, sort = "title", order = "asc" }, nil, + function(data, err) + if cancelled then return end + if not data then return cb(nil, err) end + -- 空体会被 Client:json 交成 {};拿缺页的书单对账会把本地书判成远端已删。 + if type(data.items) ~= "table" then return cb(nil, _("响应无效")) end + for _idx, item in ipairs(data.items) do + if item.id == nil then return cb(nil, _("响应无效")) end + books[#books + 1] = { + stable_id = tostring(item.id), + title = item.title, + authors = authorsOf(item.authors), + series = item.seriesName, + category = library.title, + -- Shelf.reconcile 见 percent>=100 就自动标已读(不覆盖手动未读)。 + percent = (item.readStatus == "read" or item.readStatus == "skimmed") and 100 or nil, + } + end + if data.hasNext == true then + page = page + 1 + elseif index < #libraries then + index, page = index + 1, 1 + else + return cb(require("source.shelf").reconcile(self.id, books)) + end + fetch() + end) + end + + job = self.client:json("GET", "/koreader/plugin/catalog/sections/libraries", nil, nil, function(data, err) + if cancelled then return end + if not data then return cb(nil, err) end + for _idx, entry in ipairs(data.items or {}) do + if next(chosen) == nil or chosen[tostring(entry.id)] then libraries[#libraries + 1] = entry end + end + -- 一个库都没有时不能拿空列表对账:那会把整个书架判成远端已删。 + if #libraries == 0 then return cb(nil, _("BookOrbit 上没有可同步的书库,请检查书库选择")) end + fetch() + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +--- KoreaderCatalogBookDetail → 书库行。rating 是用户自己打的分,不是公共评分,不收。 +---@param id string 源 id +---@param stable_id string +---@param detail table +---@return Book +local function detailRow(id, stable_id, detail) + local Text = require("utils.text") + local intro = detail.description + if type(intro) == "string" and intro ~= "" then + intro = Text.stripHtml(intro) + if intro == "" then intro = nil end + else + intro = nil + end + return { + source_id = id, stable_id = stable_id, title = detail.title, + authors = authorsOf(detail.authors), intro = intro, series = detail.seriesName, + meta = { + publisher = detail.publisher, published = detail.publishedDate or detail.publishedYear, + language = detail.language, isbn = detail.isbn13 or detail.isbn10, + }, + } +end + +--- 详情:写回作者 / 简介 / 系列 / 扩展元数据,回调原始详情(开书要 files)。 +---@param stable_id string +---@param cb fun(detail: table|nil, err: string|nil) +---@return HttpJob +function Source:detail(stable_id, cb) + return self.client:json("GET", "/koreader/plugin/catalog/books/" .. stable_id, { deviceId = deviceId() }, nil, + function(detail, err) + if not detail then return cb(nil, err) end + require("book.store").rememberMany({ detailRow(self.id, stable_id, detail) }) + cb(detail) + end) +end + +---@param identity BookIdentity +---@param cb fun(book: Book|nil, err: string|nil) +---@return { cancel: fun() } +function Source:getDetailAsync(identity, cb) + return self:detail(identity.stable_id, function(detail, err) + if not detail then return cb(nil, err) end + cb(detailRow(self.id, identity.stable_id, detail)) + end) +end + +--- 下载到 `<工作目录>/..part`,完整后改名并登记路径:中途断掉不会留下半个文件被当成已下载。 +---@param identity BookIdentity +---@param file table KoreaderCatalogFile +---@param title string|nil +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Source:fetchFile(identity, file, title, cb) + local Paths = require("utils.paths") + Paths.ensureBookWork(identity.stable_id, self.id) + local path = T("%1/%2.%3", Paths.bookWorkDir(identity.stable_id, self.id), file.id, file.format:lower()) + local part = path .. ".part" + local dialog = require("ui.themes.widgets.progress_dialog"):new{ title = title, dismissable = false } + dialog:show() + dialog:set(_("正在下载…")) + local job = self.client:download(file.id, part, function(bytes, total) + total = total or tonumber(file.sizeBytes) + if total and total > 0 then dialog:bytes(bytes, total) end + end, function(ok, err) + dialog:close() + if not ok then + os.remove(part) + return cb(nil, err or _("下载失败")) + end + if not os.rename(part, path) or not validFile(path) then + os.remove(part) + os.remove(path) + return cb(nil, _("下载文件校验失败")) + end + local registered, rerr = require("book.store").touch(path, identity) + cb(registered and path or nil, rerr) + end) + return { cancel = function() + job:cancel() + dialog:close() + end } +end + +--- 打开:已下载的直接开(不联网);否则取详情挑文件下载。 +function Source:openBookAsync(identity, _opts, cb) + local path = downloaded(identity.stable_id) + if path then return SourceBase.defer(cb, path) end + if not online() then return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) end + local cancelled = false + ---@type { cancel: fun() } + local job + local function finish(file, err) + if not cancelled then cb(file, err) end + end + job = self:detail(identity.stable_id, function(detail, err) + if cancelled then return end + if not detail then return finish(nil, err) end + local file = pickFile(detail.files) + if not file then return finish(nil, _("这本书没有 KOReader 能打开的文件")) end + job = self:fetchFile(identity, file, detail.title, finish) + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +---@param identity BookIdentity +---@return BookCoverRequest|nil, string|nil +function Source:coverRequest(identity) + if not self:configured() then return nil, _("未配置") end + return { + url = self.client:url("/koreader/plugin/catalog/books/" .. identity.stable_id .. "/thumbnail"), + headers = self.client:headers(), + } +end + +--- kosync 进度 → 月读位置;与本地同一 xpointer / 页时交回本地行(不算冲突)。 +---@param stable_id string +---@param remote { percentage: number, progress: string|nil, timestamp: number|nil } +---@return ProgressPosition +local function position(stable_id, remote) + local progress = type(remote.progress) == "string" and remote.progress or "" + local page = tonumber(progress) + local here = require("book.progress_db").get(ID, stable_id) + if here and ((progress ~= "" and here.locator == progress) or (page and here.page == page)) then + return here + end + return { + fraction = math.max(0, math.min(1, tonumber(remote.percentage) or 0)), + locator = progress:sub(1, 1) == "/" and progress or nil, + page = page and math.floor(page) or nil, + updated_at = tonumber(remote.timestamp), + } +end + +function Source:getProgressAsync(identity, cb) + local digest = digestOf(identity.stable_id) + if not digest then return SourceBase.defer(cb, nil, nil, { empty = true }) end + return self.client:json("GET", "/koreader/syncs/progress/" .. digest, nil, nil, function(remote, err) + if not remote then return cb(nil, err) end + -- 服务端没有这本书或没有进度都回 {}。 + if type(remote.percentage) ~= "number" then return cb(nil, nil, { empty = true }) end + cb(position(identity.stable_id, remote)) + end) +end + +--- 月读位置 → kosync:流式文档推 xpointer,固定版式推页码。timestamp 用进度自己的时间, +--- 服务端会丢弃比已知更旧的推送,离线攒下的旧进度不会盖掉别处更新的位置。 +function Source:putProgressAsync(identity, pos, cb) + local digest = digestOf(identity.stable_id) + if not digest then return SourceBase.defer(cb, nil, _("这本书还没下载,无法同步")) end + return self.client:json("PUT", "/koreader/syncs/progress", nil, { + document = digest, + percentage = math.max(0, math.min(1, tonumber(pos.fraction) or 0)), + progress = pos.locator or (pos.page and tostring(pos.page)) or nil, + device = deviceModel(), + device_id = deviceId(), + timestamp = pos.updated_at or os.time(), + }, function(data, err, code) + if code == 404 then return cb(nil, _("BookOrbit 不认识本地这个文件,可能服务端的书已更换")) end + cb(data and true, err) + end) +end + +--- 按 UTF-8 字符边界截断(服务端按字符数限长;截成半个字符整块请求会被拒)。 +---@param s any +---@param max integer +---@return string|nil +local function cut(s, max) + if type(s) ~= "string" then return nil end + if #s <= max then return s end + local out = s:sub(1, max) + local next_byte = s:byte(max + 1) + if next_byte >= 0x80 and next_byte < 0xC0 then + out = out:gsub("[\192-\255][\128-\191]*$", "") + end + return out +end + +--- 位置序列化与官方插件一致:服务端注解键 = md5(datetime|pos0),写法不同就会重复建。 +---@param pos any +---@return string|nil, string|nil +local function serializePos(pos) + if type(pos) == "string" then return pos, "xpointer" end + if type(pos) == "table" and type(pos.page) == "number" then + return string.format('{"page":%d,"x":%.2f,"y":%.2f}', pos.page, tonumber(pos.x) or 0, tonumber(pos.y) or 0), "pdf" + end + return nil +end + +---@param value any +---@return string|nil +local function datetime(value) + return type(value) == "string" and value:match(DATETIME) and value or nil +end + +--- 月读注解快照 → 服务端 KoreaderAnnotationDto;书签(无 drawer)不传。 +---@param annotations table[] +---@return table[] +local function changesOf(annotations) + local out = {} + for _idx, ann in ipairs(annotations) do + local pos0, format = serializePos(ann.pos0) + if DRAWERS[ann.drawer] and datetime(ann.datetime) and pos0 then + out[#out + 1] = { + datetime = ann.datetime, + datetimeUpdated = datetime(ann.datetime_updated), + drawer = ann.drawer, + color = cut(ann.color, 30), + text = cut(ann.text, 10000), + note = cut(ann.note, 5000), + chapter = cut(ann.chapter, 500), + pageno = type(ann.pageno) == "number" and ann.pageno >= 0 and math.floor(ann.pageno) or nil, + posFormat = format, + pos0 = cut(pos0, 4000), + pos1 = cut((serializePos(ann.pos1)), 4000), + } + end + end + return out +end + +--- 划线整份上传(服务端按 datetime|pos0 去重,重传是空操作),每次 50 条。 +--- keysComplete = false:不让服务端拿这份清单推断「设备删了哪些」;服务端回传的改动不 ack,留在服务端。 +---@param identity BookIdentity +---@param annotations table[] +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Source:pushNotesAsync(identity, annotations, cb) + local digest = digestOf(identity.stable_id) + if not digest then return SourceBase.defer(cb, nil, _("这本书还没下载,无法同步")) end + local pending = changesOf(annotations) + if #pending == 0 then return SourceBase.defer(cb, true) end + local cursor, cancelled = 1, false + ---@type HttpJob + local job + local function nextChunk() + if cursor > #pending then return cb(true) end + local chunk = {} + for idx = cursor, math.min(cursor + CHUNK - 1, #pending) do chunk[#chunk + 1] = pending[idx] end + cursor = cursor + #chunk + job = self.client:json("POST", "/koreader/plugin/annotations/exchange", nil, withDevice({ + -- 空表默认编码成 {},服务端要数组。 + books = { { hash = digest, keys = require("json").util.InitArray({}), keysComplete = false, changes = chunk } }, + }), function(data, err) + if cancelled then return end + if not data then return cb(nil, err) end + for _idx, hash in ipairs(data.unmatched or {}) do + if hash == digest then return cb(nil, _("BookOrbit 不认识本地这个文件,可能服务端的书已更换")) end + end + nextChunk() + end) + end + nextChunk() + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +return { meta = meta, new = new, ID = ID } diff --git a/moonsource-bookorbit.koplugin/moonsource_bookorbit/version.lua b/moonsource-bookorbit.koplugin/moonsource_bookorbit/version.lua new file mode 100644 index 0000000..25b37f6 --- /dev/null +++ b/moonsource-bookorbit.koplugin/moonsource_bookorbit/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/bookorbit/source_spec.lua b/tests/bookorbit/source_spec.lua new file mode 100644 index 0000000..b4dc35d --- /dev/null +++ b/tests/bookorbit/source_spec.lua @@ -0,0 +1,380 @@ +--[[-- +extensions/moonsource-bookorbit.koplugin:经源注册表发现;书架(按库分页、库名分类、空库保护)、 +开书(挑格式、下载、失败清理)、封面、详情、kosync 进度双向、划线上传。HTTP 与书库全部打桩。 + +@module tests.moonsource_bookorbit.source_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Stubs = require("support.stubs") +local Themed = require("support.theme_stubs") + +-- 往返桩:encode 登记表并发一个令牌串,decode 凭令牌取回(不是令牌就报错,同真解析器)。 +local encoded = {} +local ARRAY = {} +-- decode 同 LuaJSON 是可调用表,带 simple 模式(null → nil)。 +local SIMPLE = {} +local decode_mode +local JSON = { + encode = function(value) + encoded[#encoded + 1] = value + return "\0json" .. #encoded + end, + decode = setmetatable({ simple = SIMPLE }, { __call = function(_self, text, mode) + decode_mode = mode + return encoded[tonumber(text:match("^%z?json(%d+)$"))] or error("not json: " .. text) + end }), + util = { InitArray = function(t) return setmetatable(t, ARRAY) end }, +} +package.loaded["json"] = JSON +Themed.install() +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-bookorbit.koplugin/moonsource_bookorbit") +-- 走 preload 不改 package.path:runner 只还原 preload/loaded,插件根上的 main.lua 会顶掉月读的 main。 +for _idx, name in ipairs({ "client", "source", "setting" }) do + package.preload["moonsource_bookorbit" .. (name == "source" and ".source" or "." .. name)] = function() + return dofile(PLUGIN .. "/" .. (name == "source" and "source" or name) .. ".lua") + end +end + +local cfg = { server_url = " http://bo/api/v1/ ", username = " ann ", userkey = "k" } +local saved_cfg +package.preload["utils.settings"] = function() + local common = { active_source = "local" } + return { + get = function() return common end, + save = function() end, + getSource = function() return cfg end, + saveSource = function(_id, value) saved_cfg = value end, + } +end +for _idx, id in ipairs({ "local", "moon", "wechat", "jdread", "copymanga", "fanqie" }) do + package.loaded["source." .. id] = { + meta = function() return { id = id, name = id, type = "book" } end, + new = function() return { id = id } end, + } +end + +local online = true +package.loaded["ui/network/manager"] = { isConnected = function() return online end } +_G.G_reader_settings = { readSetting = function(_self, key) return key == "device_id" and "dev-1" or nil end } +package.loaded["device"] = { model = "Kindle" } +package.loaded["util"] = { partialMD5 = function(path) return path:match("/1/12%.epub$") and ("a"):rep(32) or ("b"):rep(32) end } + +-- HTTP:按 "METHOD /path" 路由;值为响应表或 fun(opts) → 响应表。 +local routes, calls = {}, {} +local download = { code = 200, body = "PK\3\4epub" } +package.loaded["http.request"] = { + ok = function(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 + end, + request = function(opts, cb) + calls[#calls + 1] = opts + local route = routes[opts.method .. " " .. opts.url:match("^http://bo/api/v1(/[^?]*)")] + require("ui/uimanager"):nextTick(function() + cb(type(route) == "function" and route(opts) or route or { code = 404, body = "" }) + end) + return { cancel = function() end } + end, + download = function(opts, dest, cb) + calls[#calls + 1] = opts + local file = assert(io.open(dest, "wb")) + file:write(download.body) + file:close() + require("ui/uimanager"):nextTick(function() cb(true, nil, { code = download.code }) end) + return { cancel = function() end } + end, +} +local function json(data) return { code = 200, body = JSON.encode(data) } end +local function query(opts, key) return opts.url:match("[?&]" .. key .. "=([^&]*)") end + +local books, progress, remembered, touched, reconciled = {}, {}, {}, {}, nil +package.loaded["book.books_db"] = { get = function(_sid, id) return books[id] end } +package.loaded["book.progress_db"] = { get = function(_sid, id) return progress[id] end } +package.loaded["book.store"] = { + touch = function(path, ref) + touched[#touched + 1] = { path = path, stable_id = ref.stable_id } + books[ref.stable_id] = { path = path } + return true + end, + rememberMany = function(list) + for _idx, book in ipairs(list) do remembered[book.stable_id] = book end + end, +} +package.loaded["source.shelf"] = { + reconcile = function(source_id, list) + reconciled = { source_id = source_id, books = list } + return { pulled = #list, pushed = 0, hidden = 0, conflicts = 0, skipped = false } + end, +} +local WORK = Config.dir() .. "/bookorbit_spec" +os.execute("rm -rf '" .. WORK .. "'") +package.loaded["utils.paths"] = { + ensureBookWork = function(id) os.execute("mkdir -p '" .. WORK .. "/" .. id .. "'") end, + bookWorkDir = function(id) return WORK .. "/" .. id end, +} + +package.loaded["pluginloader"] = { enabled_plugins = { Config.selfPlugin() } } +package.loaded["source.registry"] = nil +package.preload["source.bookorbit"] = function() return require("moonsource_bookorbit.source") end +local Registry = require("source.registry") + +Assert.eq(Registry.meta("bookorbit").type, "book") +local source = Registry.resolve("bookorbit") +Assert.is_true(source:configured()) + +---@return any, any, any +local function run(method, ...) + local a, b, c + local n = select("#", ...) + local args = { ... } + args[n + 1] = function(x, y, z) a, b, c = x, y, z end + source[method](source, unpack(args, 1, n + 1)) + Stubs.flush() + return a, b, c +end + +-- 地址照抄 /api/v1 也认;用户名去首尾空白。 +local Client = require("moonsource_bookorbit.client") +Assert.eq(Client.normalizeUrl(" https://b.example.com/api/v1/koreader/ "), "https://b.example.com") +Assert.is_false(Client.new({ server_url = "http://x", username = "u" }):configured()) + +-- 书架:全部书库(未选)→ 逐库分页,库名即分类,作者合并。 +routes["GET /koreader/plugin/catalog/sections/libraries"] = json({ items = { + { id = "1", title = "小说" }, { id = "2", title = "漫画" }, +} }) +routes["GET /koreader/plugin/catalog/books"] = function(opts) + local lib, page = query(opts, "libraryId"), query(opts, "page") + if lib == "1" and page == "1" then + return json({ hasNext = true, items = { { id = 1, title = "长夜", authors = { "甲", "乙" }, seriesName = "夜", readStatus = "read" } } }) + end + if lib == "1" then return json({ hasNext = false, items = { { id = 2, title = "白昼", authors = {} } } }) end + return json({ hasNext = false, items = { { id = 3, title = "图册", readStatus = "reading" } } }) +end +local result = run("syncBooksAsync", nil) +Assert.eq(result.pulled, 3) +Assert.eq(reconciled.source_id, "bookorbit") +Assert.eq(reconciled.books[1].stable_id, "1") +Assert.eq(reconciled.books[1].authors, "甲 / 乙") +Assert.eq(reconciled.books[1].series, "夜") +Assert.eq(reconciled.books[1].category, "小说") +Assert.is_nil(reconciled.books[2].authors) +Assert.eq(reconciled.books[1].percent, 100) +Assert.is_nil(reconciled.books[3].percent) +Assert.eq(reconciled.books[3].category, "漫画") +Assert.eq(calls[1].headers["x-auth-user"], "ann") +Assert.eq(calls[1].headers["x-auth-key"], "k") +Assert.eq(query(calls[2], "sort"), "title") +Assert.is_true(run("syncBooksAsync", { dirty_only = true }).skipped, "没有删书接口,只推脏行时跳过") + +-- 选了书库只拉选中的;选中的库都没了不能拿空列表对账(会把书架判成远端已删)。 +cfg.libraries = { ["2"] = true } +reconciled = nil +Assert.len(run("syncBooksAsync", nil) and reconciled.books, 1) +cfg.libraries = { ["9"] = true } +reconciled = nil +local none, err = run("syncBooksAsync", nil) +Assert.is_nil(none) +Assert.matches(err, "书库") +Assert.is_nil(reconciled) +cfg.libraries = nil + +-- 鉴权失败给可读提示。 +routes["GET /koreader/plugin/catalog/sections/libraries"] = { code = 401, body = "" } +none, err = run("syncBooksAsync", nil) +Assert.is_nil(none) +Assert.matches(err, "密码") + +-- 开书:详情写回元数据,按偏好挑 epub(不挑有声书 / pdf),下载原件并登记路径。 +routes["GET /koreader/plugin/catalog/books/1"] = function(opts) + Assert.eq(query(opts, "deviceId"), "dev-1") + return json({ id = 1, title = "长夜", authors = { "甲" }, description = "简介", seriesName = "夜", + publisher = "某出版社", publishedDate = "2008-01-01T00:00:00.000Z", publishedYear = 2008, + language = "zh", isbn10 = "7000000000", isbn13 = "9787000000000", rating = 5, files = { + { id = 10, format = "m4b" }, { id = 11, format = "PDF" }, { id = 12, format = "EPUB", sizeBytes = 9 }, + } }) +end +local path = run("openBookAsync", { source_id = "bookorbit", stable_id = "1" }, nil) +Assert.eq(path, WORK .. "/1/12.epub") +Assert.eq(touched[1].stable_id, "1") +Assert.eq(remembered["1"].intro, "简介") +Assert.eq(remembered["1"].authors, "甲") +Assert.eq(remembered["1"].meta.publisher, "某出版社") +Assert.eq(remembered["1"].meta.published, "2008-01-01T00:00:00.000Z", "原样交给 BookDB 规范化") +Assert.eq(remembered["1"].meta.language, "zh") +Assert.eq(remembered["1"].meta.isbn, "9787000000000", "优先 ISBN-13") +Assert.is_nil(remembered["1"].meta.rating, "用户自评分不当公共评分") +Assert.matches(calls[#calls].url, "/koreader/plugin/catalog/files/12/download$") +Assert.eq(calls[#calls].headers["x-auth-key"], "k", "下载带鉴权头") +Assert.is_nil(io.open(path .. ".part"), "临时文件改名后不留") + +-- 已下载:直接开,不联网。 +online = false +local before = #calls +Assert.eq(run("openBookAsync", { source_id = "bookorbit", stable_id = "1" }, nil), path) +Assert.eq(#calls, before) +local offline, oerr = run("openBookAsync", { source_id = "bookorbit", stable_id = "2" }, nil) +Assert.is_nil(offline) +Assert.matches(oerr, "网络不可用") +online = true + +-- 没有能开的格式;下载非 2xx / 文件头不对都删文件报错。 +routes["GET /koreader/plugin/catalog/books/2"] = json({ id = 2, title = "听书", files = { { id = 20, format = "m4b" } } }) +local failed, ferr = run("openBookAsync", { source_id = "bookorbit", stable_id = "2" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "没有 KOReader 能打开") +routes["GET /koreader/plugin/catalog/books/3"] = json({ id = 3, title = "坏书", files = { { id = 30, format = "epub" } } }) +download.code, download.body = 500, "oops" +failed, ferr = run("openBookAsync", { source_id = "bookorbit", stable_id = "3" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "500") +Assert.is_nil(io.open(WORK .. "/3/30.epub.part")) +download.code = 200 +failed, ferr = run("openBookAsync", { source_id = "bookorbit", stable_id = "3" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "校验失败") +Assert.is_nil(io.open(WORK .. "/3/30.epub")) +download.body = "PK\3\4epub" + +-- 详情页补简介。 +local detail = run("getDetailAsync", { source_id = "bookorbit", stable_id = "1" }) +Assert.eq(detail.intro, "简介") +Assert.eq(detail.title, "长夜") +Assert.eq(detail.meta.isbn, "9787000000000") +Assert.eq(decode_mode, SIMPLE, "响应按 simple 模式解析(null → nil)") +routes["GET /koreader/plugin/catalog/books/4"] = json({ id = 4, title = "无日期", publishedYear = 1999, files = {} }) +Assert.eq(run("getDetailAsync", { source_id = "bookorbit", stable_id = "4" }).meta.published, 1999, "没有日期退到年份") +-- 简介若带 HTML(BookOrbit 常见),入库前剥成纯文本,详情页不再露出 div/p。 +routes["GET /koreader/plugin/catalog/books/5"] = json({ + id = 5, title = "带标签", description = "

第一段

第二段&续

", files = {}, +}) +Assert.eq(run("getDetailAsync", { source_id = "bookorbit", stable_id = "5" }).intro, "第一段\n第二段&续") +Assert.eq(remembered["5"].intro, "第一段\n第二段&续") + +-- 封面:缩略图接口带鉴权头。 +local cover = source:coverRequest({ stable_id = "1" }) +Assert.eq(cover.url, "http://bo/api/v1/koreader/plugin/catalog/books/1/thumbnail") +Assert.eq(cover.headers["x-auth-user"], "ann") + +-- 拉进度:按本地文件摘要查;xpointer → locator;同一 xpointer 交回本地行;{} 算空;没下载算空。 +local book1 = { source_id = "bookorbit", stable_id = "1" } +local DIGEST = ("a"):rep(32) +local remote = { percentage = 0.42, progress = "/body/DocFragment[3]/body/p[2]/text().0", timestamp = 1700000000 } +routes["GET /koreader/syncs/progress/" .. DIGEST] = function() return json(remote) end +local pos, perr0 = run("getProgressAsync", book1) +Assert.is_nil(perr0) +Assert.eq(pos.fraction, 0.42) +Assert.eq(pos.locator, remote.progress) +Assert.is_nil(pos.page) +Assert.eq(pos.updated_at, 1700000000) +progress["1"] = { locator = remote.progress, fraction = 0.4 } +Assert.eq(run("getProgressAsync", book1), progress["1"]) +remote = { percentage = 0.5, progress = "12" } +pos = run("getProgressAsync", book1) +Assert.eq(pos.page, 12) +Assert.is_nil(pos.locator) +remote = {} +local empty, _e, meta = run("getProgressAsync", book1) +Assert.is_nil(empty) +Assert.is_true(meta.empty) +_e, _e, meta = run("getProgressAsync", { source_id = "bookorbit", stable_id = "9" }) +Assert.is_true(meta.empty, "没下载没有摘要") + +-- 推进度:xpointer / 页码串,时间用进度自己的;404 = 服务端不认识文件。 +local sent +routes["PUT /koreader/syncs/progress"] = function(opts) + sent = JSON.decode(opts.body) + return json({ document = sent.document }) +end +Assert.is_true(run("putProgressAsync", book1, { fraction = 0.3, locator = "/body/p[1]", updated_at = 1700000001 })) +Assert.eq(sent.document, DIGEST) +Assert.eq(sent.progress, "/body/p[1]") +Assert.eq(sent.percentage, 0.3) +Assert.eq(sent.timestamp, 1700000001) +Assert.eq(sent.device_id, "dev-1") +Assert.eq(sent.device, "Kindle") +run("putProgressAsync", book1, { fraction = 1.2, page = 7, total_pages = 9 }) +Assert.eq(sent.progress, "7") +Assert.eq(sent.percentage, 1) +routes["PUT /koreader/syncs/progress"] = { code = 404, body = "" } +local okp, perr = run("putProgressAsync", book1, { fraction = 0.3 }) +Assert.is_nil(okp) +Assert.matches(perr, "不认识") + +-- 划线:只传带 drawer 的高亮,分块 50 条;keys 是空数组、keysComplete=false(不让服务端推断删除)。 +local exchanged = {} +routes["POST /koreader/plugin/annotations/exchange"] = function(opts) + exchanged[#exchanged + 1] = JSON.decode(opts.body) + return json({ results = { {} }, unmatched = {} }) +end +local anns = { + { datetime = "2026-10-01 10:00:00", datetime_updated = "bad", drawer = "lighten", color = "yellow", + text = "春眠不觉晓", note = "好诗", chapter = "一", pageno = 3, pos0 = "/body/p[1]/text().0", pos1 = "/body/p[1]/text().5" }, + { datetime = "2026-10-01 10:00:01", drawer = "underscore", text = "图", pos0 = { page = 2, x = 1, y = 2.345 }, + pos1 = { page = 2, x = 3, y = 4 } }, + { datetime = "2026-10-01 10:00:02", text = "书签", pos0 = "/body/p[2]" }, + { datetime = "昨天", drawer = "lighten", pos0 = "/body/p[3]" }, +} +for idx = 1, 55 do + anns[#anns + 1] = { datetime = "2026-10-02 10:00:00", drawer = "lighten", text = ("长"):rep(4000), + pos0 = "/body/p[" .. (idx + 10) .. "]" } +end +Assert.is_true(run("pushNotesAsync", book1, anns)) +Assert.len(exchanged, 2, "57 条分两块") +local first = exchanged[1] +Assert.eq(first.deviceId, "dev-1") +Assert.eq(first.pluginVersion, "moon-1.0") +Assert.matches(first.deviceTime, "^%d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d$") +local book = first.books[1] +Assert.eq(book.hash, DIGEST) +Assert.is_false(book.keysComplete) +Assert.eq(getmetatable(book.keys), ARRAY, "空 keys 必须编码成数组") +Assert.len(book.changes, 50) +Assert.len(exchanged[2].books[1].changes, 7) +local c1, c2 = book.changes[1], book.changes[2] +Assert.eq(c1.posFormat, "xpointer") +Assert.eq(c1.pos1, "/body/p[1]/text().5") +Assert.is_nil(c1.datetimeUpdated, "非法时间不传") +Assert.eq(c1.note, "好诗") +Assert.eq(c1.pageno, 3) +Assert.eq(c2.posFormat, "pdf") +Assert.eq(c2.pos0, '{"page":2,"x":1.00,"y":2.35}', "与官方插件同一种序列化,注解键才对得上") +Assert.eq(#book.changes[3].text, 9999, "超长按 UTF-8 字符边界截断") + +-- 服务端不认识文件:报错,核心留脏重试;没有高亮不发请求。 +routes["POST /koreader/plugin/annotations/exchange"] = json({ results = {}, unmatched = { DIGEST } }) +local okn, nerr = run("pushNotesAsync", book1, { anns[1] }) +Assert.is_nil(okn) +Assert.matches(nerr, "不认识") +before = #calls +Assert.is_true(run("pushNotesAsync", book1, { anns[3] })) +Assert.eq(#calls, before) + +-- 设备 id:KOReader 没有(或格式不合)时自己生成一次并保存。 +_G.G_reader_settings = { readSetting = function() return "has space" end } +routes["PUT /koreader/syncs/progress"] = function(opts) + sent = JSON.decode(opts.body) + return json({}) +end +run("putProgressAsync", book1, { fraction = 0.1 }) +Assert.matches(sent.device_id, "^%x+$") +Assert.eq(saved_cfg.device_id, sent.device_id) + +-- 设置:密码只存 MD5,空串清掉;装了官方插件且有账号时多一行导入。 +local Setting = require("moonsource_bookorbit.setting") +local key_field = Setting.remote[3] +Assert.eq(key_field.key, "userkey") +Assert.is_true(key_field.secret) +Assert.eq(key_field.normalize(" pw "), require("ffi/sha2").md5("pw")) +Assert.eq(key_field.normalize(" "), "") +Assert.eq(Setting.remote[1].normalize("http://x/api/v1/"), "http://x") +Assert.len(Setting.rows(), 6, "已填账号时多一行退出登录") +_G.G_reader_settings = { readSetting = function(_self, key) + return key == "bookorbit" and { server_url = "http://bo/api/v1", username = "u", userkey = "kk" } or nil +end } +Assert.len(Setting.rows(), 7, "官方插件账号再多一行导入") +_G.G_reader_settings = nil + +os.execute("rm -rf '" .. WORK .. "'") 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 "$@"