commit 1dd1cccb68e3dbcdcd69d963b29f13062e3e458a Author: Garfield Date: Fri Nov 27 13:00:01 2026 +0800 :sparkles: (kmoe): 新增 Kmoe 漫画书源,按卷下载 EPUB 阅读 书城搜索与筛选、详情、卷列表、整卷 EPUB 下载与缓存、收藏书架同步。 支持邮箱密码、浏览器授权、粘贴 Cookie 登录;下载要求 UA 与登录时一致, 会话 UA 随 Cookie 一起保存。 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..a015476 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 更新日志 + +## 0.0.1 + +- 新增「Kmoe」书源:书城分类与排序、搜索、漫画详情。 +- 登录后看卷列表,按卷下载 EPUB 阅读;收藏夹与月读书架双向同步。 +- 支持邮箱密码登录、浏览器授权、粘贴 Cookie,不保存密码。 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..f5576c8 --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# 月读书源:Kmoe + +给月读增加「Kmoe」在线书源的 KOReader 插件。本仓库只含这一个插件,独立维护、独立发版,全部书源见 [moon-source 组织](https://git.garfieldho.me/moon-source)。 + +## 免责声明 + +- 本仓库与「Kmoe」官方**没有任何关联**,所有商标、书名、内容归原权利人所有。 +- 插件只是在用户自己的账号、自己的设备上,按用户本人已有的权限读取内容;不提供、不分发任何书籍内容,也不绕过付费。 +- 使用可能违反对应平台的用户协议,账号可能被限制或封禁。是否使用、风险如何,由使用者自行判断并承担。 +- 权利人认为本仓库内容有问题,请通过仓库 issue 联系,核实后会及时处理。 + +## 安装 + +1. 先装好月读。 +2. 从 [Release](../../releases) 下载 `moonsource-kmoe.koplugin-<版本>.zip`,解压出 `moonsource-kmoe.koplugin` 目录,整个复制到 KOReader 的 `plugins/` 下。 +3. 重启 KOReader,在月读的书源列表里启用。 + +书源 id 是 `kmoe`。能力和限制见 [moonsource_kmoe/README.md](moonsource-kmoe.koplugin/moonsource_kmoe/README.md)。 + +## 更新 + +在月读的「书库 → Kmoe 更新」里有「检查书源插件更新」和「自动检查书源插件更新」(默认开,每 24 小时一次,只提示、不静默安装)。 +本插件只检查并更新自己(本仓库的 Release),校验值取自 Release 的 `SHA256SUMS`,装完重启 KOReader。 + +## 发布 + +推送 `vX.Y.Z` 标签(带 `-` 的如 `v1.2.0-rc.1` 为预发布),Forgejo Actions 会打包 `moonsource-kmoe.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/kmoe/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-kmoe.koplugin/_meta.lua b/moonsource-kmoe.koplugin/_meta.lua new file mode 100644 index 0000000..dabe2c9 --- /dev/null +++ b/moonsource-kmoe.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:Kmoe"), + description = _("给月读增加「Kmoe」漫画书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-kmoe.koplugin/main.lua b/moonsource-kmoe.koplugin/main.lua new file mode 100644 index 0000000..6393b73 --- /dev/null +++ b/moonsource-kmoe.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_kmoe", + is_doc_only = false, +} diff --git a/moonsource-kmoe.koplugin/moon_source.lua b/moonsource-kmoe.koplugin/moon_source.lua new file mode 100644 index 0000000..3cf86a1 --- /dev/null +++ b/moonsource-kmoe.koplugin/moon_source.lua @@ -0,0 +1,17 @@ +--[[-- +月读第三方书源描述:Kmoe。契约见月读 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_kmoe.source").meta() end, + new = function() return require("moonsource_kmoe.source").new() end, + setting = lazy("moonsource_kmoe.setting"), +} diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/README.md b/moonsource-kmoe.koplugin/moonsource_kmoe/README.md new file mode 100644 index 0000000..83e1276 --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/README.md @@ -0,0 +1,20 @@ +# Kmoe + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 邮箱密码登录 | 支持 | 保存前打开「我的」页校验账号;不保存密码;用插件固定的电脑版 UA 登录 | +| 浏览器授权 | 支持 | 需要能回传浏览器 UA 的新版 moon-cookie-storage 扩展;旧版扩展授权后只能浏览、同步书架,不能下载 | +| 粘贴 Cookie | 支持 | 要同时填同一浏览器的 User-Agent,不填只能浏览、同步书架,不能下载 | +| 扫码、验证码登录 | 不支持 | 网站登录页没有这两种方式 | +| 搜索与书城 | 支持 | 排序、连载状态、语言、分类筛选,每页 21 部,默认聚合约 60 部;无需登录 | +| 详情 | 支持 | 作者、分类、简介、封面;无需登录 | +| 卷列表 | 支持 | 需要登录;一卷是一章,单行本、话、番外按网站顺序排列 | +| 漫画阅读 | 支持 | 整卷下载 EPUB(普通线路);网站要求账号先验证手机号,并消耗账号下载额度;下载要求 UA 与登录时完全一致 | +| 卷缓存与离线阅读 | 支持 | 只在打开或手动缓存时下载,不做阅读期预取;已下载的卷离线可读;批量缓存未实测 | +| 书架拉取 | 支持 | 网站「收藏」即书架,只订阅不收藏的书不算;收藏页出现分页时不按缺席下架 | +| 书架新增与移出 | 支持 | 改网站收藏,之后重新拉取书架确认 | +| 阅读进度同步 | 不支持 | 网站没有阅读进度接口,只保存本地进度 | +| 笔记与统计同步 | 不支持 | 仅本地保存 | +| 书评 | 不支持 | 网站有整书书评,插件未接入 | +| 章评、段评与回复 | 不支持 | 网站只有整书书评 | +| 账号切换 | 已实现,未实测 | 按数字账号区分;换号时清掉旧账号的本地书架和阅读记录 | diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/_meta.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/_meta.lua new file mode 100644 index 0000000..d6bb9b7 --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/_meta.lua @@ -0,0 +1,15 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。 + +@module moonsource_kmoe._meta +--]] + +local _ = require("l10n").get("moonsource_kmoe") + +return { + id = "kmoe", + name = _("Kmoe"), + type = "chapter", + description = _("Kmoe 漫画,按卷下载 EPUB 阅读"), + abilities = { _("搜索与发现"), _("书架同步") }, +} diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/chapter.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/chapter.lua new file mode 100644 index 0000000..ef87296 --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/chapter.lua @@ -0,0 +1,119 @@ +--[[-- +Kmoe 一卷 = 一章:取下载地址,把整卷 EPUB 下到书目录,按卷号命名。 + +一卷几十 MB,而且占用账号的下载额度,所以只在打开或用户点缓存时下载,不做阅读期预取。 + +@module moonsource_kmoe.chapter +--]] + +local Paths = require("utils.paths") +local _ = require("l10n").get("moonsource_kmoe") + +local Chapter = {} + +---@param identity BookIdentity +---@param chapter BookChapter +---@return string +function Chapter.path(identity, chapter) + return Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/" .. chapter.uid .. ".epub" +end + +--- 文件是完整的 EPUB(zip 头)。 +---@param path string +---@return boolean +local function isEpub(path) + local f = io.open(path, "rb") + if not f then return false end + local head = f:read(4) + f:close() + return head == "PK\3\4" +end + +--- 已下载好的卷;没有则 nil。 +---@param identity BookIdentity +---@param chapter BookChapter +---@return string|nil +function Chapter.existing(identity, chapter) + local path = Chapter.path(identity, chapter) + return isEpub(path) and path or nil +end + +--- 下载一卷;已有文件直接复用。 +---@param client KmoeClient +---@param identity BookIdentity +---@param chapter KmoeChapter +---@param on_progress fun(bytes: number, total: number|nil)|nil +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Chapter.materializeAsync(client, identity, chapter, on_progress, cb) + local SourceBase = require("source.base") + local path = Chapter.existing(identity, chapter) + if path then return SourceBase.defer(cb, path) end + if chapter.building then + return SourceBase.defer(cb, nil, _("这一卷的 EPUB 还在制作中,过一阵再试")) + end + Paths.ensureBookWork(identity.stable_id, identity.source_id) + path = Chapter.path(identity, chapter) + local handle = {} + handle.inner = client:downUrlAsync(chapter.origin, function(url, err) + if handle.cancelled then return end + if not url then cb(nil, err); return end + handle.inner = require("http.request").download({ + url = url, + headers = { ["User-Agent"] = client.ua, ["Referer"] = client.BASE .. "/" }, + timeout = require("http.timeout").net(20), + max_bytes = 1024 * 1024 * 1024, + resume = true, + on_progress = on_progress, + }, path, function(ok, download_err) + if handle.cancelled then return end + if not ok then cb(nil, download_err or _("下载失败")); return end + if not isEpub(path) then + os.remove(path) + cb(nil, _("Kmoe 返回的不是 EPUB 文件")) + return + end + cb(path) + end) + end) + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +--- 顺序下载 from_idx+1 起的 count 卷;单卷失败不阻断后面。 +---@param client KmoeClient +---@param identity BookIdentity +---@param toc KmoeChapter[] +---@param from_idx integer +---@param count integer +---@param progress fun(done: integer, total: integer)|nil +---@param cb fun(cached: integer, total: integer, failed: integer, err: string|nil) +---@return { cancel: fun() } +function Chapter.cacheAsync(client, identity, toc, from_idx, count, progress, cb) + local handle, cached, failed, last_err = {}, 0, 0, nil + local last = math.min(#toc, from_idx + count) + local total = math.max(0, last - from_idx) + local idx = from_idx + local function step() + if handle.cancelled then return end + idx = idx + 1 + if idx > last then cb(cached, total, failed, last_err); return end + handle.inner = Chapter.materializeAsync(client, identity, toc[idx], nil, function(path, err) + if handle.cancelled then return end + if path then cached = cached + 1 else failed, last_err = failed + 1, err end + if progress then progress(cached + failed, total) end + step() + end) + end + step() + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +return Chapter diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/client.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/client.lua new file mode 100644 index 0000000..729d0cd --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/client.lua @@ -0,0 +1,257 @@ +--[[-- +Kmoe(mox.moe)HTTP 客户端。 + +书单 / 搜索走公开 JSON `data_list.php`,不带账号 Cookie;详情、卷列表、书架、收藏、下载带登录 Cookie。 +需要登录的页面在未登录时 302 到 login.php;没做手机验证的账号取下载地址会 302 到 regphone.php。 +请求一律不跟随跳转,跳转目标就是错误类型。 + +取下载地址要求 UA 与登录时逐字一致,否则 403(普通页面不查)。所以会话的 UA 跟 Cookie 一起保存: +密码登录用这里的固定电脑版 UA;浏览器授权和粘贴 Cookie 用那个浏览器自己的 UA。 + +@module moonsource_kmoe.client +--]] + +local Mapper = require("moonsource_kmoe.mapper") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kmoe") + +local SOURCE_ID = "kmoe" +local BASE = "https://mox.moe" +local UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" + +---@class KmoeClient +---@field jar CookieJar|nil 登录会话;未登录为 nil +---@field ua string 这份会话登录时的 UA +local Client = {} +Client.__index = Client +Client.BASE = BASE +Client.ua = UA + +---@param cookie string|nil 已保存的登录 Cookie +---@param ua string|nil 登录时的 UA;nil 为密码登录用的默认 UA +---@return KmoeClient +function Client.new(cookie, ua) + return setmetatable({ jar = require("http.cookie_jar").session(SOURCE_ID, cookie), ua = ua }, Client) +end + +---@return boolean +function Client:loggedIn() + return self.jar ~= nil +end + +--- 需要登录却没登录(或登录已失效)时的错误。 +---@return string +function Client:loginError() + if not self.jar then return _("请先登录 Kmoe 账号") end + return require("source.auth").expire(SOURCE_ID, + _("Kmoe 登录已失效。打开「设置 → 书库 → 账号 → Kmoe」,重新登录。")) +end + +--- 站内请求。body 非 nil 时 POST 表单。成功 cb(body, nil, res)。 +---@param path string 站内路径(/ 开头) +---@param opts { form: table|nil, auth: boolean|nil, jar: CookieJar|nil } +---@param cb fun(body: string|nil, err: string|nil, res: table|nil) +---@return { cancel: fun() } +function Client:request(path, opts, cb) + local jar = opts.jar or (opts.auth and self.jar or nil) + local headers = { ["User-Agent"] = self.ua, ["Referer"] = BASE .. "/" } + local function done(body, err, res) + if body then cb(body, nil, res); return end + local code = res and res.code or 0 + local location = code >= 300 and code < 400 and Request.header(res, "Location") or "" + if location:find("regphone", 1, true) then + cb(nil, _("Kmoe 要求先验证手机号才能下载:在 Kmoe 网站「設置 → 帳號信息 → 手機驗證」完成验证,再回月读重新登录。"), res) + elseif location:find("login", 1, true) then + cb(nil, self:loginError(), res) + elseif location ~= "" then + cb(nil, _("Kmoe 返回了意外的跳转"), res) + else + cb(nil, err or _("网络请求失败"), res) + end + end + local http = { headers = headers, jar = jar, timeout = require("http.timeout").net(1) } + if opts.form then + headers["Content-Type"] = "application/x-www-form-urlencoded" + return Request.post(BASE .. path, Text.formEncode(opts.form), http, done) + end + return Request.get(BASE .. path, http, done) +end + +---@class KmoeListQuery +---@field s string 关键词,或 `CAT*<分类>` +---@field ["end"] string|nil 完結 / 連載 +---@field lang string|nil chn / jpn / eng +---@field by string|nil 排序 + +--- 书单一页(每页 21 部)。 +---@param query KmoeListQuery +---@param page integer +---@param cb fun(books: Book[]|nil, err: string|nil, more: boolean|nil) +---@return { cancel: fun() } +function Client:listAsync(query, page, cb) + local q = { + k = "", s = query.s or "", ["end"] = query["end"] or "", lang = query.lang or "", + blen = "", regn = "", by = query.by or "", color = "0", hd = "0", p = tostring(page), + } + return self:request("/data_list.php?" .. Text.formEncode(q), {}, function(body, err) + if not body then cb(nil, err); return end + cb(Mapper.list(body)) + end) +end + +--- 手机版详情页。登录时带 Cookie,页面里的 uin 用来判断登录是否还有效。 +---@param key string +---@param cb fun(detail: KmoeDetail|nil, err: string|nil) +---@return { cancel: fun() } +function Client:detailAsync(key, cb) + return self:request("/m/c/" .. key .. ".htm", { auth = true }, function(body, err) + if not body then cb(nil, err); return end + local detail = Mapper.detail(key, body) + if not detail then cb(nil, _("Kmoe 漫画详情解析失败")); return end + cb(detail) + end) +end + +--- 卷列表。匿名请求服务器回空列表,所以先看详情页是否按登录态渲染。 +---@param detail KmoeDetail +---@param cb fun(chapters: BookChapter[]|nil, err: string|nil) +---@return { cancel: fun() } +function Client:volumesAsync(detail, cb) + if not detail.logged_in then return require("source.base").defer(cb, nil, self:loginError()) end + if not detail.hash then return require("source.base").defer(cb, nil, _("Kmoe 漫画详情解析失败")) end + return self:request("/data_book.php?h=" .. detail.hash, { auth = true }, function(body, err) + if not body then cb(nil, err); return end + cb(Mapper.chapters(body, detail.bookid)) + end) +end + +--- 取一卷的文件地址。 +---@param origin string 目录里存的 getdownurl 路径 +---@param cb fun(url: string|nil, err: string|nil) +---@return { cancel: fun() } +function Client:downUrlAsync(origin, cb) + if not self.jar then return require("source.base").defer(cb, nil, self:loginError()) end + return self:request(origin, { auth = true }, function(body, err, res) + if res and res.code == 403 then + cb(nil, _("Kmoe 拒绝下载:登录时的浏览器和现在不一致。改用邮箱密码重新登录;浏览器授权要用新版扩展,粘贴 Cookie 要同时填浏览器 UA。")) + return + end + if not body then cb(nil, err); return end + local url, parse_err = Mapper.downUrl(body) + cb(url and Text.absoluteUrl(BASE .. "/", url) or nil, parse_err) + end) +end + +--- 书架快照:「訂閱收藏」页里打了收藏的书。没有封面的新书顺序补拉详情页拿封面和简介,补拉失败只少封面。 +---@param cb fun(books: Book[]|nil, err: string|nil, meta: { incomplete: boolean }|nil) +---@return { cancel: fun() } +function Client:shelfSyncAsync(cb) + local handle = {} + if not self.jar then return require("source.base").defer(cb, nil, self:loginError()) end + handle.inner = self:request("/myfollow.php", { auth = true }, function(body, err) + if handle.cancelled then return end + if not body then cb(nil, err); return end + local rows, parse_err, paged = Mapper.shelf(body) + if not rows then cb(nil, parse_err); return end + local BookDB = require("book.books_db") + local books, pos = {}, 0 + for i, row in ipairs(rows) do books[i] = row.book end + local function step() + if handle.cancelled then return end + pos = pos + 1 + local book = books[pos] + if not book then cb(books, nil, { incomplete = paged }); return end + local known = BookDB.get(SOURCE_ID, book.stable_id) + if known and known.cover then return step() end + handle.inner = self:detailAsync(book.stable_id, function(detail, detail_err) + if detail then + book.cover, book.intro, book.category = detail.book.cover, detail.book.intro, detail.book.category + else + require("utils.log").warn("kmoe shelf cover backfill failed", book.stable_id, detail_err) + end + step() + end) + end + step() + end) + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +--- 收藏 / 取消收藏。接口要数字书号,先读详情页;成功回包里有 `c101`。 +---@param key string +---@param act string "1" 收藏 / "0" 取消 +---@param cb fun(ok: boolean|nil, err: string|nil) +---@return { cancel: fun() } +function Client:followAsync(key, act, cb) + local handle = {} + handle.inner = self:detailAsync(key, function(detail, err) + if handle.cancelled then return end + if not detail then cb(nil, err); return end + if not detail.logged_in then cb(nil, self:loginError()); return end + handle.inner = self:request("/book_follow.php", { + auth = true, + form = { follow_bookid = detail.bookid, follow_type = "0", follow_act = act }, + }, function(body, follow_err) + if handle.cancelled then return end + if not body then cb(nil, follow_err); return end + if not body:find('"c101"', 1, true) then cb(nil, _("Kmoe 没有确认收藏操作")); return end + cb(true) + end) + end) + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +function Client:addToShelfAsync(key, cb) + return self:followAsync(key, "1", cb) +end + +function Client:removeFromShelfAsync(key, cb) + return self:followAsync(key, "0", cb) +end + +--- 校验一份 Cookie:带它打开「我的」页,拿个人主页链接 `/u//` 里的数字账号。 +---@param cookie string +---@param cb fun(ok: boolean, err: string|nil, account: { id: string }|nil) +---@return { cancel: fun() } +function Client.accountAsync(cookie, cb) + local client = setmetatable({ jar = require("http.cookie_jar").new():seed(cookie) }, Client) + return client:request("/my.php", { auth = true }, function(body, err, res) + local uin = body and body:match("/u/(%d+)/") + if uin then cb(true, nil, { id = uin }); return end + local code = res and res.code or 0 + if body or (code >= 300 and code < 400) then cb(false, _("Kmoe 登录无效,请重新登录")); return end + cb(false, err) + end) +end + +--- 账号密码登录,成功回登录 Cookie 串(还要经 accountAsync 校验)。密码不落盘。 +---@param email string +---@param password string +---@param cb fun(cookie: string|nil, err: string|nil) +---@return { cancel: fun() } +function Client.loginAsync(email, password, cb) + local client = setmetatable({}, Client) + return client:request("/login_act.php", { form = { email = email, passwd = password } }, function(body, err, res) + if not body then cb(nil, err); return end + local ok, wire = pcall(require("json").decode, body) + if not ok or type(wire) ~= "table" then cb(nil, _("Kmoe 登录响应无效")); return end + if wire.msgid ~= "m100" then + cb(nil, type(wire.msg) == "string" and wire.msg ~= "" and wire.msg or _("登录失败")) + return + end + local cookie = require("source.cookie_login").parse("", Request.headerAll(res, "Set-Cookie")) + if cookie == "" then cb(nil, _("Kmoe 登录成功但没有返回 Cookie")); return end + cb(cookie) + end) +end + +return Client diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/en.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/en.lua new file mode 100644 index 0000000..6600b4f --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/en.lua @@ -0,0 +1,62 @@ +return { + ["Kmoe"] = "Kmoe", + ["Kmoe 下载地址响应无效"] = "Invalid download link response from Kmoe", + ["Kmoe 书单响应无效"] = "Invalid list response from Kmoe", + ["Kmoe 书架页面无法识别"] = "Could not read the Kmoe bookshelf page", + ["Kmoe 卷列表响应无效"] = "Invalid volume list response from Kmoe", + ["Kmoe 没有确认收藏操作"] = "Kmoe did not confirm the favorite change", + ["Kmoe 没有返回下载地址"] = "Kmoe returned no download link", + ["Kmoe 没有返回这部漫画的卷列表"] = "Kmoe returned no volume list for this comic", + ["Kmoe 漫画详情解析失败"] = "Failed to parse Kmoe comic details", + ["Kmoe 漫画,按卷下载 EPUB 阅读"] = "Kmoe comics, read by downloading each volume as EPUB", + ["Kmoe 登录响应无效"] = "Invalid sign-in response from Kmoe", + ["Kmoe 登录已失效。打开「设置 → 书库 → 账号 → Kmoe」,重新登录。"] = "Your Kmoe sign-in has expired. Open Settings → Library → Account → Kmoe and sign in again.", + ["Kmoe 登录成功但没有返回 Cookie"] = "Kmoe sign-in succeeded but returned no cookie", + ["Kmoe 登录无效,请重新登录"] = "Kmoe sign-in is invalid. Please sign in again", + ["Kmoe 要求先验证手机号才能下载:在 Kmoe 网站「設置 → 帳號信息 → 手機驗證」完成验证,再回月读重新登录。"] = "Kmoe requires phone verification before downloading. Verify your phone on the Kmoe website (設置 → 帳號信息 → 手機驗證), then sign in again in Moon.", + ["Kmoe 账号"] = "Kmoe account", + ["Kmoe 返回了意外的跳转"] = "Kmoe returned an unexpected redirect", + ["Kmoe 返回的不是 EPUB 文件"] = "Kmoe did not return an EPUB file", + ["下载失败"] = "Download failed", + ["中文"] = "Chinese", + ["书架同步"] = "Shelf sync", + ["全部分类"] = "All categories", + ["全部状态"] = "Any status", + ["全部语言"] = "Any language", + ["分类"] = "Category", + ["完结"] = "Completed", + ["密码"] = "Password", + ["已登录"] = "Signed in", + ["排序"] = "Sort", + ["搜索与发现"] = "Search and discover", + ["新上架"] = "Newly added", + ["日文"] = "Japanese", + ["最近更新"] = "Recently updated", + ["未登录 · 点此登录"] = "Not signed in · Tap to sign in", + ["正在下载这一卷…"] = "Downloading this volume…", + ["正在准备漫画…"] = "Preparing comic…", + ["正在登录…"] = "Signing in…", + ["漫画目录保存失败"] = "Failed to save comic chapter list", + ["热门"] = "Popular", + ["状态"] = "Status", + ["登录"] = "Sign in", + ["登录失败"] = "Sign-in failed", + ["登录成功"] = "Signed in", + ["确定退出 Kmoe 账号?"] = "Sign out of Kmoe?", + ["综合"] = "Overall", + ["网络不可用,请先连接 Wi-Fi"] = "Network unavailable. Connect to Wi-Fi first", + ["网络请求失败"] = "Network request failed", + ["英文"] = "English", + ["评分"] = "Rating", + ["语言"] = "Language", + ["请先登录 Kmoe 账号"] = "Sign in to Kmoe first", + ["请输入邮箱和密码"] = "Enter email and password", + ["这一卷的 EPUB 还在制作中,过一阵再试"] = "The EPUB for this volume is still being made. Try again later", + ["这部漫画还没有可下载的卷"] = "This comic has no downloadable volumes yet", + ["连载"] = "Ongoing", + ["邮箱"] = "Email", + ["Kmoe 登录 Cookie"] = "Kmoe sign-in cookie", + ["同一浏览器的 User-Agent(选填,不填不能下载)"] = "User-Agent of the same browser (optional; required for downloads)", + ["Kmoe 拒绝下载:登录时的浏览器和现在不一致。改用邮箱密码重新登录;浏览器授权要用新版扩展,粘贴 Cookie 要同时填浏览器 UA。"] = "Kmoe refused the download: this session was signed in from a different browser. Sign in again with email and password; browser sign-in needs the latest extension, and a pasted cookie needs the browser User-Agent too.", + ["在 mox.moe 登录后,复制请求标头里的完整 Cookie"] = "Sign in on mox.moe, then copy the full Cookie request header", +} diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/zh_TW.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/zh_TW.lua new file mode 100644 index 0000000..ddf0c03 --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/l10n/zh_TW.lua @@ -0,0 +1,62 @@ +return { + ["Kmoe"] = "Kmoe", + ["Kmoe 下载地址响应无效"] = "Kmoe 下載地址回應無效", + ["Kmoe 书单响应无效"] = "Kmoe 書單回應無效", + ["Kmoe 书架页面无法识别"] = "無法識別 Kmoe 書架頁面", + ["Kmoe 卷列表响应无效"] = "Kmoe 卷列表回應無效", + ["Kmoe 没有确认收藏操作"] = "Kmoe 沒有確認收藏操作", + ["Kmoe 没有返回下载地址"] = "Kmoe 沒有返回下載地址", + ["Kmoe 没有返回这部漫画的卷列表"] = "Kmoe 沒有返回這部漫畫的卷列表", + ["Kmoe 漫画详情解析失败"] = "Kmoe 漫畫詳情解析失敗", + ["Kmoe 漫画,按卷下载 EPUB 阅读"] = "Kmoe 漫畫,按卷下載 EPUB 閱讀", + ["Kmoe 登录响应无效"] = "Kmoe 登入回應無效", + ["Kmoe 登录已失效。打开「设置 → 书库 → 账号 → Kmoe」,重新登录。"] = "Kmoe 登入已失效。打開「設定 → 書庫 → 帳號 → Kmoe」,重新登入。", + ["Kmoe 登录成功但没有返回 Cookie"] = "Kmoe 登入成功但沒有返回 Cookie", + ["Kmoe 登录无效,请重新登录"] = "Kmoe 登入無效,請重新登入", + ["Kmoe 要求先验证手机号才能下载:在 Kmoe 网站「設置 → 帳號信息 → 手機驗證」完成验证,再回月读重新登录。"] = "Kmoe 要求先驗證手機號碼才能下載:在 Kmoe 網站「設置 → 帳號信息 → 手機驗證」完成驗證,再回月讀重新登入。", + ["Kmoe 账号"] = "Kmoe 帳號", + ["Kmoe 返回了意外的跳转"] = "Kmoe 返回了意外的跳轉", + ["Kmoe 返回的不是 EPUB 文件"] = "Kmoe 返回的不是 EPUB 檔案", + ["下载失败"] = "下載失敗", + ["中文"] = "中文", + ["书架同步"] = "書架同步", + ["全部分类"] = "全部分類", + ["全部状态"] = "全部狀態", + ["全部语言"] = "全部語言", + ["分类"] = "分類", + ["完结"] = "完結", + ["密码"] = "密碼", + ["已登录"] = "已登入", + ["排序"] = "排序", + ["搜索与发现"] = "搜尋與發現", + ["新上架"] = "新上架", + ["日文"] = "日文", + ["最近更新"] = "最近更新", + ["未登录 · 点此登录"] = "未登入 · 點此登入", + ["正在下载这一卷…"] = "正在下載這一卷…", + ["正在准备漫画…"] = "正在準備漫畫…", + ["正在登录…"] = "正在登入…", + ["漫画目录保存失败"] = "漫畫目錄儲存失敗", + ["热门"] = "熱門", + ["状态"] = "狀態", + ["登录"] = "登入", + ["登录失败"] = "登入失敗", + ["登录成功"] = "登入成功", + ["确定退出 Kmoe 账号?"] = "確定登出 Kmoe 帳號?", + ["综合"] = "綜合", + ["网络不可用,请先连接 Wi-Fi"] = "網路不可用,請先連接 Wi-Fi", + ["网络请求失败"] = "網路請求失敗", + ["英文"] = "英文", + ["评分"] = "評分", + ["语言"] = "語言", + ["请先登录 Kmoe 账号"] = "請先登入 Kmoe 帳號", + ["请输入邮箱和密码"] = "請輸入信箱和密碼", + ["这一卷的 EPUB 还在制作中,过一阵再试"] = "這一卷的 EPUB 還在製作中,過一陣再試", + ["这部漫画还没有可下载的卷"] = "這部漫畫還沒有可下載的卷", + ["连载"] = "連載", + ["邮箱"] = "信箱", + ["Kmoe 登录 Cookie"] = "Kmoe 登入 Cookie", + ["同一浏览器的 User-Agent(选填,不填不能下载)"] = "同一瀏覽器的 User-Agent(選填,不填無法下載)", + ["Kmoe 拒绝下载:登录时的浏览器和现在不一致。改用邮箱密码重新登录;浏览器授权要用新版扩展,粘贴 Cookie 要同时填浏览器 UA。"] = "Kmoe 拒絕下載:登入時的瀏覽器和現在不一致。改用信箱密碼重新登入;瀏覽器授權需要新版擴充功能,貼上 Cookie 需要同時填瀏覽器 UA。", + ["在 mox.moe 登录后,复制请求标头里的完整 Cookie"] = "在 mox.moe 登入後,複製請求標頭裡的完整 Cookie", +} diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/loadmeta.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/loadmeta.lua new file mode 100644 index 0000000..0d09143 --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_kmoe._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/mapper.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/mapper.lua new file mode 100644 index 0000000..2565343 --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/mapper.lua @@ -0,0 +1,179 @@ +--[[-- +Kmoe 回包解析:书单 JSON、详情页 HTML、卷列表 JSON、书架页 HTML。纯函数,不发请求。 + +@module moonsource_kmoe.mapper +--]] + +local JSON = require("json") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kmoe") + +local SOURCE_ID = "kmoe" +local Mapper = {} + +---@param s string|nil +---@return string +local function plain(s) + return Text.stripHtml(s or "") +end + +---@param body string|nil +---@return table|nil +local function decode(body) + if type(body) ~= "string" or body == "" then return nil end + local ok, wire = pcall(JSON.decode, body) + return ok and type(wire) == "table" and wire or nil +end + +--- 书页链接里的书 key(`/c/.htm`),即本源的 stable_id。 +---@param url string|nil +---@return string|nil +function Mapper.key(url) + return type(url) == "string" and url:match("/c/(%w+)%.htm") or nil +end + +--- `data_list.php` 回包 → 书列表。搜索结果的书名带 `` 高亮,一并剥掉。 +---@param body string|nil +---@return Book[]|nil books +---@return string|nil err +---@return boolean|nil more 还有下一页 +function Mapper.list(body) + local wire = decode(body) + if not wire or type(wire.data) ~= "table" then return nil, _("Kmoe 书单响应无效") end + local books = {} + for _idx, row in ipairs(wire.data) do + local key = type(row) == "table" and Mapper.key(row.url_book) + if key then + books[#books + 1] = { + source_id = SOURCE_ID, + stable_id = key, + title = plain((tostring(row.name or ""):gsub("", ""))), + authors = plain(row.author), + cover = row.url_cover, + } + end + end + return books, nil, (tonumber(wire.nowpage) or 0) < (tonumber(wire.totalpage) or 0) +end + +--- 详情页里一段 `…` 中可见的文字;隐藏的占位不算。第二个起的作者前面垫了全角空格。 +---@param block string|nil +---@return string[] +local function visible(block) + local out = {} + for display, inner in (block or ""):gmatch('(.-)') do + local text = Text.trim((plain(inner):gsub("\227\128\128", " "))) + if display == "" and text ~= "" then out[#out + 1] = text end + end + return out +end + +---@class KmoeDetail +---@field book Book +---@field bookid string 数字书号;收藏、下载接口用它 +---@field hash string|nil 卷列表 `data_book.php?h=` 的参数 +---@field logged_in boolean 页面按登录态渲染(`var uin` 非空) + +--- 手机版详情页 `/m/c/.htm` → 书信息。认不出书号或书名返回 nil。 +---@param key string +---@param html string|nil +---@return KmoeDetail|nil +function Mapper.detail(key, html) + html = html or "" + local bookid = html:match('var%s+bookid%s*=%s*"(%d+)"') + local title = html:match("]*>(.-)") + if not bookid or not title then return nil end + local intro = html:match('getElementById%("div_desc_content"%)%.innerHTML%s*=%s*"(.-)";') + return { + book = { + source_id = SOURCE_ID, + stable_id = key, + title = plain(title), + authors = table.concat(visible(html:match("作者:(.-)(.-)') do + local key, title, author = tr:match("href='[^']*/c/(%w+)%.htm'[^>]*>(.-)%s*]*>(.-)") + local bookid = tr:match("sel_pushtype_(%d+)") + local fav = tr:match('icon%-tick%-fav%.png"[^>]-display:(%a*)"') + if key and bookid and fav == "" then + rows[#rows + 1] = { + book = { source_id = SOURCE_ID, stable_id = key, title = plain(title), authors = plain(author) }, + bookid = bookid, + } + end + end + return rows, nil, html:find("myfollow%.php%?[^\"']*p=%d") ~= nil +end + +return Mapper diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/setting.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/setting.lua new file mode 100644 index 0000000..d5c30cc --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/setting.lua @@ -0,0 +1,161 @@ +--[[-- +Kmoe 账号:邮箱密码登录、浏览器授权、粘贴 Cookie 三种方式,最后都只保存校验通过的 Cookie、数字账号和登录时的 UA,不存密码。 + +下载接口要求 UA 与登录时一致,所以每种方式都带上自己的 UA:密码登录用插件默认 UA(存 nil), +浏览器授权用扩展回传的 `payload.ua`,粘贴 Cookie 用用户一并填的浏览器 UA。 + +@module moonsource_kmoe.setting +--]] + +local CookieLogin = require("source.cookie_login") +local _ = require("l10n").get("moonsource_kmoe") + +local SOURCE_ID = "kmoe" +local Setting = {} + +local function loggedIn() + local cfg = require("utils.settings").getSource(SOURCE_ID) + return type(cfg.cookie) == "string" and cfg.cookie ~= "" +end + +---@type CookieLoginSpec +local SPEC = { + id = SOURCE_ID, + title = _("Kmoe 账号"), + cookie_title = _("Kmoe 登录 Cookie"), + cookie_hint = _("在 mox.moe 登录后,复制请求标头里的完整 Cookie"), + logout_text = _("确定退出 Kmoe 账号?"), + loggedIn = loggedIn, + checkAsync = function(cookie, cb) + return require("moonsource_kmoe.client").accountAsync(cookie, cb) + end, + ---@param account { id: string } checkAsync 成功时必带 + commit = function(cookie, account, cb, current) + return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, cb, current) + end, + clear = function(cfg) cfg.cookie, cfg.account_id, cfg.ua = nil, nil, nil end, +} + +--- 带登录 UA 的 SPEC:UA 先写进配置再提交 Cookie(提交里会重载源),提交失败就还原。 +---@param ua string|nil nil 为插件默认 UA +---@return CookieLoginSpec +local function withUA(ua) + return setmetatable({ + commit = function(cookie, account, cb, current) + local Settings = require("utils.settings") + local cfg = Settings.getSource(SOURCE_ID) + local previous = cfg.ua + cfg.ua = ua + return CookieLogin.commitAccount(SOURCE_ID, cookie, account.id, function(ok, err) + if not ok then + cfg.ua = previous + Settings.saveSource(SOURCE_ID, cfg) + end + cb(ok, err) + end, current) + end, + }, { __index = SPEC }) +end + +---@param s any +---@return string|nil +local function nonEmpty(s) + s = type(s) == "string" and s:match("^%s*(.-)%s*$") or "" + return s ~= "" and s or nil +end + +---@param email string +---@param password string +local function doLogin(email, password) + local Toast = require("ui.themes.widgets.toast") + if email == "" or password == "" then + Toast:new{ text = _("请输入邮箱和密码"), timeout = 3 }:show() + return + end + require("ui/network/manager"):runWhenConnected(function() + local job + local waiting = require("ui.themes.widgets.progress_dialog"):new{ + title = SPEC.title, text = _("正在登录…"), dismissable = false, + on_cancel = function() if job then job.cancel() end end, + } + waiting:show() + local function done(ok, err) + waiting:close() + Toast:new{ text = ok and _("登录成功") or err or _("登录失败"), timeout = ok and 2 or 3 }:show() + end + job = require("moonsource_kmoe.client").loginAsync(email, password, function(cookie, err) + if not cookie then done(false, err); return end + job = CookieLogin.save(withUA(nil), cookie, done) + end) + end) +end + +local function showLogin() + require("ui.themes.widgets.input"):new{ + title = SPEC.title, + fields = { + { text = "", hint = _("邮箱") }, + { text = "", hint = _("密码"), text_type = "password" }, + }, + ok_text = _("登录"), + callback = function(email, password) doLogin(email or "", password or "") end, + }:show() +end + +local function showPaste() + require("ui.themes.widgets.input"):new{ + title = SPEC.cookie_title, + fields = { + { text = "", hint = SPEC.cookie_hint }, + { text = "", hint = _("同一浏览器的 User-Agent(选填,不填不能下载)") }, + }, + ok_text = _("登录"), + callback = function(value, ua) + local cookie = CookieLogin.parse(value or "") + if cookie == "" then + require("ui.themes.widgets.toast"):new{ text = _("没有读到 Cookie"), timeout = 3 }:show() + return + end + CookieLogin.verify(withUA(nonEmpty(ua)), cookie) + end, + }:show() +end + +function Setting.rowIcon() + return "photo_library" +end + +function Setting.rowStatus() + local on = CookieLogin.authorized(SPEC) + return on and _("已登录") or _("未登录 · 点此登录"), on +end + +Setting.browser = { + domain = "mox.moe", + scope = "cookie", + login = "https://mox.moe/login.php", + check = "https://mox.moe/my.php", + icon = "https://mox.moe/favicon.ico", + isAuthorized = function() return CookieLogin.authorized(SPEC) end, + apply = function(payload, cb) + return CookieLogin.save(withUA(nonEmpty(payload.ua)), CookieLogin.fromPayload(payload, "mox.moe"), cb) + end, +} + +function Setting.rows() + local rows = { + CookieLogin.accountRow(SPEC, { callback = showLogin }), + CookieLogin.browserRow(), + function(iw) + return require("ui.themes.widgets.row").widget({ width = iw, chevron = true, kind = "nav", + icon = "content_paste", title = _("粘贴 Cookie"), callback = showPaste }) + end, + } + if loggedIn() then rows[#rows + 1] = CookieLogin.logoutRow(SPEC) end + return rows +end + +--- 登录失效提示的「重新登录」直达入口(desktop.sync.promptLogin)。 +Setting.login = showLogin + +return Setting diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/source.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/source.lua new file mode 100644 index 0000000..cd66dbb --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/source.lua @@ -0,0 +1,293 @@ +--[[-- +Kmoe 数据源门面。 + +书城与搜索匿名可用;卷列表、下载、书架要登录。一卷是一章,下载整卷 EPUB 阅读。 +书架是网站的「收藏」,经 Shelf 双向同步。网站没有阅读进度接口,进度只在本机。 + +@module moonsource_kmoe.source +--]] + +local Browse = require("source.browse") +local Client = require("moonsource_kmoe.client") +local SourceBase = require("source.base") +local Shelf = require("source.shelf") +local Toc = require("source.toc") +local _ = require("l10n").get("moonsource_kmoe") + +local Kmoe = {} + +---@return BookSourceMeta +function Kmoe.meta() + return require("moonsource_kmoe.loadmeta")() +end + +---@class KmoeSource : SourceBase +---@field _client KmoeClient +local Source = setmetatable({ shelf_add = true }, { __index = SourceBase }) +Source.__index = Source + +---@return KmoeSource +function Kmoe.new() + local cfg = require("utils.settings").getSource("kmoe") + local meta = Kmoe.meta() + return setmetatable({ + id = meta.id, + name = meta.name, + type = meta.type, + _client = Client.new(cfg.cookie, cfg.ua), + }, Source) +end + +--- 已登录才算配置好:书架、卷列表都要登录;书城浏览匿名可用,不看这里。 +---@return boolean +function Source:configured() + return self._client:loggedIn() +end + +---@param opts { dirty_only?: boolean, force?: boolean, on_progress?: fun(text: string|nil, done: integer|nil, total: integer|nil) }|nil +---@param cb fun(result: SyncResult|nil, err: any) +---@return { cancel: fun() } +function Source:syncBooksAsync(opts, cb) + if not self._client:loggedIn() then return SourceBase.syncBooksAsync(self, opts, cb) end + return Shelf.syncAsync(self.id, self._client, nil, opts, cb) +end + +---@param keyword string +---@param cb fun(res: { data: Book[] }|nil, err: string|nil) +---@return { cancel: fun() } +function Source:searchAsync(keyword, cb) + return Browse.pages(function(page, done) + return self._client:listAsync({ s = keyword }, page, done) + end, 63, {}, cb) +end + +-- 网站「分類」原文(繁体),既是查询参数也是显示名。 +local CATEGORIES = { + "幽默", "愛情", "競技", "熱血", "冒險", "格鬥", "恐怖", "生存", "懸疑", "偵探", "生活", "勵志", + "校園", "職場", "美食", "音樂", "治癒", "歷史", "戰爭", "機戰", "科幻", "魔幻", "魔法", "神鬼", + "武俠", "萌系", "耽美", "偽娘", "百合", "後宮", "少女", "少年", "青年", "輕改", "四格", +} +local SORTS = { + { "sortpoint", _("综合") }, { "score", _("评分") }, { "count_push", _("热门") }, + { "newadd", _("新上架") }, { "lastupdate", _("最近更新") }, +} +local STATUSES = { { "", _("全部状态") }, { "連載", _("连载") }, { "完結", _("完结") } } +local LANGS = { { "", _("全部语言") }, { "chn", _("中文") }, { "jpn", _("日文") }, { "eng", _("英文") } } + +---@param rows string[][] +---@param value string|nil +---@return string +local function pick(rows, value) + for _idx, row in ipairs(rows) do + if row[1] == value then return row[1] end + end + return rows[1][1] +end + +--- 书城浏览:节点 `排序,状态,语言,分类`,四段都可空,缺省按综合排序看全部。每页 21 部。 +---@param opts { node?: string, limit?: integer } +---@param cb fun(res: { data: Book[], groups: StoreChipGroup[] }|nil, err: string|nil) +---@return { cancel: fun() } +function Source:browseAsync(opts, cb) + opts = opts or {} + local by, status, lang, cat = (opts.node or ""):match("^([^,]*),([^,]*),([^,]*),(.*)$") + local f = { pick(SORTS, by), pick(STATUSES, status), pick(LANGS, lang), "" } + for _idx, name in ipairs(CATEGORIES) do + if name == cat then f[4] = cat end + end + local node = table.concat(f, ",") + --- 只改第 slot 段的节点。 + local function with(slot, value) + local copy = { f[1], f[2], f[3], f[4] } + copy[slot] = value + return table.concat(copy, ",") + end + local function group(slot, rows, title) + local chips = {} + for i, row in ipairs(rows) do chips[i] = { id = with(slot, row[1]), title = row[2] } end + local g = Browse.group(chips, node) + g.title = title + return g + end + local cats = { { "", _("全部分类") } } + for i, name in ipairs(CATEGORIES) do cats[i + 1] = { name, name } end + local groups = { + group(1, SORTS, _("排序")), group(2, STATUSES, _("状态")), + group(3, LANGS, _("语言")), group(4, cats, _("分类")), + } + local query = { s = f[4] ~= "" and "CAT*" .. f[4] or "", by = f[1], ["end"] = f[2], lang = f[3] } + return Browse.pages(function(page, done) + return self._client:listAsync(query, page, done) + end, opts.limit or 63, groups, cb) +end + +--- 详情不要求登录;登录着且还没有目录缓存时顺手把卷列表存下。 +---@param identity BookIdentity +---@param cb fun(book: Book|nil, err: string|nil) +---@return { cancel: fun() } +function Source:getDetailAsync(identity, cb) + local handle = {} + handle.inner = self._client:detailAsync(identity.stable_id, function(detail, err) + if handle.cancelled then return end + if not detail then cb(nil, err); return end + local book = detail.book + local existing = require("book.books_db").get(self.id, identity.stable_id) + if existing then book.deleted = existing.deleted end + local function finish() + require("book.store").rememberMany({ book }) + cb(book) + end + if not detail.logged_in or Toc.read(self.id, identity.stable_id) then return finish() end + handle.inner = self._client:volumesAsync(detail, function(chapters) + if handle.cancelled then return end + if chapters then Toc.put(self.id, identity.stable_id, chapters) end + finish() + end) + end) + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +--- 绕过缓存拉卷列表并写回。 +---@param identity BookIdentity +---@param cb fun(toc: KmoeChapter[]|nil, err: string|nil) +---@return { cancel: fun() } +function Source:refreshTocAsync(identity, cb) + local handle = {} + handle.inner = self._client:detailAsync(identity.stable_id, function(detail, err) + if handle.cancelled then return end + if not detail then cb(nil, err); return end + handle.inner = self._client:volumesAsync(detail, function(chapters, vol_err) + if handle.cancelled then return end + if not chapters then cb(nil, vol_err); return end + if not Toc.put(identity.source_id, identity.stable_id, chapters) then + cb(nil, _("漫画目录保存失败")) + return + end + cb(chapters) + end) + end) + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +---@param identity BookIdentity +---@param cb fun(toc: KmoeChapter[]|nil, err: string|nil) +---@param force boolean|nil +---@return { cancel: fun() } +function Source:loadTocAsync(identity, cb, force) + local cached = not force and Toc.read(identity.source_id, identity.stable_id) + if cached and #cached > 0 then return SourceBase.defer(cb, cached) end + return self:refreshTocAsync(identity, cb) +end + +--- 起始卷:显式章号 > 本地进度章号 > 本地进度全书比例 > 第一卷。 +---@param identity BookIdentity +---@param opts table +---@param toc KmoeChapter[] +---@return integer +local function startIndex(identity, opts, toc) + local idx = opts.chapter_idx + if not idx then + local pending = require("book.progress_db").get(identity.source_id, identity.stable_id) + idx = pending and (pending.chapter_idx or math.floor(pending.fraction * #toc) + 1) + end + return math.max(1, math.min(#toc, idx or 1)) +end + +---@param identity BookIdentity +---@param opts table|nil +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Source:openBookAsync(identity, opts, cb) + opts = opts or {} + local Chapter = require("moonsource_kmoe.chapter") + local function finish(path, idx) + local ok, err = require("book.store").touch(path, identity, { chapter_idx = idx, book = identity.book }) + cb(ok and path or nil, err) + end + + -- 已下载的卷直接交给阅读器,不经过联网门控。 + local toc = Toc.read(identity.source_id, identity.stable_id) + if toc then + local idx = startIndex(identity, opts, toc) + local path = Chapter.existing(identity, toc[idx]) + if path then return SourceBase.defer(finish, path, idx) end + end + if not require("ui/network/manager"):isConnected() then + return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) + end + + local cancelled, active, dialog = false, nil, nil + local function closeDialog() + if dialog then dialog:close(); dialog = nil end + end + require("ui/uimanager"):nextTick(function() + if cancelled then return end + dialog = require("ui.themes.widgets.progress_dialog"):new{ + title = identity.book and identity.book.title or identity.stable_id, + dismissable = false, + } + dialog:show() + dialog:set(_("正在准备漫画…")) + active = self:loadTocAsync(identity, function(fresh, err) + active = nil + if cancelled then return end + if not fresh then closeDialog(); cb(nil, err); return end + local idx = startIndex(identity, opts, fresh) + local mb = 1024 * 1024 + active = Chapter.materializeAsync(self._client, identity, fresh[idx], + function(bytes, total) + if dialog and total and total > 0 then + dialog:update(_("正在下载这一卷…"), math.floor(bytes / mb), math.ceil(total / mb)) + end + end, + function(path, materialize_err) + active = nil + closeDialog() + if cancelled then return end + if not path then cb(nil, materialize_err); return end + finish(path, idx) + end + ) + end) + end) + + return { cancel = function() + cancelled = true + if active then active.cancel() end + closeDialog() + end } +end + +--- 缓存卷(全本或 range 指定的一段);已下载的卷跳过。 +---@param identity BookIdentity +---@param on_progress fun(done: integer, total: integer)|nil +---@param cb fun(ok: boolean, cached: integer, err: string|nil, total: integer, failed: integer) +---@param range ChapterCacheRange|nil +---@return { cancel: fun() } +function Source:cacheAllChaptersAsync(identity, on_progress, cb, range) + local handle = {} + handle.inner = self:loadTocAsync(identity, function(toc, err) + if handle.cancelled then return end + if not toc then cb(false, 0, err, 0, 0); return end + local from_idx, count = require("source.chapter").cacheRange(toc, range) + handle.inner = require("moonsource_kmoe.chapter").cacheAsync(self._client, identity, toc, from_idx, count, + on_progress, function(cached, total, failed, last_err) + if not handle.cancelled then cb(failed == 0, cached, last_err, total, failed) end + end) + end) + function handle.cancel() + handle.cancelled = true + if handle.inner then handle.inner.cancel() end + end + return handle +end + +return Kmoe diff --git a/moonsource-kmoe.koplugin/moonsource_kmoe/version.lua b/moonsource-kmoe.koplugin/moonsource_kmoe/version.lua new file mode 100644 index 0000000..25b37f6 --- /dev/null +++ b/moonsource-kmoe.koplugin/moonsource_kmoe/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/kmoe/client_spec.lua b/tests/kmoe/client_spec.lua new file mode 100644 index 0000000..5640b63 --- /dev/null +++ b/tests/kmoe/client_spec.lua @@ -0,0 +1,173 @@ +--[[-- +moonsource_kmoe.client 离线用例:跳转归类、公开接口不带账号 Cookie、登录取 Cookie、账号校验、收藏确认。 + +@module tests.moonsource_kmoe.client_spec +--]] +---@diagnostic disable: need-check-nil, undefined-field, inject-field + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() +package.loaded["json"] = { decode = require("support.json_stub").decode } + +local calls, script, expired = {}, {}, {} + +local function header(res, name) + local v = res and res.headers and res.headers[name] + return type(v) == "table" and v[1] or v +end + +package.preload["http.request"] = function() + local function send(method, url, body, opts, cb) + local jar = opts and opts.jar + calls[#calls + 1] = { method = method, url = url, body = body, cookie = jar and jar:header(url) or nil, + ua = opts and opts.headers and opts.headers["User-Agent"] } + local step = table.remove(script, 1) or { code = 200, body = "" } + if step.code ~= 200 then + cb(nil, "HTTP " .. step.code, { code = step.code, headers = step.headers or {} }) + else + cb(step.body, nil, { code = 200, headers = step.headers or {} }) + end + return { cancel = function() end } + end + return { + get = function(url, opts, cb) return send("GET", url, nil, opts, cb) end, + post = function(url, body, opts, cb) return send("POST", url, body, opts, cb) end, + header = header, + headerAll = function(res, name) + local v = res and res.headers and res.headers[name] + return type(v) == "table" and v or { v } + end, + } +end +package.preload["source.auth"] = function() + return { expire = function(id, msg) expired[#expired + 1] = id; return msg end } +end + +local Client = require("moonsource_kmoe.client") + +local function reset(steps) + calls, script, expired = {}, steps, {} +end + +-- 书单是公开接口:登录着也不带账号 Cookie;分类、排序、页码进查询串。 +do + reset({ { code = 200, body = [[{"totalpage":1,"nowpage":1,"data":[]}]] } }) + local books, more + Client.new("VOLSKEY=k"):listAsync({ s = "CAT*幽默", by = "score", ["end"] = "連載", lang = "chn" }, 2, + function(b, _e, m) books, more = b, m end) + Assert.len(books, 0) + Assert.is_false(more) + Assert.is_nil(calls[1].cookie) + local url = calls[1].url + Assert.matches(url, "^https://mox%.moe/data_list%.php%?") + Assert.is_true(url:find("s=CAT%2A%E5%B9%BD%E9%BB%98", 1, true) ~= nil, url) + Assert.is_true(url:find("by=score", 1, true) ~= nil) + Assert.is_true(url:find("lang=chn", 1, true) ~= nil) + Assert.is_true(url:find("&p=2", 1, true) ~= nil) +end + +-- 详情带登录 Cookie;没做手机验证 → 手机验证说明;登录失效 → 标记失效;未登录 → 请先登录。 +do + reset({ { code = 302, headers = { Location = "https://mox.moe/m/regphone.php" } } }) + local url, err + Client.new("VOLSKEY=k"):downUrlAsync("/getdownurl.php?b=1&v=2&mobi=2&vip=0&json=1", function(u, e) url, err = u, e end) + Assert.is_nil(url) + Assert.matches(err, "手機驗證") + Assert.eq(calls[1].cookie, "VOLSKEY=k") + + reset({ { code = 302, headers = { Location = "https://mox.moe/login.php" } } }) + Client.new("VOLSKEY=k"):detailAsync("abc", function(_d, e) err = e end) + Assert.matches(err, "重新登录") + Assert.eq(expired[1], "kmoe") + Assert.eq(calls[1].url, "https://mox.moe/m/c/abc.htm") + + reset({}) + Client.new(nil):downUrlAsync("/getdownurl.php", function(_u, e) err = e end) + Stubs.flush() + Assert.matches(err, "请先登录") + Assert.len(calls, 0, "没登录不发下载请求") + Assert.len(expired, 0) + + reset({ { code = 200, body = [[{"url":"/dl/x.epub","name":"x.epub"}]] } }) + Client.new("VOLSKEY=k"):downUrlAsync("/getdownurl.php", function(u) url = u end) + Assert.eq(url, "https://mox.moe/dl/x.epub") +end + +-- 会话 UA:带了就逐字沿用,没带用默认电脑 UA;取下载地址 403 = UA 和登录时不一致。 +do + reset({ { code = 200, body = "" }, { code = 200, body = "" } }) + Client.new("VOLSKEY=k", "Browser/157"):detailAsync("abc", function() end) + Client.new("VOLSKEY=k"):detailAsync("abc", function() end) + Assert.eq(calls[1].ua, "Browser/157") + Assert.eq(calls[2].ua, Client.ua) + Assert.matches(Client.ua, "Macintosh") + + reset({ { code = 403 } }) + local url, err + Client.new("VOLSKEY=k"):downUrlAsync("/getdownurl.php", function(u, e) url, err = u, e end) + Assert.is_nil(url) + Assert.matches(err, "浏览器和现在不一致") +end + +-- 卷列表:详情页不是登录态就不请求 data_book(匿名只会拿到空列表)。 +do + reset({}) + local err + Client.new("VOLSKEY=k"):volumesAsync({ logged_in = false, hash = "h", bookid = "1" }, function(_c, e) err = e end) + Stubs.flush() + Assert.len(calls, 0) + Assert.matches(err, "重新登录") +end + +-- 密码登录:表单字段 email / passwd;m100 + Set-Cookie 才成功;失败带出站点原话。 +do + reset({ { code = 200, body = [[{"ret":0,"msg":"","msgid":"m100"}]], + headers = { ["Set-Cookie"] = { "VOLSKEY=abc; path=/; domain=.mox.moe", "VLIBSID=s1; path=/" } } } }) + local cookie, err + Client.loginAsync("a@b.c", "p&w", function(c, e) cookie, err = c, e end) + Assert.is_nil(err) + Assert.is_true(cookie:find("VOLSKEY=abc", 1, true) ~= nil) + Assert.is_true(cookie:find("VLIBSID=s1", 1, true) ~= nil) + Assert.eq(calls[1].method, "POST") + Assert.eq(calls[1].url, "https://mox.moe/login_act.php") + Assert.eq(calls[1].body, "email=a%40b.c&passwd=p%26w") + Assert.is_nil(calls[1].cookie) + + reset({ { code = 200, body = [[{"ret":1,"msg":"郵箱帳號或密碼錯誤。","msgid":"e400"}]] } }) + Client.loginAsync("a@b.c", "x", function(c, e) cookie, err = c, e end) + Assert.is_nil(cookie) + Assert.eq(err, "郵箱帳號或密碼錯誤。") +end + +-- 账号校验:「我的」页里的 /u// 是账号;跳登录页是 Cookie 无效。 +do + reset({ { code = 200, body = '主頁' } }) + local ok, err, account + Client.accountAsync("VOLSKEY=k", function(o, e, a) ok, err, account = o, e, a end) + Assert.is_true(ok) + Assert.eq(account.id, "123456") + Assert.eq(calls[1].cookie, "VOLSKEY=k") + + reset({ { code = 302, headers = { Location = "https://mox.moe/login.php" } } }) + Client.accountAsync("VOLSKEY=bad", function(o, e) ok, err = o, e end) + Assert.is_false(ok) + Assert.matches(err, "登录") +end + +-- 收藏:先读详情拿数字书号,回包里有 c101 才算成功。 +do + local detail = [[有鬼]] + reset({ { code = 200, body = detail }, { code = 200, body = '' } }) + local ok, err + Client.new("VOLSKEY=k"):addToShelfAsync("de34d9", function(o, e) ok, err = o, e end) + Assert.is_true(ok) + Assert.eq(calls[2].url, "https://mox.moe/book_follow.php") + Assert.eq(calls[2].body, "follow_act=1&follow_bookid=34410&follow_type=0") + + reset({ { code = 200, body = detail }, { code = 200, body = '' } }) + Client.new("VOLSKEY=k"):removeFromShelfAsync("de34d9", function(o, e) ok, err = o, e end) + Assert.is_nil(ok) + Assert.not_nil(err) + Assert.is_true(calls[2].body:find("follow_act=0", 1, true) ~= nil) +end diff --git a/tests/kmoe/mapper_spec.lua b/tests/kmoe/mapper_spec.lua new file mode 100644 index 0000000..908fd7a --- /dev/null +++ b/tests/kmoe/mapper_spec.lua @@ -0,0 +1,133 @@ +--[[-- +moonsource_kmoe.mapper 离线用例:书单 JSON、详情页 HTML、卷列表、下载地址、书架页。样本结构取自 mox.moe 实际回包。 + +@module tests.moonsource_kmoe.mapper_spec +--]] +---@diagnostic disable: need-check-nil, undefined-field + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() +package.loaded["json"] = { decode = require("support.json_stub").decode } + +local Mapper = require("moonsource_kmoe.mapper") + +-- 书单:搜索结果名字带 高亮;nowpage < totalpage 才还有下一页。 +do + local body = [[{"uin":"","total":2,"totalpage":2,"nowcount":1,"nowpage":1,"data":[ + {"status":"\u5b8c\u7d50","url_book":"https:\/\/mox.moe\/c\/f1bc90.htm","url_cover":"https:\/\/kmimg.moex.ink\/cover\/x.jpg?sign=a", + "newvol":"\u5377 31","name":"\u881f\u7b46<\/b>\u5c0f\u65b0","author":"\u81fc\u4e95\u5100\u4eba","score":"9.1"}, + {"url_book":"https:\/\/mox.moe\/about.htm","name":"x"}]}]] + local books, err, more = Mapper.list(body) + Assert.is_nil(err) + Assert.len(books, 1, "认不出书 key 的行丢掉") + Assert.eq(books[1].stable_id, "f1bc90") + Assert.eq(books[1].source_id, "kmoe") + Assert.eq(books[1].title, "蠟筆小新") + Assert.eq(books[1].authors, "臼井儀人") + Assert.eq(books[1].cover, "https://kmimg.moex.ink/cover/x.jpg?sign=a") + Assert.is_true(more) + + local _b, _e, last = Mapper.list([[{"totalpage":3,"nowpage":3,"data":[]}]]) + Assert.is_false(last) + local none, bad = Mapper.list("") + Assert.is_nil(none) + Assert.not_nil(bad, "非 JSON 是响应无效,不是空结果") +end + +local DETAIL = [[ +蠟筆小新
+蠟筆小新
+ + 作者:臼井儀人 +  UY Team +   +  ... +
+ 狀態:完結 +
+ 分類:幽默 +   治癒 +
+]] + +-- 详情:只取可见作者 / 分类;简介去标签解实体;uin 非空才算登录态页面。 +do + local d = Mapper.detail("f1bc90", DETAIL:gsub("@UIN@", "")) + Assert.eq(d.bookid, "35063") + Assert.eq(d.hash, "17957395811f1bc9") + Assert.is_false(d.logged_in) + Assert.eq(d.book.stable_id, "f1bc90") + Assert.eq(d.book.title, "蠟筆小新") + Assert.eq(d.book.authors, "臼井儀人, UY Team") + Assert.eq(d.book.category, "幽默 治癒") + Assert.eq(d.book.cover, "https://kmimg.moex.ink/cover/l.jpg!cover_l?sign=b") + Assert.eq(d.book.intro, "五歲的小孩,\n引發 \"笑料\" Crayon") + Assert.is_true(Mapper.detail("f1bc90", (DETAIL:gsub("@UIN@", "123"))).logged_in) + Assert.is_nil(Mapper.detail("f1bc90", "維護中"), "认不出书号就是解析失败") +end + +-- 卷列表:保序,卷号做 uid,EPUB 大小 0 标为制作中;空回包 / 空列表都是错误。 +do + local body = [==[{"msgid":0,"bookkey":"de34d9","voldata":[ + ["1001",0,0,"單行本",1,"卷 01",120,240,"60.1","70.2","0","70.3","","2024-01-01"], + ["3086",0,0,"話",2,"話 086-090",90,180,"20","25","0","0","","2026-11-23"]]}]==] + local chapters, err = Mapper.chapters(body, "34410") + Assert.is_nil(err) + Assert.len(chapters, 2) + Assert.eq(chapters[1].idx, 1) + Assert.eq(chapters[1].uid, "1001") + Assert.eq(chapters[1].title, "卷 01") + Assert.eq(chapters[1].origin, "/getdownurl.php?b=34410&v=1001&mobi=2&vip=0&json=1") + Assert.is_nil(chapters[1].building) + Assert.is_true(chapters[2].building) + + local none, empty_err = Mapper.chapters("", "1") + Assert.is_nil(none) + Assert.not_nil(empty_err, "空回包不能当成没有卷") + local _n, no_vol = Mapper.chapters([[{"voldata":[]}]], "1") + Assert.not_nil(no_vol) +end + +-- 下载地址:有 url 返回;没有就把站点消息带出来。 +do + Assert.eq(Mapper.downUrl([[{"url":"https:\/\/dl.example\/a.epub","name":"a.epub"}]]), "https://dl.example/a.epub") + local url, err = Mapper.downUrl([[{"msg":"額度不足"}]]) + Assert.is_nil(url) + Assert.eq(err, "額度不足") + Assert.is_nil((Mapper.downUrl(""))) +end + +local function row(key, bookid, title, fav) + return ([[ %s コノシマルカ ]]) + :format(key, title, bookid, fav) +end + +-- 书架:只收打了收藏的行;页脚的 /c/10001.htm 不在表格行里;出现分页链接时标不完整。 +do + local html = '⬆︎' + .. row("de34d9", "34410", "有鬼拍不到", "") .. row("abc123", "1", "只訂閱", "none") + .. '
說明' + local rows, err, paged = Mapper.shelf(html) + Assert.is_nil(err) + Assert.len(rows, 1) + Assert.eq(rows[1].book.stable_id, "de34d9") + Assert.eq(rows[1].book.title, "有鬼拍不到") + Assert.eq(rows[1].book.authors, "コノシマルカ") + Assert.eq(rows[1].bookid, "34410") + Assert.is_false(paged) + + local _r, _e, more = Mapper.shelf(html .. '2') + Assert.is_true(more) + local empty = Mapper.shelf('⬆︎') + Assert.len(empty, 0, "空收藏是空列表") + local none, bad = Mapper.shelf("維護中") + Assert.is_nil(none) + Assert.not_nil(bad, "认不出的页面不能当空书架") +end diff --git a/tests/kmoe/source_spec.lua b/tests/kmoe/source_spec.lua new file mode 100644 index 0000000..432f698 --- /dev/null +++ b/tests/kmoe/source_spec.lua @@ -0,0 +1,151 @@ +--[[-- +moonsource_kmoe.source / chapter 离线用例:书城节点与筛选组、搜索聚合、卷下载(制作中、已有文件、非 EPUB)、缓存统计。 + +@module tests.moonsource_kmoe.source_spec +--]] +---@diagnostic disable: need-check-nil, undefined-field, inject-field, duplicate-set-field + +local Assert = require("support.assert") +local Stubs = require("support.stubs") +Stubs.install() + +local WORK = os.tmpname() +os.remove(WORK) +os.execute("mkdir -p '" .. WORK .. "'") + +package.preload["utils.paths"] = function() + return { + bookWorkDir = function(stable_id) return WORK .. "/" .. stable_id end, + ensureBookWork = function(stable_id) os.execute("mkdir -p '" .. WORK .. "/" .. stable_id .. "'") end, + } +end +package.preload["utils.settings"] = function() + return { getSource = function() return { cookie = "VOLSKEY=k" } end, saveSource = function() end } +end + +local queries, downloads, down_body = {}, {}, nil +package.preload["http.request"] = function() + return { + download = function(opts, dest, cb) + downloads[#downloads + 1] = { url = opts.url, dest = dest } + local f = io.open(dest, "wb") + f:write(down_body) + f:close() + cb(true, nil, { code = 200 }) + return { cancel = function() end } + end, + } +end + +local fake = { ua = "UA", BASE = "https://mox.moe" } +package.preload["moonsource_kmoe.client"] = function() + return { new = function() return fake end } +end +function fake.loggedIn() return true end +function fake.listAsync(_self, query, page, cb) + queries[#queries + 1] = { query = query, page = page } + cb({ { source_id = "kmoe", stable_id = query.s .. page } }, nil, page < 2) + return { cancel = function() end } +end +function fake.downUrlAsync(_self, origin, cb) + cb("https://dl.example/" .. origin) + return { cancel = function() end } +end + +local Kmoe = require("moonsource_kmoe.source") +local Chapter = require("moonsource_kmoe.chapter") +local src = Kmoe.new() + +-- 缺省节点:综合排序、不限状态 / 语言 / 分类;四组 chip 各有名字。 +do + local res + src:browseAsync({ limit = 1 }, function(r) res = r end) + Assert.eq(queries[1].query.by, "sortpoint") + Assert.eq(queries[1].query.s, "") + Assert.len(res.groups, 4) + Assert.eq(res.groups[1].active, "sortpoint,,,") + Assert.eq(res.groups[1].title, "排序") + Assert.eq(res.groups[4].title, "分类") + Assert.eq(res.groups[2].chips[2].id, "sortpoint,連載,,", "改状态保留其他三段") + Assert.eq(res.groups[4].chips[2].id, "sortpoint,,,幽默") +end + +-- 选中分类:查询串 CAT*<分类>,别的段原样;认不出的段回到缺省。 +do + queries = {} + local res + src:browseAsync({ node = "score,完結,jpn,幽默", limit = 1 }, function(r) res = r end) + Assert.eq(queries[1].query.s, "CAT*幽默") + Assert.eq(queries[1].query.by, "score") + Assert.eq(queries[1].query["end"], "完結") + Assert.eq(queries[1].query.lang, "jpn") + Assert.eq(res.groups[4].active, "score,完結,jpn,幽默") + + queries = {} + src:browseAsync({ node = "evil,x,y,不存在", limit = 1 }, function(r) res = r end) + Assert.eq(queries[1].query.by, "sortpoint") + Assert.eq(queries[1].query.s, "") + Assert.eq(res.groups[1].active, "sortpoint,,,") +end + +-- 搜索:按页聚合到源说没有更多为止。 +do + queries = {} + local res + src:searchAsync("小新", function(r) res = r end) + Assert.len(queries, 2) + Assert.eq(queries[1].query.s, "小新") + Assert.len(res.data, 2) +end + +local identity = { source_id = "kmoe", stable_id = "de34d9" } + +-- 制作中的卷不请求下载。 +do + local path, err + Chapter.materializeAsync(fake, identity, { uid = "1", origin = "o", building = true }, nil, + function(p, e) path, err = p, e end) + Stubs.flush() + Assert.is_nil(path) + Assert.matches(err, "制作中") + Assert.len(downloads, 0) +end + +-- 下到的不是 zip 就删掉报错;是 EPUB 就交出路径,下次直接复用不再下载。 +do + down_body = "額度不足" + local path, err + Chapter.materializeAsync(fake, identity, { uid = "3086", origin = "o" }, nil, function(p, e) path, err = p, e end) + Assert.is_nil(path) + Assert.matches(err, "EPUB") + Assert.is_nil(io.open(WORK .. "/de34d9/3086.epub", "rb"), "坏文件不留") + + down_body = "PK\3\4epub" + Chapter.materializeAsync(fake, identity, { uid = "3086", origin = "o" }, nil, function(p, e) path, err = p, e end) + Assert.eq(path, WORK .. "/de34d9/3086.epub") + Assert.eq(downloads[#downloads].url, "https://dl.example/o") + local n = #downloads + Chapter.materializeAsync(fake, identity, { uid = "3086", origin = "o" }, nil, function(p) path = p end) + Stubs.flush() + Assert.eq(path, WORK .. "/de34d9/3086.epub") + Assert.eq(#downloads, n, "已有文件不再下载") +end + +-- 缓存一段:单卷失败不阻断,统计已缓存 / 失败。 +do + down_body = "PK\3\4epub" + local toc = { + { uid = "a", origin = "o" }, { uid = "b", origin = "o", building = true }, { uid = "c", origin = "o" }, + } + local result + Chapter.cacheAsync(fake, identity, toc, 0, 3, nil, function(cached, total, failed, err) + result = { cached, total, failed, err } + end) + Stubs.flush() + Assert.eq(result[1], 2) + Assert.eq(result[2], 3) + Assert.eq(result[3], 1) + Assert.matches(result[4], "制作中") +end + +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/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 "$@"