commit 994167fbe55f10c5314a1afec13d02ba483460dd Author: Garfield Date: Fri Nov 27 08:08:02 2026 +0800 :truck: (split): 从月读拆出独立仓库,沿用原书源 id diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..cb8d0df --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,86 @@ +name: Release + +# 推送 vX.Y.Z(或 vX.Y.Z-rc.1 等预发布)标签:打包本仓库的插件为 zip → 建 Release 并上传。 +# 更新日志取自 CHANGELOG.md 里 "## <版本号>" 这一节,作为 Release 说明(月读的更新弹窗也会显示)。 +# 令牌默认用内置 GITHUB_TOKEN;需要时可在仓库密钥里配 RELEASE_TOKEN 覆盖。 +on: + push: + tags: + - "v*" + +jobs: + release: + runs-on: gitea + container: + image: node:22-bookworm + steps: + # 实例内网地址在任务容器里解析不了,签出和 API 都走公网地址 + - name: Checkout + uses: actions/checkout@v4 + with: + github-server-url: https://git.garfieldho.me + + - name: Resolve version + id: ver + run: | + set -euo pipefail + TAG="${GITHUB_REF_NAME}" + VERSION="${TAG#v}" + if [[ ! "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+([.+-].*)?$ ]]; then + echo "标签不合法:${TAG}(应为 vMAJOR.MINOR.PATCH)" + exit 1 + fi + PRERELEASE=false + [[ "$VERSION" == *-* ]] && PRERELEASE=true + { + echo "tag=${TAG}" + echo "version=${VERSION}" + echo "prerelease=${PRERELEASE}" + } >> "$GITHUB_OUTPUT" + shell: bash + + - name: Install packaging tools + run: apt-get update && apt-get install -y -o Acquire::Retries=3 rsync zip + + - name: Package plugin + run: tools/package.sh "${{ steps.ver.outputs.version }}" dist + + - name: Create release and upload assets + env: + TOKEN: ${{ secrets.RELEASE_TOKEN || secrets.GITHUB_TOKEN }} + TAG: ${{ steps.ver.outputs.tag }} + PRERELEASE: ${{ steps.ver.outputs.prerelease }} + VERSION: ${{ steps.ver.outputs.version }} + run: | + set -euo pipefail + : "${TOKEN:?没有可用令牌:没有内置令牌,也没有配置 RELEASE_TOKEN}" + API="https://git.garfieldho.me/api/v1/repos/${GITHUB_REPOSITORY}" + AUTH="Authorization: token ${TOKEN}" + + # 同一标签重跑:删掉旧 Release 再建,附件不会重复 + OLD=$(curl -fsS -H "$AUTH" "${API}/releases/tags/${TAG}" 2>/dev/null | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{console.log(JSON.parse(s).id||"")}catch(e){}})' || true) + [ -n "$OLD" ] && curl -fsS -X DELETE -H "$AUTH" "${API}/releases/${OLD}" + + BODY=$(node -e ' + const fs = require("fs"); + let notes = ""; + try { + const lines = fs.readFileSync("CHANGELOG.md", "utf8").split(/\r?\n/); + const start = lines.findIndex(l => l.trim() === "## " + process.env.VERSION); + if (start >= 0) { + let end = lines.findIndex((l, i) => i > start && /^## /.test(l)); + if (end < 0) end = lines.length; + notes = lines.slice(start + 1, end).join("\n").trim(); + } + } catch (e) {} + const tail = "给月读增加在线平台书源的 KOReader 插件。把 zip 解压到 KOReader 的 plugins/ 目录即可,附件 SHA256SUMS 用于校验。与各平台官方无关,使用风险自行承担。"; + console.log(JSON.stringify({tag_name:process.env.TAG,name:process.env.TAG,prerelease:process.env.PRERELEASE==="true",body:notes?notes+"\n\n---\n"+tail:tail})); + ') + ID=$(curl -fsS -X POST -H "$AUTH" -H "Content-Type: application/json" -d "$BODY" "${API}/releases" \ + | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>console.log(JSON.parse(s).id))') + + for f in dist/*; do + echo "upload $(basename "$f")" + curl -fsS -X POST -H "$AUTH" -F "attachment=@${f}" "${API}/releases/${ID}/assets?name=$(basename "$f")" >/dev/null + done + shell: bash diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..0bcbcdc --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.DS_Store +*.swp +dist/ +.idea/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..bd883c1 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,7 @@ +# 更新日志 + +## 0.0.1 + +- 「Kavita」书源拆成独立仓库,独立发版、独立更新;原来所有书源同版本一起更新的做法取消。 +- 检查更新与自动更新只管本书源:月读「书库 → 更新」里每个书源各有一项,只提示、不静默安装,装完重启 KOReader。 +- 书源 id、书架、进度、登录配置和缓存沿用原有数据,从旧版覆盖安装即可,无需迁移。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d69deba --- /dev/null +++ b/README.md @@ -0,0 +1,47 @@ +# 月读书源:Kavita + +给月读增加「Kavita」在线书源的 KOReader 插件。本仓库只含这一个插件,独立维护、独立发版,全部书源见 [moon-source 组织](https://git.garfieldho.me/moon-source)。 + +## 免责声明 + +- 本仓库与「Kavita」官方**没有任何关联**,所有商标、书名、内容归原权利人所有。 +- 插件只是在用户自己的账号、自己的设备上,按用户本人已有的权限读取内容;不提供、不分发任何书籍内容,也不绕过付费。 +- 使用可能违反对应平台的用户协议,账号可能被限制或封禁。是否使用、风险如何,由使用者自行判断并承担。 +- 权利人认为本仓库内容有问题,请通过仓库 issue 联系,核实后会及时处理。 + +## 安装 + +1. 先装好月读。 +2. 从 [Release](../../releases) 下载 `moonsource-kavita.koplugin-<版本>.zip`,解压出 `moonsource-kavita.koplugin` 目录,整个复制到 KOReader 的 `plugins/` 下。 +3. 重启 KOReader,在月读的书源列表里启用。 + +书源 id 是 `kavita`,与旧版(合并仓库、内置书源)相同,书架、进度、登录配置、缓存沿用原有数据,无需迁移。 + +## 更新 + +在月读的「书库 → Kavita 更新」里有「检查书源插件更新」和「自动检查书源插件更新」(默认开,每 24 小时一次,只提示、不静默安装)。 +本插件只检查并更新自己(本仓库的 Release),校验值取自 Release 的 `SHA256SUMS`,装完重启 KOReader。 + +> 从旧的合并仓库 `GarfieldTony/moon-source` 迁移:旧仓库的更新入口已停用,请直接从本仓库下载最新包覆盖安装。 + +## 发布 + +推送 `vX.Y.Z` 标签(带 `-` 的如 `v1.2.0-rc.1` 为预发布),Forgejo Actions 会打包 `moonsource-kavita.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/kavita/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-kavita.koplugin/_meta.lua b/moonsource-kavita.koplugin/_meta.lua new file mode 100644 index 0000000..6054adc --- /dev/null +++ b/moonsource-kavita.koplugin/_meta.lua @@ -0,0 +1,5 @@ +local _ = require("gettext") +return { + fullname = _("月读书源:Kavita"), + description = _("给月读增加「Kavita」书源。需要同时安装月读,与平台官方无关。"), +} diff --git a/moonsource-kavita.koplugin/main.lua b/moonsource-kavita.koplugin/main.lua new file mode 100644 index 0000000..19b027f --- /dev/null +++ b/moonsource-kavita.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_kavita", + is_doc_only = false, +} diff --git a/moonsource-kavita.koplugin/moon_source.lua b/moonsource-kavita.koplugin/moon_source.lua new file mode 100644 index 0000000..fdc6bd2 --- /dev/null +++ b/moonsource-kavita.koplugin/moon_source.lua @@ -0,0 +1,18 @@ +--[[-- +月读第三方书源描述:Kavita。契约见月读 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, + home_widgets = { require("moonsource_kavita.on_deck") }, + }, + meta = function() return require("moonsource_kavita.source").meta() end, + new = function() return require("moonsource_kavita.source").new() end, + setting = lazy("moonsource_kavita.setting"), +} diff --git a/moonsource-kavita.koplugin/moonsource_kavita/README.md b/moonsource-kavita.koplugin/moonsource_kavita/README.md new file mode 100644 index 0000000..d711500 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/README.md @@ -0,0 +1,17 @@ +# Kavita + +| 能力 | 是否支持 | 备注 | +| --- | --- | --- | +| 服务连接 | 支持 | Kavita 0.9 或更新版本;填写地址、API Key 并选择书库 | +| 书架拉取 | 支持 | 分页读取系列;多卷系列打开时选择卷 | +| 加入与移出远端书架 | 不支持 | 书架只读;本地删除不操作服务器藏书 | +| 详情与封面 | 支持 | 读取书库、系列及作者等元数据 | +| 整本下载与阅读 | 支持 | EPUB、PDF、CBZ 等 KOReader 支持的格式 | +| 漫画在线阅读与缓存 | 部分支持 | 依赖兼容的 kamare 增强版;无增强接口时 CBZ 可下载阅读,图片目录不能同样回退 | +| 阅读进度同步 | 支持 | 按卷保存;EPUB 使用 spine/锚点,固定版式使用页码 | +| 划线与备注同步 | 部分支持 | 仅 EPUB;依赖本地内容和坐标定位 | +| 阅读统计同步 | 部分支持 | 拉取历史快照;进度心跳可记入会话时长,不上传本地统计集合 | +| 整书书评 | 已实现,未实测 | 系列级书评,卷共享所属系列缓存;受服务器版本、Kavita+ 及外部评价权限影响 | +| 章评与段评 | 不支持 | 未接入可验证的读取接口;服务器存在章节评价模型,不等于插件已接入 | +| 评论回复与写操作 | 不支持 | 不发评、不改评分 | +| 离线阅读 | 支持 | 已下载文件及目录可用;漫画缓存取决于 kamare | diff --git a/moonsource-kavita.koplugin/moonsource_kavita/_meta.lua b/moonsource-kavita.koplugin/moonsource_kavita/_meta.lua new file mode 100644 index 0000000..fd061d5 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/_meta.lua @@ -0,0 +1,16 @@ +--[[-- +书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。 + +@module moonsource_kavita._meta +--]] + +local _ = require("l10n").get("moonsource_kavita") + +return { + id = "kavita", + name = _("Kavita"), + type = "book", + description = _("同步 Kavita 书架、电子书与漫画"), + abilities = { _("书架与卷目录同步(只读)"), _("进度同步"), _("EPUB 划线同步"), _("阅读历史拉取"), + _("漫画在线阅读与缓存(需 kamare 增强版)"), _("书评") }, +} diff --git a/moonsource-kavita.koplugin/moonsource_kavita/annotation.lua b/moonsource-kavita.koplugin/moonsource_kavita/annotation.lua new file mode 100644 index 0000000..32e4cab --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/annotation.lua @@ -0,0 +1,192 @@ +--[[-- +Kavita 注解的线上形态与同一性:纯函数、无 IO,pull / push / delete 共用同一条口径。 + +Kavita 网页端把备注存成 Quill Delta JSON(`comment`)+ Quill HTML(`commentHtml`), +纯文本 `commentPlainText` 是**后端从 HTML 去标签**算出来的(块级标签不插分隔,有损)。 +读回、写入、冲突判定三处必须共用这里的归一,否则同一段备注每轮都会被判「改过」→ 无限 update。 + +@module moonsource_kavita.annotation +--]] + +local JSON = require("json") +local Text = require("utils.text") + +local Annotation = {} + +--- 键分隔符用 US(0x1F):Kavita 的路径与选中文本里不会出现,天然不可撞。 +--- 导出是为了让源侧拼「同坐标」判定键时用同一个字符,不各写一份字面量。 +Annotation.KEY_SEP = string.char(31) + +--- 排版上不可见、但字节上会破坏比较的字符:ZWSP / ZWNJ / ZWJ / BOM / WORD JOINER。 +local ZERO_WIDTH = { "\226\128\139", "\226\128\140", "\226\128\141", "\239\187\191", "\226\129\160" } + +--- 写入前的归一:`\r\n` → `\n`、去掉尾部换行;纯空白在调用方判空。 +---@param note string|nil +---@return string +local function normalizeNote(note) + return (Text.normalizeNewlines(note):gsub("\n+$", "")) +end + +--- 比较用归一:trim + 内部连续空白压成单空格 + 剔除零宽字符。 +--- 只用于「是不是同一段备注」,不能拿它落库(会把用户的换行/缩进抹平)。 +---@param s string|nil +---@return string +local function comparisonText(s) + local text = tostring(s or ""):gsub("\r\n", "\n"):gsub("\r", "\n") + for _idx, zw in ipairs(ZERO_WIDTH) do text = text:gsub(zw, "") end + return (text:gsub("%s+", " "):gsub("^%s+", ""):gsub("%s+$", "")) +end + +--- Delta → 纯文本:`ops[*].insert` 里的字符串拼接,embed(图片等)与 `attributes` 一律忽略。 +--- 末尾换行是 Delta 文档的收尾,不是内容;拼完剥掉。 +---@param data table +---@return string +local function deltaText(data) + local ops = data.ops + if type(ops) ~= "table" then return "" end + local parts = {} + for _idx, op in ipairs(ops) do + if type(op) == "table" and type(op.insert) == "string" then + parts[#parts + 1] = op.insert + end + end + return (table.concat(parts):gsub("\n+$", "")) +end + +--- HTML → 纯文本:块级边界(`

` / `` / `
`)换行,其余标签丢弃,实体解码。 +--- 不能直接用 Text.stripHtml:它会丢弃空行,而备注里的空行是内容。 +---@param html string +---@return string +local function htmlText(html) + local text = tostring(html or ""):gsub("\r\n", "\n"):gsub("\r", "\n") + -- Quill 的空行是 `


`:先整个折成一个换行,否则
与

会各补一行。 + text = text:gsub("]*>%s*%s*

", "\n") + text = text:gsub("", "\n"):gsub("", "\n"):gsub("", "\n") + text = text:gsub("<[^>]*>", "") + -- Quill 把连续空格写成  ,解出来是 NBSP,还原成普通空格才能与本地文本对上。 + text = Text.xmlDecode(text):gsub("\194\160", " ") + return (text:gsub("\n+$", "")) +end + +--- 读回归一。优先级:commentHtml → commentPlainText → comment 的 Delta → comment 原文(legacy 纯文本)。 +--- 空值集合("" / "{}" / {"ops":[]} / {"ops":[{"insert":"\n"}]} / null)一律 ""。 +---@param comment string|nil +---@param comment_html string|nil +---@param comment_plain_text string|nil +---@return string +function Annotation.noteText(comment, comment_html, comment_plain_text) + if type(comment_html) == "string" and Text.trim(comment_html) ~= "" then + return htmlText(comment_html) + end + if type(comment_plain_text) == "string" and Text.trim(comment_plain_text) ~= "" then + -- 后端 StripHtml 的产物,块间无分隔;这里只需去首尾空白。 + return Text.trim(comment_plain_text) + end + local raw = tostring(comment or "") + if Text.trim(raw) == "" or Text.trim(raw) == "null" then return "" end + local ok, data = pcall(JSON.decode, raw) + -- json.decode 失败 = 存量纯文本备注(网页端 JSON.parse 会崩,但设备侧要能读)。 + if not ok then return raw end + if data == nil then return "" end + if type(data) ~= "table" then return tostring(data) end + local text = deltaText(data) + if text:match("^%s*$") then return "" end + return text +end + +--- 写回归一(create / update 共用):与 Web 同构,`comment` 为 Quill Delta JSON、`commentHtml` 为对应 HTML。 +--- 空备注写 `"{}"` + `""`(Web「新建未输入」的原样),否则网页端 `JSON.parse(comment)` 会崩。 +---@param note string|nil +---@return { comment: string, commentHtml: string } +function Annotation.toRemote(note) + local text = normalizeNote(note) + if text:match("^%s*$") then + return { comment = "{}", commentHtml = "" } + end + local lines = {} + for line in (text .. "\n"):gmatch("([^\n]*)\n") do + lines[#lines + 1] = line == "" and "


" or ("

" .. Text.xmlEscape(line) .. "

") + end + return { + comment = JSON.encode({ ops = { { insert = text .. "\n" } } }), + commentHtml = table.concat(lines), + } +end + +--- 幂等键(spec §8.2):`\31\31\31`。 +--- `comment` 不进键(备注可改,进键会把「改备注」变成「新建」);`selectedText` 用比较归一, +--- 否则网页端/设备端的换行差异会让同一条划线认不出来(落库仍存原文)。 +--- 字段名两套都要认:线上 DTO 用 `xPath` / `endingXPath` / `selectedText`,落库后的 payload +--- (阅读器快照、远端去重的输入)用 `kavita_xpath` / `kavita_ending_xpath` / `text`。 +---@param ann { chapterId: integer|nil, xPath: string|nil, endingXPath: string|nil, selectedText: string|nil, kavita_xpath: string|nil, kavita_ending_xpath: string|nil, text: string|nil } +---@return string +function Annotation.key(ann) + local selected = ann.selectedText + if selected == nil then selected = ann.text end + return table.concat({ + tostring(ann.chapterId or ""), + tostring(ann.xPath or ann.kavita_xpath or ""), + tostring(ann.endingXPath or ann.kavita_ending_xpath or ""), + comparisonText(selected), + }, Annotation.KEY_SEP) +end + +--- 在对账列表里找本地这条注解的远端对应:同键多条取 id 最小(网页端重扫可能留下重复), +--- 没有 id 的条目没法采纳,直接跳过。 +---@param remote table[]|nil +---@param ann table +---@return table|nil +function Annotation.match(remote, ann) + if type(remote) ~= "table" then return nil end + local wanted = Annotation.key(ann) + local best, best_id + for _idx, item in ipairs(remote) do + local id = type(item) == "table" and tonumber(item.id) + if id and (not best_id or id < best_id) and Annotation.key(item) == wanted then + best, best_id = item, id + end + end + return best +end + +--- 比较两段备注是不是同一段:trim、内部连续空白压成单空格、剔除零宽字符,两边都空判等。 +--- push / pull / 冲突裁决共用;不能拿它落库(换行与缩进会被抹平)。 +---@param a string|nil +---@param b string|nil +---@return boolean +function Annotation.sameNote(a, b) + return comparisonText(a) == comparisonText(b) +end + +--- owner 比较:远端 id 是数字,调用方可能拿到字符串(配置/`/api/Users/me` 解析),两边能对上。 +---@param a any +---@param b any +---@return boolean +local function sameOwner(a, b) + local na, nb = tonumber(a), tonumber(b) + if na and nb then return na == nb end + return tostring(a) == tostring(b) +end + +--- 该章全部注解(`GET /api/Annotation/all`,无分页)。`owner_id` 非空时只留自己的: +--- 账号开了「查看他人注解」后接口会混入别人的条目,删改别人的会整批 400。 +---@param client KavitaClient +---@param chapter_id integer +---@param owner_id integer|string|nil nil / "" = 拿不到当前用户时的降级:不过滤 +---@param cb fun(list: table[]|nil, err: string|nil) +---@return HttpJob|nil +function Annotation.listByChapter(client, chapter_id, owner_id, cb) + return client:json("GET", "/api/Annotation/all", { chapterId = chapter_id }, nil, function(data, err) + if not data then return cb(nil, err) end + local filter = owner_id ~= nil and owner_id ~= "" + local out = {} + for _idx, item in ipairs(type(data) == "table" and data or {}) do + if type(item) == "table" and (not filter or sameOwner(item.ownerUserId, owner_id)) then + out[#out + 1] = item + end + end + cb(out) + end) +end + +return Annotation diff --git a/moonsource-kavita.koplugin/moonsource_kavita/busy.lua b/moonsource-kavita.koplugin/moonsource_kavita/busy.lua new file mode 100644 index 0000000..703c3e1 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/busy.lua @@ -0,0 +1,33 @@ +--[[-- +同步阻塞操作期间的忙碌窗:kamare 的缓存操作直接写盘,主线程会停住。 +先把窗画出来、强制重绘一次,再动手;返回后关窗。 + +调用方只给标题与要跑的函数;`fn` 的返回值原样透传(最多四个)。 +关闭失败不会发生:窗在建好后才交给 UIManager。 + +@module moonsource_kavita.busy +--]] + +local _ = require("l10n").get("moonsource_kavita") + +local Busy = {} + +---@param title string 窗标题(一般是动作名,如「清理已读」) +---@param fn fun(): any +---@return any, any, any, any +function Busy.run(title, fn) + local UIManager = require("ui/uimanager") + local dialog = require("ui.themes.widgets.progress_dialog"):new{ + title = title, + text = _("正在清理…"), + dismissable = false, + } + local ok, code, message, detail = dialog:showWhile(function() + if UIManager.forceRePaint then UIManager:forceRePaint() end + return fn() + end) + dialog:close() + return ok, code, message, detail +end + +return Busy diff --git a/moonsource-kavita.koplugin/moonsource_kavita/cache.lua b/moonsource-kavita.koplugin/moonsource_kavita/cache.lua new file mode 100644 index 0000000..57defda --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/cache.lua @@ -0,0 +1,912 @@ +--[[-- +kamare 漫画缓存适配层:探测、能力门面、配置镜像、错误文案、书架投影、删除保护。 + +kamare 是缓存的唯一执行者与写入者;moon 只读状态、发下载 / 删除 / 队列请求。 +kamare 的模块一律在函数内 `pcall(require, …)`,绝不顶层 require、也不持有它的 table: +插件升级 / 重载后旧 table 会失效。探测成功结果进程内记忆,失败不记忆(require 自带缓存)。 + +@module moonsource_kavita.cache +--]] + +local _ = require("l10n").get("moonsource_kavita") +local T = require("ffi/util").template +local logger = require("utils.log") +local Text = require("utils.text") + +local Cache = {} + +---@class KamareProbe +---@field ok boolean +---@field state "missing"|"official"|"incompatible"|"enhanced" +---@field reason string|nil +---@field api_version integer|nil +---@field capabilities table|nil +---@field version string|nil +---@field path string|nil + +--- 成功探测的记忆(只存元信息,不存模块 table)。 +---@type KamareProbe|nil +local memo + +--- 当前进程内已镜像过的配置(base_url\0api_key),失败不写。 +---@type string|nil +local mirrored + +--- 本次会话的镜像是否失败过(设置页第五态)。 +local mirror_failed = false + +--- 一次性日志的去重键(同一原因只记一行,状态变化才再记)。 +local logged = {} + +--- 当前打开的章(kamare 保证同一时刻只有一个 viewer)。 +---@type { base_url: string|nil, chapter_id: any }|nil +local active + +--- 书架投影记忆,按服务器分开;只由成功写操作 / 手动刷新 / Registry.reload 失效。 +---@type table +local shelves = {} + +--- 上次记录过的暂停原因(按服务器),轮询时只在变化时写日志。 +---@type table +local pause_reason_logged = {} + +--- 记一行日志;同一 key 在本进程内只记一次。 +---@param key string +---@param text string +local function logOnce(key, text) + if logged[key] then return end + logged[key] = true + logger.info(text) +end + +--- 能力名清单(排序后按分隔符拼接),日志与设置页共用一份口径。 +---@param capabilities table|nil +---@param separator string|nil 缺省逗号(日志);设置页传「、」 +---@return string +function Cache.capabilityNames(capabilities, separator) + local names = {} + for name, on in pairs(type(capabilities) == "table" and capabilities or {}) do + if on == true then names[#names + 1] = tostring(name) end + end + table.sort(names) + if #names == 0 then return "none" end + return table.concat(names, separator or ",") +end + +--- 探测结果每进程(每种结果)一行:四态 + 版本 + 能力;不记 API Key。 +---@param probe KamareProbe +local function logProbe(probe) + local capabilities = Cache.capabilityNames(probe.capabilities) + local signature = string.format("probe|%s|%s|%s", probe.state, tostring(probe.version), capabilities) + logOnce(signature, string.format("kamare probe ok=%s state=%s version=%s caps=%s", + tostring(probe.ok), probe.state, tostring(probe.version), capabilities)) +end + +---@param ids any +---@return string +local function joinIds(ids) + if type(ids) ~= "table" then return "-" end + local parts = {} + for _idx, id in ipairs(ids) do parts[#parts + 1] = tostring(id) end + return #parts > 0 and table.concat(parts, ",") or "-" +end + +--- 每次缓存写操作一行: + 章 id + code(成功记 ok)。 +---@param op string +---@param ids any +---@param code string|nil +local function logWrite(op, ids, code) + logger.info("cache " .. op .. " cid=" .. joinIds(ids) .. " code=" .. tostring(code or "ok")) +end + +--- 目录条目 → chapterId 列表(只用于日志)。 +---@param entries table|nil +---@return table +local function entryIds(entries) + local ids = {} + for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do + if type(entry) == "table" then + ids[#ids + 1] = entry.chapterId or entry.chapter_id or entry.id or "?" + end + end + return ids +end + +--- 函数内 require:拿不到就 nil,不抛错。 +---@param name string +---@return table|nil +local function loadModule(name) + local ok, mod = pcall(require, name) + if ok and type(mod) == "table" then return mod end + return nil +end + +--- 本地封面文件存在才算数(缓存可能已被 kamare 清理)。 +---@param path any +---@return boolean +local function fileExists(path) + if type(path) ~= "string" or path == "" then return false end + local file = io.open(path, "rb") + if not file then return false end + file:close() + return true +end + +--- 官方 / 旧版 kamare 的查看器是否可用(legacy 通道的触发条件)。 +---@return boolean +local function legacyAvailable() + local viewer = loadModule("kamareimageviewer") + return type(viewer) == "table" and type(viewer.new) == "function" +end + +--- `kamareversion` 返回字符串(发布时写入);老写法可能是表。 +---@return string|nil +local function kamareVersion() + local ok, value = pcall(require, "kamareversion") + if not ok then return nil end + if type(value) == "string" and value ~= "" then return value end + if type(value) == "table" then + local version = value.version or value.VERSION + if type(version) == "string" and version ~= "" then return version end + end + return nil +end + +--- 模块文件路径:借任一公开函数反查,不扫 package.path。 +--- 归一重复斜杠:KOReader 的 `extra_plugin_paths` 带尾斜杠,data 目录里的插件会被拼成 +--- `plugins//kamare.koplugin`,原样显示会让人以为路径写错了(文件系统本身不介意)。 +---@param mod table +---@return string|nil +local function modulePath(mod) + for _idx, name in ipairs({ "status", "summary", "enqueue", "delete", "open" }) do + if type(mod[name]) == "function" then + local ok, info = pcall(debug.getinfo, mod[name], "S") + local source = ok and info and info.source + if type(source) == "string" and source:sub(1, 1) == "@" then + return (source:sub(2):gsub("/+", "/")) + end + end + end + return nil +end + +---@param mod table +---@return KamareProbe +local function enhancedProbe(mod) + local api_version = tonumber(mod.api_version) + local capabilities = type(mod.capabilities) == "table" and mod.capabilities or {} + local ok = api_version == 1 + return { + ok = ok, + state = ok and "enhanced" or "incompatible", + reason = ok and nil or "major_mismatch", + api_version = api_version, + capabilities = capabilities, + version = kamareVersion(), + path = modulePath(mod), + } +end + +---@param official boolean +---@return KamareProbe +local function missingProbe(official) + return { + ok = false, + state = official and "official" or "missing", + reason = "missing", + api_version = nil, + capabilities = nil, + version = kamareVersion(), + path = nil, + } +end + +--- 清空进程内记忆(测试缝;Registry.reload 不经过这里,探测态本就与源实例无关)。 +function Cache.reset() + memo = nil + mirrored = nil + mirror_failed = false + logged = {} + shelves = {} + active = nil + pause_reason_logged = {} +end + +---@return KamareProbe +function Cache.probe() + if memo then return memo end + local mod = loadModule("kamarecache") + if mod then + local result = enhancedProbe(mod) + -- 只有增强版值得记:官方 / 不兼容 / 未安装都要能随安装或升级立刻变化。 + if result.ok then memo = result end + logProbe(result) + return result + end + local result = missingProbe(legacyAvailable()) + logProbe(result) + return result +end + +--- 重新探测(设置页的「重新检测」):清掉成功记忆再探;结果没变则不重复记日志。 +---@return KamareProbe +function Cache.reprobe() + memo = nil + return Cache.probe() +end + +--- 插件根目录:kamare 已装用它当前所在目录(就地替换),否则用月读自己的。 +---@param own_path string|nil book.koplugin 目录 +---@return string +function Cache.pluginsDir(own_path) + local path = Cache.probe().path + local installed = type(path) == "string" and path:gsub("/+", "/"):match("^(.*)/[^/]+%.koplugin/") + if installed then return installed end + if type(own_path) == "string" and own_path ~= "" then + local own = own_path:gsub("/+", "/"):gsub("/+$", "") + return own:match("^(.*)/[^/]+$") or own + end + local source = debug.getinfo(1, "S").source + if type(source) == "string" and source:sub(1, 1) == "@" then source = source:sub(2) end + -- 本文件在 /moonsource-kavita.koplugin/moonsource_kavita/,往上三级 + return source:match("^(.*)/[^/]+%.koplugin/moonsource_kavita/[^/]+$") or "plugins" +end + +--- 功能清单:kamare 随包提供的用户可见功能文案(kamarefeatures.lua)。 +--- 只用于展示;缺失 / api_version 不符 / 结构不合法都当没有清单,不做能力推断回退。 +---@param probe KamareProbe|nil +---@return string|nil +function Cache.featureText(probe) + probe = probe or Cache.probe() + if not probe.ok then return nil end + local ok, manifest = pcall(require, "kamarefeatures") + if not ok or type(manifest) ~= "table" or manifest.api_version ~= 1 then return nil end + local list = manifest.features + if type(list) ~= "table" then return nil end + local parts, seen = {}, {} + for _idx, item in ipairs(list) do + if type(item) == "string" and item ~= "" and not seen[item] then + seen[item] = true + parts[#parts + 1] = item + if #parts == 8 then break end + end + end + if #parts == 0 then return nil end + return table.concat(parts, " · ") +end + +--- 能力是否可用。`open` 是唯一允许退回 legacy 通道的能力(02 A4)。 +---@param cap string|nil +---@return boolean +function Cache.available(cap) + local probe = Cache.probe() + if not probe.ok then + return cap == "open" and legacyAvailable() or false + end + if cap == nil then return true end + local capabilities = probe.capabilities or {} + if cap == "open" then + return capabilities.open == true or legacyAvailable() + end + return capabilities[cap] == true +end + +--- 源配置:只读 base_url / api_key,其它键与缓存无关。 +---@return table +local function config() + local value = require("utils.settings").getSource("kavita") + return type(value) == "table" and value or {} +end + +--- 与 Client.new 同口径:去尾斜杠、去首尾空白;空串当未给。 +---@param url any +---@return string|nil +local function normBase(url) + local text = Text.rtrimSlashes(Text.trim(url)) + return text ~= "" and text or nil +end + +--- API Key 里的空白一律去掉(粘贴时常带换行 / 空格)。 +---@param key any +---@return string|nil +local function normKey(key) + local text = Text.stripWhitespace(key) + return text ~= "" and text or nil +end + +--- 当前服务器;未配置返回 nil(调用方按 unknown_server 静默降级)。 +---@return string|nil +local function targetBase() + return normBase(config().base_url) +end + +--- 能力对应的 kamare 函数名。 +local KAMARE = { + status = "status", + summary = "summary", + resume = "resume_page", + queue = "queue_state", + index = "index", + enqueue = "enqueue", + delete = "delete", + estimate = "estimate", + open = "open", + server = "register_server", + chapters = "chapters", + delete_all = "delete_all", +} + +--- 取能力对应的函数:缺能力 / 缺函数一律 unsupported(调用点不各写一套)。 +--- 队列控制是同一个能力(queue_control)下的三个动作,由 fn_name 指定函数。 +---@param name string +---@param fn_name string|nil 缺省为 KAMARE[name] +---@return table|nil mod, string|nil code, function|nil fn +local function capability(name, fn_name) + local probe = Cache.probe() + if not probe.ok then return nil, "unsupported" end + if (probe.capabilities or {})[name] ~= true then return nil, "unsupported" end + local mod = loadModule("kamarecache") + if not mod then return nil, "unsupported" end + local fn = mod[fn_name or KAMARE[name]] + if type(fn) ~= "function" then return nil, "unsupported" end + return mod, nil, fn +end + +--- 写:把 moon 的服务器地址 + API Key 镜像给 kamare(幂等、不联网、不传 name)。 +---@param base_url string|nil +---@param api_key string|nil +---@return string|nil server_key, string|nil code, string|nil message +function Cache.registerServer(base_url, api_key) + local mod, code, fn = capability("server") + if not mod then return nil, code end + local url = normBase(base_url) or targetBase() + local key = normKey(api_key) or normKey(config().api_key) + if not url then return nil, "base_url_required" end + if not key then return nil, "api_key_required" end + local server_key, err, message = fn({ base_url = url, api_key = key }) + if server_key then + mirrored = url .. "\0" .. key + mirror_failed = false + else + mirror_failed = true + logOnce("mirror|" .. tostring(err), "cache mirror failed code=" .. tostring(err)) + end + return server_key, err, message +end + +--- 本次会话内镜像是否失败过(设置页的第五态)。 +---@return boolean +function Cache.mirrorFailed() + return mirror_failed +end + +--- 镜像兜底:读路径首次操作前一次;写路径每次幂等重放。 +---@param write boolean +---@param base_url string|nil +---@param api_key string|nil +---@return boolean +local function ensureMirror(write, base_url, api_key) + local probe = Cache.probe() + if not probe.ok or (probe.capabilities or {}).server ~= true then return false end + local url = normBase(base_url) or targetBase() + local key = normKey(api_key) or normKey(config().api_key) + if not url or not key then return false end + if not write and mirrored == url .. "\0" .. key then return true end + return Cache.registerServer(url, key) ~= nil +end + +---@param list any +---@param value any +---@return boolean +local function includes(list, value) + if type(list) ~= "table" then return false end + for _idx, item in ipairs(list) do + if tostring(item) == tostring(value) then return true end + end + return false +end + +--- 这一章是不是正在 kamare 查看器里(删除按钮据此置灰)。 +---@param chapter_id any +---@return boolean +function Cache.isChapterOpen(chapter_id) + if not active then return false end + if tostring(active.chapter_id) ~= tostring(chapter_id) then return false end + local base_url = targetBase() + return base_url == nil or active.base_url == base_url +end + +--- 关闭回调包一层:先清 active,再交给调用方(source 写双行进度)。 +---@param opts table +---@param base_url string|nil +---@param chapter_id any +---@return table +local function wrapClose(opts, base_url, chapter_id) + local user_close = opts.on_close + local wrapped = {} + for key, value in pairs(opts) do wrapped[key] = value end + wrapped.on_close = function(page, total) + if active and tostring(active.chapter_id) == tostring(chapter_id) + and (base_url == nil or active.base_url == base_url) then + active = nil + end + if user_close then return user_close(page, total) end + end + return wrapped +end + +--- kamare 的页尺寸接口页号有时从 0 起,查看器只认从 1 起;拿不到就不预热。 +---@param client table +---@param chapter_id any +---@return table|nil +local function dimensions(client, chapter_id) + if type(client.getFileDimensions) ~= "function" then return nil end + local dims, code = client:getFileDimensions(chapter_id) + if type(dims) ~= "table" or type(code) ~= "number" or code < 200 or code >= 300 then return nil end + local zero_based = false + for _idx, item in ipairs(dims) do + if item.pageNumber == 0 then zero_based = true end + end + if zero_based then + for _idx, item in ipairs(dims) do + if type(item.pageNumber) == "number" then item.pageNumber = item.pageNumber + 1 end + end + end + return dims +end + +--- 官方 / 旧版 kamare 的查看器通道:02 A4 要求官方版(无 kamarecache)与增强版缺 `open` 时 +--- 仍保住今天的在线看图,所以这条通道留在适配层;source.lua 里那份重复实现已删(12 号票)。 +---@param opts table +---@return table|nil viewer, string|nil code, string|nil message +local function legacyOpen(opts) + local Viewer = loadModule("kamareimageviewer") + if not Viewer or type(Viewer.new) ~= "function" then return nil, "unsupported" end + local entry = opts.entry or {} + if (tonumber(entry.pages) or 0) <= 0 then return nil, "no_pages" end + local client = loadModule("kavitaclient") + if not client then return nil, "open_failed", _("打开漫画阅读器失败") end + local ok, viewer, code, message = pcall(function() + client.base_url, client.api_key, client.auth_method, client.bearer = + opts.base_url, opts.api_key, "apiKey", nil + if not client.device_id or client.device_id == "" then client.device_id = "moon-kavita" end + local images = client:streamChapter(entry.chapterId) + if type(images) ~= "table" then return nil, "open_failed", _("打开漫画阅读器失败") end + local LuaSettings = require("luasettings") + local spec = Viewer:new{ + images_list_data = images, + images_list_nb = entry.pages, + title = opts.title, + fullscreen = true, + metadata = { + seriesName = opts.title, + seriesId = entry.seriesId, + libraryId = entry.libraryId, + volumeId = entry.volumeId, + chapterId = entry.chapterId, + chapter = { id = entry.chapterId, volumeId = entry.volumeId, pages = entry.pages }, + startPage = opts.start_page, + content_type = "chapter", + }, + preloaded_dimensions = dimensions(client, entry.chapterId), + kamare_settings = LuaSettings:open(require("datastorage"):getSettingsDir() .. "/kamare.lua"), + on_close_callback = opts.on_close, + on_next_chapter_callback = opts.on_next and function(next_id) + require("ui/uimanager"):nextTick(function() opts.on_next(next_id) end) + end or nil, + } + if spec._aborted then return nil, "viewer_running", _("漫画阅读器已在运行") end + require("ui/uimanager"):show(spec) + return spec + end) + if not ok then + logger.warn("kavita.cache legacy open failed", viewer) + return nil, "open_failed", _("打开漫画阅读器失败") + end + return viewer, code, message +end + +--- 增强版是否接管打开:起始页 / 离线全归 kamare(journal + 缓存)。 +--- 官方版或增强版缺 `open` 时退回 legacy 查看器,起始页要 moon 自己给。 +---@return boolean +function Cache.enhancedOpen() + local probe = Cache.probe() + if not probe.ok or (probe.capabilities or {}).open ~= true then return false end + local mod = loadModule("kamarecache") + return mod ~= nil and type(mod.open) == "function" +end + +--- 打开一卷:enhanced 有 open 交 kamare 判缓存 / 离线 / 起始页;否则退回 legacy 查看器。 +---@param opts { base_url: string|nil, api_key: string|nil, entry: table, title: string, +--- start_page: integer|nil, on_close: function|nil, on_next: function|nil } +---@return table|nil viewer, string|nil code, string|nil message +function Cache.open(opts) + opts = type(opts) == "table" and opts or {} + local entry = opts.entry or {} + local base_url = normBase(opts.base_url) or targetBase() + local api_key = normKey(opts.api_key) or normKey(config().api_key) + if not base_url then return nil, "unknown_server" end + local probe = Cache.probe() + local mod = probe.ok and loadModule("kamarecache") or nil + local use_enhanced = Cache.enhancedOpen() + local viewer, code, message + if use_enhanced then + ensureMirror(false, base_url, api_key) + viewer, code, message = mod.open(wrapClose(opts, base_url, entry.chapterId)) + else + local next_opts = {} + for key, value in pairs(opts) do next_opts[key] = value end + next_opts.base_url, next_opts.api_key = base_url, api_key + viewer, code, message = legacyOpen(wrapClose(next_opts, base_url, entry.chapterId)) + end + if viewer then + active = { base_url = base_url, chapter_id = entry.chapterId } + elseif code then + logOnce("open|" .. tostring(entry.chapterId) .. "|" .. code, + "cache open cid=" .. tostring(entry.chapterId) .. " code=" .. tostring(code)) + end + return viewer, code, message +end + +--- 让书架投影失效(手动刷新书架 / Registry.reload 都走这里)。 +function Cache.resetShelf() + shelves = {} +end + +--- 「已缓存」的唯一口径:complete 或 stale(stale 与 complete 等价,03 A3)。 +--- 同时接受两种形状:Cache.status 的章状态(state)与书架 index 的系列摘要(complete/stale)。 +---@param status table|nil +---@return boolean +function Cache.isCached(status) + if type(status) ~= "table" then return false end + if status.state == "complete" or status.state == "stale" then return true end + if status.state ~= nil then return false end + return status.complete == true or status.stale == true +end + +--- 只读:书架投影(series_ids / mark / cover),按服务器记忆;无 TTL。 +---@return ShelfCacheProjection|nil +function Cache.shelf() + local base_url = targetBase() + if not base_url then return nil end + if shelves[base_url] then return shelves[base_url] end + local index = Cache.index() + if not index then return nil end + local projection = { series_ids = {}, mark = {}, cover = {} } + local series = type(index.series) == "table" and index.series or {} + for key, info in pairs(series) do + if type(info) == "table" then + local stable_id = tostring(info.seriesId or key) + -- 只有 complete / stale 算「已缓存」;queued / downloading 只有 .part,离线打不开。 + if (tonumber(info.chapters) or 0) > 0 and Cache.isCached(info) then + projection.series_ids[stable_id] = true + projection.mark[stable_id] = true + end + local cover = info.coverPath + if type(cover) == "string" and cover ~= "" and fileExists(cover) then + projection.cover[stable_id] = cover + end + end + end + shelves[base_url] = projection + return projection +end + +--- 只读:缓存占用(设置页与「缓存占用」展示;确认框一律用 estimate)。 +---@return table|nil, string|nil, string|nil +function Cache.summary() + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("summary") + if not mod then return nil, code end + ensureMirror(false) + return fn(base_url) +end + +--- 只读:所有服务器(含未关联)的合计占用;未配置服务器时用它算「清理全部」的预览。 +---@return table|nil, string|nil, string|nil +function Cache.summaryAll() + local mod, code, fn = capability("summary") + if not mod then return nil, code end + return fn(nil) +end + +--- 只读:当前服务器的清理计划(每章 facts)。series_id 可选。 +---@param series_id any|nil +---@return table[]|nil, string|nil, string|nil +function Cache.chapters(series_id) + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("chapters") + if not mod then return nil, code end + ensureMirror(false) + return fn(base_url, series_id) +end + +--- 只读:已缓存章的状态(complete / stale / partial)。 +---@param chapter_id any +---@return table|nil, string|nil, string|nil +function Cache.status(chapter_id) + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("status") + if not mod then return nil, code end + ensureMirror(false) + return fn(base_url, chapter_id) +end + +--- 只读:续读页(journal > snapshot > nil)。 +---@param chapter_id any +---@param series_id any|nil +---@return table|nil, string|nil, string|nil +function Cache.resumePage(chapter_id, series_id) + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("resume") + if not mod then return nil, code end + ensureMirror(false) + return fn(base_url, chapter_id, series_id) +end + +--- 只读:按当前服务器过滤后的队列状态。 +---@return table|nil, string|nil, string|nil +function Cache.queueState() + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("queue") + if not mod then return nil, code end + ensureMirror(false) + local state, err, message = fn(base_url) + if type(state) == "table" then + -- 1 秒轮询:只在暂停原因变化时记一行,恢复后清空,下次同原因再记。 + if state.pause_reason ~= nil and state.pause_reason ~= "" then + if pause_reason_logged[base_url] ~= state.pause_reason then + pause_reason_logged[base_url] = state.pause_reason + logger.info("queue paused reason=" .. tostring(state.pause_reason)) + end + else + pause_reason_logged[base_url] = nil + end + end + return state, err, message +end + +--- 批量暂停(全局队列,契约明确作用于所有服务器)。 +---@return boolean|nil, string|nil, string|nil +function Cache.queuePause() + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("queue_control", "queue_pause") + if not mod then return nil, code end + ensureMirror(true) + local ok, err, message = fn(base_url) + logWrite("queue_pause", nil, err) + if ok then Cache.resetShelf() end + return ok, err, message +end + +--- 批量恢复。 +---@return boolean|nil, string|nil, string|nil +function Cache.queueResume() + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("queue_control", "queue_resume") + if not mod then return nil, code end + ensureMirror(true) + local ok, err, message = fn(base_url) + logWrite("queue_resume", nil, err) + if ok then Cache.resetShelf() end + return ok, err, message +end + +--- 只重试 queued / failed 的条目。 +---@param chapter_ids any[] +---@return boolean|nil, string|nil, string|nil +function Cache.queueRetry(chapter_ids) + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("queue_control", "queue_retry") + if not mod then return nil, code end + ensureMirror(true) + local ok, err, message = fn(base_url, chapter_ids) + logWrite("queue_retry", chapter_ids, err) + if ok then Cache.resetShelf() end + return ok, err, message +end + +--- 只读:书架索引投影(一次全量,不分页)。 +---@return table|nil, string|nil, string|nil +function Cache.index() + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("index") + if not mod then return nil, code end + ensureMirror(false) + return fn(base_url) +end + +--- 写:入队下载。成功时第三个返回值是 { chapters, bytes, available }。 +---@param entries table[] +---@return boolean|nil, string|nil, any, table|nil +function Cache.enqueue(entries) + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("enqueue") + if not mod then return nil, code end + ensureMirror(true) + local ok, err, message, detail = fn(base_url, entries) + logWrite("enqueue", entryIds(entries), err) + if ok then Cache.resetShelf() end + return ok, err, message, detail +end + +--- 写:删除缓存(不碰 journal)。正在查看器里打开的章本地先拦一次(与 kamare 双层保护)。 +---@param chapter_ids any[] +---@return boolean|nil, string|nil, string|nil, integer|nil +function Cache.delete(chapter_ids) + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + if active and active.base_url == base_url and includes(chapter_ids, active.chapter_id) then + return nil, "chapter_open" + end + local mod, code, fn = capability("delete") + if not mod then return nil, code end + ensureMirror(true) + local ok, err, message, deleted = fn(base_url, chapter_ids) + logWrite("delete", chapter_ids, err) + if ok then Cache.resetShelf() end + return ok, err, message, deleted +end + +--- 写:清空所有服务器(含未关联)。成功时第四个返回值是 { chapters, bytes } 估算。 +---@return boolean|nil, string|nil, string|nil, table|nil +function Cache.deleteAll() + local mod, code, fn = capability("delete_all") + if not mod then return nil, code end + local ok, err, third = fn() + logWrite("delete_all", nil, err) + if ok then + Cache.resetShelf() + return true, nil, nil, type(third) == "table" and third or nil + end + return nil, err, third +end + +--- 只读:下载前估算(数量 / 峰值 / 可用 / 裁决),不写盘、不入队、不建 serverKey。 +---@param entries table[] +---@return table|nil, string|nil, string|nil, table|nil +function Cache.estimate(entries) + local base_url = targetBase() + if not base_url then return nil, "unknown_server" end + local mod, code, fn = capability("estimate") + if not mod then return nil, code end + ensureMirror(false) + return fn(base_url, entries) +end + +--- 错误码 → 用户可见文案(02 A9)。调用点只问这张表,不各写一套。 +local SILENT = { + unknown_server = true, + already_cached = true, + already_queued = true, +} + +local CODE_TEXT = { + offline_not_cached = _("这一卷还没缓存,联网后可下载"), + viewer_running = _("漫画阅读器已在运行"), + no_pages = _("这一卷没有可显示的页面"), + settings_write_failed = _("无法写入 kamare 配置"), + retry_no_entry = _("没有可重试的任务"), + chapter_open = _("正在阅读这一卷,关闭后可以删除"), + unsupported = _("需要安装带缓存接口的增强版 kamare"), + base_url_required = _("无法同步配置到 kamare"), + api_key_required = _("无法同步配置到 kamare"), + delete_incomplete = _("部分缓存未能删除(权限或存储错误)"), +} + +local SPACE_CODES = { + not_enough_space = true, + cache_limit_reached = true, + low_space = true, +} + +--- 字节数 → 一行「x.x MB」;不做单位阶梯,容量判断只看数量级。 +---@param bytes any +---@return string +function Cache.sizeText(bytes) + local value = tonumber(bytes) + if not value then return _("未知") end + return T(_("%1 MB"), string.format("%.1f", value / (1024 * 1024))) +end + +--- 空间错误的 code + detail 文案。detail 由 kamare 给(不在 moon 复制阈值)。 +---@param code string +---@param detail table|nil +---@return string +local function spaceText(code, detail) + detail = type(detail) == "table" and detail or {} + if code == "not_enough_space" then + return T(_("空间不足:需要 %1,可用 %2"), Cache.sizeText(detail.needed), Cache.sizeText(detail.available)) + elseif code == "cache_limit_reached" then + return T(_("缓存空间已满:需要 %1,上限 %2"), Cache.sizeText(detail.needed), Cache.sizeText(detail.limit)) + end + return T(_("可用空间低于 %1,清理后再下载"), Cache.sizeText(detail.low_water)) +end + +--- code → 文案;静默码返回 nil。 +---@param code string|nil +---@param message string|nil kamare 的原话(未知 code 时优先) +---@param detail table|nil 空间错误的 { needed, available, used, limit, low_water } +---@return string|nil +function Cache.message(code, message, detail) + if code == nil or SILENT[code] then return nil end + if SPACE_CODES[code] then return spaceText(code, detail) end + return CODE_TEXT[code] or message or _("缓存操作失败") +end + +--- 清理计划 → 汇总。`filter` 为 "read" 时只算已读;`toc_read` 是可选的服务端进度 +--- (chapterId → pagesRead),用于补上 kamare 离线拿不到的第三源。 +---@param entries table[]|nil +---@param filter "all"|"read" +---@param toc_read table|nil +---@return { chapters: integer, bytes: integer, ids: any[], queued: integer, open: boolean } +function Cache.plan(entries, filter, toc_read) + local out = { chapters = 0, bytes = 0, ids = {}, queued = 0, open = false } + for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do + local pages = tonumber(entry.pages) or 0 + local server_read = toc_read and (tonumber(toc_read[tostring(entry.chapterId)]) or 0) or 0 + local read = entry.read == true or (pages > 0 and server_read >= pages) + if filter ~= "read" or read then + out.chapters = out.chapters + 1 + out.bytes = out.bytes + (tonumber(entry.bytes) or 0) + out.ids[#out.ids + 1] = entry.chapterId + if entry.queued then out.queued = out.queued + 1 end + if entry.open then out.open = true end + end + end + return out +end + +--- estimate 的裁决 → 确认框 / toast 文案;可下载时 nil。 +---@param result table|nil +---@return string|nil +function Cache.estimateMessage(result) + if type(result) ~= "table" or result.ok then return nil end + if result.reason == "nothing_to_do" then return _("全部已缓存或正在下载") end + if result.reason == "space" then + return T(_("空间不足:需要 %1,可用 %2"), Cache.sizeText(result.bytes), Cache.sizeText(result.available)) + end + if result.reason == "low_water" then + return T(_("可用空间不足(剩余 %1),清理后再下载"), Cache.sizeText(result.available)) + end + return nil +end + +--- 逐条 lastError 的特征 → 文案(07 A7)。moon 不加自动重试,只负责解释。 +local FAILURE_PATTERNS = { + { "http 403", _("服务器拒绝下载(403),检查 API Key / 权限") }, + { "not an archive", _("下载内容不完整或不是有效压缩包") }, + { "size ", _("下载内容不完整或不是有效压缩包") }, + { "extracted", _("下载内容不完整或不是有效压缩包") }, + { "sink write failed", _("存储空间不足或写入失败") }, + { "no space", _("存储空间不足或写入失败") }, + { "disk full", _("存储空间不足或写入失败") }, + { "socket", _("网络中断或服务器不可达") }, + { "connect", _("网络中断或服务器不可达") }, + { "closed", _("网络中断或服务器不可达") }, + { "truncated", _("网络中断或服务器不可达") }, + { "timeout", _("网络中断或服务器不可达") }, +} + +---@param last_error string|nil +---@return string|nil +function Cache.failureText(last_error) + if type(last_error) ~= "string" or last_error == "" then return nil end + local lowered = last_error:lower() + for _idx, pattern in ipairs(FAILURE_PATTERNS) do + if lowered:find(pattern[1], 1, true) then return pattern[2] end + end + return T(_("缓存失败:%1"), last_error) +end + +return Cache diff --git a/moonsource-kavita.koplugin/moonsource_kavita/cache_task.lua b/moonsource-kavita.koplugin/moonsource_kavita/cache_task.lua new file mode 100644 index 0000000..0cec422 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/cache_task.lua @@ -0,0 +1,257 @@ +--[[-- +漫画缓存的后台任务登记:把「缓存这一批卷」登记成一条 passive 后台任务。 + +kamare 仍是唯一的执行者与写入者:这里不下载、不取消队列,只按本批 chapterId 轮询 +`queue_state` / `status`,把进度报给 `workers.tasks`,让顶栏「后台任务」看得到、缓存期间不自动休眠、 +关掉卷列表后仍有完成提示。队列是全局的(按服务器过滤),所以进度只数本批自己那几卷。 + + local handle = CacheTask.track{ series = series, entries = entries } -- 入队成功后 + handle.mute(true) -- 页面自己的进度框负责提示时静音(默认不静音,由任务 toast) + handle.add(more) -- 同一部又有卷入队 / 重试失败项:并进同一条任务,终态清掉重新观察 + handle.cancel() -- 只停轮询,不动 kamare 队列(队列控制仍走 Cache.queuePause/Resume/Retry) + +@module moonsource_kavita.cache_task +--]] + +local _ = require("l10n").get("moonsource_kavita") +local T = require("ffi/util").template +local Cache = require("moonsource_kavita.cache") + +local CacheTask = {} + +--- 轮询间隔:下载中 1 秒;暂停时 5 秒(用户可能几小时不处理,别每秒读一次索引)。 +local POLL_SECONDS = 1 +local PAUSED_SECONDS = 5 +--- 连续这么多拍都看不到本批的队列项、也没落地:kamare 重启 / 队列被清,按中断收尾。 +local MAX_IDLE_TICKS = 5 + +--- 队列任务 → 本批状态与句柄;同 key 再入队时并进去。弱键:任务出队后随之回收。 +---@type table +local tracked = setmetatable({}, { __mode = "k" }) + +---@param text string|nil +local function toast(text) + if not text then return end + require("ui.themes.widgets.toast"):new{ text = text, timeout = 2 }:show() +end + +--- 队列条目按 chapterId 归一成字符串键(kamare 的键可能是数字)。 +---@param queue table|nil +---@return table +function CacheTask.queueEntries(queue) + local out = {} + for key, entry in pairs(type(queue) == "table" and queue.entries or {}) do + out[tostring(key)] = entry + end + return out +end + +---@param queue table|nil +---@return boolean +function CacheTask.queuePaused(queue) + return type(queue) == "table" and (queue.state == "paused" or queue.pause_reason ~= nil) +end + +---@param st table +local function stopTimer(st) + if st.timer then + require("ui/uimanager"):unschedule(st.timer) + st.timer = nil + end +end + +---@param st table +local function schedule(st) + if st.settled or st.timer then return end + local delay = st.paused and PAUSED_SECONDS or POLL_SECONDS + st.timer = require("ui.guard").wrap("kavita cache task poll", function() + st.timer = nil + st:poll() + end) + require("ui/uimanager"):scheduleIn(delay, st.timer) +end + +--- 本批任务的可变状态:track / 轮询 / handle 共用一份。 +---@param opts table +---@return table +local function newState(opts) + local series = type(opts.series) == "table" and opts.series or {} + local st = { + title = series.title or series.stable_id, + ids = {}, -- 顺序数组,去重 + seen = {}, -- tostring(id) -> true + landed = {}, -- tostring(id) -> 终态(已缓存或失败) + failed = {}, -- tostring(id) -> true + titles = {}, -- tostring(id) -> 卷名 + total = 0, + ok_count = 0, + idle = 0, + muted = false, + paused = false, + settled = false, + timer = nil, + report = nil, + call_done = nil, + } + + --- 并进一批卷:新 id 追加;已有的清掉终态,重试 / 重新入队后下一拍重新观察。 + ---@param entries table[] + function st:add(entries) + for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do + local id = entry.chapterId or entry.chapter_id or entry.id + if id ~= nil then + local key = tostring(id) + if not self.seen[key] then + self.seen[key] = true + self.ids[#self.ids + 1] = id + end + self.landed[key] = nil + self.failed[key] = nil + self.titles[key] = entry.title + end + end + self.total = #self.ids + self.idle = 0 + end + + --- 报表一次;没有 run 之前(还在排队)跳过。 + ---@param text string|nil + function st:emit(text) + if self.report then self.report(text, self.ok_count, self.total) end + end + + --- 收尾:只结算一次;静音时不出提示(页面自己的进度框已经报过)。 + ---@param interrupted boolean|nil + ---@return table + function st:settle(interrupted) + if self.settled then return { ok = false } end + self.settled = true + stopTimer(self) + -- 最后一卷落地的那一拍直接 settle,不会走到 poll 末尾的 emit:补报一次最终计数, + -- 否则任务卡片停在上一拍的「已完成 2/3」。 + self:emit(nil) + local failed_count = 0 + for key in pairs(self.failed) do + if self.seen[key] then failed_count = failed_count + 1 end + end + if not self.muted then + if interrupted and self.ok_count == 0 then + toast(_("缓存已中断")) + elseif failed_count == 0 then + toast(T(_("已缓存 %1 卷"), self.total)) + else + toast(T(_("%1 卷成功,%2 卷失败"), self.ok_count, failed_count)) + end + end + local result = { + ok = failed_count == 0 and not interrupted, + cached = self.ok_count, + total = self.total, + failed = failed_count, + interrupted = interrupted or nil, + } + if self.call_done then self.call_done(result) end + return result + end + + --- 每一拍:数本批的终态,报进度;全部落地就收尾。 + function st:poll() + self.timer = nil + if self.settled then return end + local queue = Cache.queueState() + local entries = CacheTask.queueEntries(queue) + local remaining, queued_any = 0, false + for _idx, id in ipairs(self.ids) do + local key = tostring(id) + if not self.landed[key] then + local queued = entries[key] + if queued and queued.state == "failed" then + self.landed[key] = true + self.failed[key] = true + elseif Cache.isCached(Cache.status(id)) then + self.landed[key] = true + else + remaining = remaining + 1 + if queued then queued_any = true end + end + end + end + local ok_count = 0 + for _idx, id in ipairs(self.ids) do + local key = tostring(id) + if self.landed[key] and not self.failed[key] then ok_count = ok_count + 1 end + end + self.ok_count = ok_count + self.paused = CacheTask.queuePaused(queue) + if remaining <= 0 then return self:settle() end + if self.paused then + self.idle = 0 + self:emit(queue and queue.pause_reason == "low_space" and _("空间不足,已暂停") or _("已暂停")) + else + local current = queue and queue.current_chapter_id + self:emit(current ~= nil and self.titles[tostring(current)] or nil) + if queued_any then + self.idle = 0 + else + -- 本批的卷既没在队列里、也没落地:kamare 重启 / 队列被清,不能永远挂着。 + self.idle = self.idle + 1 + if self.idle >= MAX_IDLE_TICKS then return self:settle(true) end + end + end + schedule(self) + end + + return st +end + +--- 登记一条 passive 任务;同一部书已有未结束的任务就并进去。 +---@param opts { series: table|nil, entries: table[], key: string|nil } +---@return table|nil handle mute(value): …; add(entries): …; cancel(): … +function CacheTask.track(opts) + opts = type(opts) == "table" and opts or {} + local entries = type(opts.entries) == "table" and opts.entries or {} + if #entries == 0 then return nil end + if not Cache.available("queue") then return nil end + local Tasks = require("workers.tasks") + local series = type(opts.series) == "table" and opts.series or {} + local key = "cache\0kavita\0" .. tostring(opts.key or series.stable_id or series.title or "series") + + local live = tracked[Tasks.get(key) or false] + if live then + live.st:add(entries) + live.st:emit(nil) + return live.handle + end + + local st = newState(opts) + st:add(entries) + local handle = {} + handle.mute = function(value) st.muted = value ~= false end + handle.add = function(more) + st:add(more) + st:emit(nil) + end + handle.cancel = function() stopTimer(st) end + + local task = { + key = key, + kind = "cache", + title = st.title, + passive = true, + -- 队列暂停(空间不足 / 等网络)时不再压自动休眠:一停几小时不能把电耗光。 + hold = function() return not st.paused end, + run = function(report, done) + st.report, st.call_done = report, done + st:emit(nil) + schedule(st) + return { cancel = function() stopTimer(st) end } + end, + } + local queued = Tasks.enqueue(task) + if not queued then return nil end + tracked[queued] = { st = st, handle = handle } + handle.task = queued + return handle +end + +return CacheTask diff --git a/moonsource-kavita.koplugin/moonsource_kavita/client.lua b/moonsource-kavita.koplugin/moonsource_kavita/client.lua new file mode 100644 index 0000000..08d2c8c --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/client.lua @@ -0,0 +1,215 @@ +--[[-- +Kavita HTTP 客户端:x-api-key 认证,只回 wire,不做领域转换。 +调用方先看 configured(),这里不再判。 + +@module moonsource_kavita.client +--]] + +local JSON = require("json") +local Request = require("http.request") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kavita") +local T = require("ffi/util").template + +--- 单次请求默认超时(秒)。全量书架(`all-v2`)在慢设备 / 慢服务器上 30s 拉不完, +--- 一个请求超时就会中断整轮同步、书架永远加载不出来,所以默认给足,并允许在设置里调大。 +local DEFAULT_TIMEOUT = 60 +--- 设置里的合法区间:太小等于次次超时,太大等于卡住没法恢复。 +local MIN_TIMEOUT = 5 +local MAX_TIMEOUT = 600 + +---@class KavitaClient +---@field base_url string +---@field api_key string +---@field timeout integer 单次请求超时秒(含下载) +local Client = {} +Client.__index = Client +Client.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT +Client.MIN_TIMEOUT = MIN_TIMEOUT +Client.MAX_TIMEOUT = MAX_TIMEOUT + +---@param cfg { base_url: string|nil, api_key: string|nil, timeout: integer|string|nil } +---@return KavitaClient +function Client.new(cfg) + local timeout = math.floor(tonumber(cfg.timeout) or DEFAULT_TIMEOUT) + if timeout < MIN_TIMEOUT then timeout = MIN_TIMEOUT end + if timeout > MAX_TIMEOUT then timeout = MAX_TIMEOUT end + return setmetatable({ + base_url = Text.rtrimSlashes(cfg.base_url), + api_key = Text.stripWhitespace(cfg.api_key), + timeout = timeout, + }, Client) +end + +---@return boolean +function Client:configured() + return self.base_url ~= "" and self.api_key ~= "" +end + +--- Kavita 按 User-Agent 识别客户端;不带时设备列表里显示 Unknown Client。 +---@return table +function Client:headers() + local device = package.loaded["device"] + local platform = type(device) == "table" and device.isAndroid and device:isAndroid() and "Android" or "Linux" + return { ["x-api-key"] = self.api_key, ["User-Agent"] = "KOReader/MoonBook (" .. platform .. ")" } +end + +--- 查询串:单值参数与 `Text.formEncode` 同形;值是数组时展开成重复键 +--- (Kavita 的 `Libraries` 过滤器要 `&Libraries=8&Libraries=10`,逗号串会被当成一个库、恒返回 0 条)。 +---@param query table +---@return string +local function queryString(query) + local keys = {} + for key in pairs(query) do keys[#keys + 1] = key end + table.sort(keys, function(a, b) return tostring(a) < tostring(b) end) + local parts = {} + for _idx, key in ipairs(keys) do + local value = query[key] + if type(value) == "table" then + for _i, item in ipairs(value) do + parts[#parts + 1] = Text.urlEncode(key) .. "=" .. Text.urlEncode(item) + end + elseif value ~= nil then + parts[#parts + 1] = Text.urlEncode(key) .. "=" .. Text.urlEncode(value) + end + end + return table.concat(parts, "&") +end + +---@param path string +---@param query table|nil +---@return string +function Client:url(path, query) + if query then return self.base_url .. path .. "?" .. queryString(query) end + return self.base_url .. path +end + +--- 原始请求:2xx 回 cb(res)(带状态码与响应头,分页接口要读 `Pagination` 头); +--- 401/403 与非 2xx 一律 cb(nil, err, code)。 +---@param method string +---@param path string +---@param query table|nil +---@param body table|nil JSON 请求体 +---@param cb fun(res: table|nil, err: string|nil, code: integer|nil) +---@return HttpJob +function Client:requestRes(method, path, query, body, cb) + local headers = self:headers() + local payload + if body then + headers["Content-Type"] = "application/json" + payload = JSON.encode(body) + end + return Request.request({ + url = self:url(path, query), method = method, headers = headers, body = payload, timeout = self.timeout, + }, function(res, err) + if err or not res then + cb(nil, err and tostring(err) or _("网络请求失败")) + return + end + local code = tonumber(res.code) + if code == 401 or code == 403 then + cb(nil, _("Kavita API Key 无效或无权限"), code) + elseif not Request.ok(code) then + cb(nil, T(_("请求失败 (HTTP %1)"), tostring(code)), code) + else + -- 只规范化 body;响应头原样带着(`Request.header` 认 Turbo 头与普通表两种)。 + cb({ code = code, headers = res.headers, body = Text.stripBom(res.body or "") }, nil, code) + end + end) +end + +--- 原始请求:2xx 回 cb(body),否则 cb(nil, err, code)。 +---@param method string +---@param path string +---@param query table|nil +---@param body table|nil JSON 请求体 +---@param cb fun(body: string|nil, err: string|nil, code: integer|nil) +---@return HttpJob +function Client:request(method, path, query, body, cb) + return self:requestRes(method, path, query, body, function(res, err, code) + cb(res and res.body, err, code) + end) +end + +--- JSON 解码:写接口成功时回空体,按 {} 交回;服务端或反代可能回 HTML 错误页, +--- 解析失败按请求失败处理,不让异常冒到回调链外。 +---@param raw string +---@return table|nil, string|nil +local function decodeJson(raw) + if Text.trim(raw) == "" then return {} end + local ok, data = pcall(JSON.decode, raw) + if ok and type(data) == "table" then return data end + return nil, _("响应不是 JSON") +end + +--- JSON 请求。 +---@param method string +---@param path string +---@param query table|nil +---@param body table|nil +---@param cb fun(data: table|nil, err: string|nil, code: integer|nil) +---@return HttpJob +function Client:json(method, path, query, body, cb) + return self:request(method, path, query, body, function(raw, err, code) + if not raw then + cb(nil, err, code) + return + end + local data, derr = decodeJson(raw) + cb(data, derr, code) + end) +end + +--- 分页接口的 JSON 请求:Kavita 把分页信息放在响应头 `Pagination` 里(不在 body), +--- 回调第四参是本页声明的总页数(缺失 / 不可信时为 nil,调用方自行兜底)。 +--- 头的内容只由 client 解释,源不必碰 `http.request`。 +---@param method string +---@param path string +---@param query table|nil +---@param body table|nil +---@param cb fun(data: table|nil, err: string|nil, code: integer|nil, pages: integer|nil) +---@return HttpJob +function Client:jsonPaged(method, path, query, body, cb) + return self:requestRes(method, path, query, body, function(res, err, code) + if not res then + cb(nil, err, code) + return + end + local data, derr = decodeJson(res.body) + cb(data, derr, code, Client.totalPages(Request.header(res, "Pagination"))) + end) +end + +--- `Pagination` 头 → 总页数:`{"currentPage":1,"itemsPerPage":200,"totalItems":316,"totalPages":2}`。 +--- 缺失 / 解析不出 / 负数一律回 nil(当分页信息不可信),调用方按「本页拉满就还有下一页」兜底。 +---@param raw string|nil +---@return integer|nil +function Client.totalPages(raw) + if type(raw) ~= "string" or raw == "" then return nil end + local ok, data = pcall(JSON.decode, raw) + if not ok or type(data) ~= "table" then return nil end + local pages = tonumber(data.totalPages) + if not pages or pages < 0 then return nil end + return math.floor(pages) +end + +--- 下载一卷原文件。Request.download 遇到非 2xx 也会落盘,这里删掉并报错。 +---@param chapter_id integer +---@param dest string +---@param on_progress fun(bytes: number, total: number|nil) +---@param cb fun(ok: boolean, err: string|nil) +---@return HttpJob +function Client:download(chapter_id, dest, on_progress, cb) + return Request.download({ + url = self:url("/api/Download/chapter", { chapterId = chapter_id }), + headers = self:headers(), timeout = self.timeout, on_progress = on_progress, + }, dest, function(ok, err, res) + if ok and not Request.ok(res and res.code) then + os.remove(dest) + ok, err = false, T(_("请求失败 (HTTP %1)"), tostring(res and res.code)) + end + cb(ok, err and tostring(err)) + end) +end + +return Client diff --git a/moonsource-kavita.koplugin/moonsource_kavita/continue_point.lua b/moonsource-kavita.koplugin/moonsource_kavita/continue_point.lua new file mode 100644 index 0000000..c782852 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/continue_point.lua @@ -0,0 +1,144 @@ +--[[-- +卷列表与系列页共用的「继续阅读」目标。 + +主线 = 最远碰过的那一卷(有进度);这一卷读完就顺延到下一卷,全读完回到第一卷(重读)。 +`updated_at` 只用来标记「上次翻阅」,不参与选卷——回头翻旧卷不会把入口拽回去 +(Kavita 的 continue-point 是「最早未读完」,正是会被回顾劫持的那种)。 + +纯函数:不读网、不读盘,进度与时间由调用方注入。 + +@module moonsource_kavita.continue_point +--]] + +local T = require("ffi/util").template +local _ = require("l10n").get("moonsource_kavita") + +local M = {} + +--- 卷名:优先 toc 的标题;没有、或退化成系列名时兜底「第 N 卷」。 +---@param entry table|nil +---@param series_title string|nil +---@return string +function M.label(entry, series_title) + local title = entry and entry.title + if type(title) ~= "string" or title == "" or title == series_title then + local n = tonumber(entry and (entry.idx or entry.number)) + return n and T(_("第 %1 卷"), n) or "?" + end + return title +end + +---@param target ContinueTarget +---@param series_title string|nil +---@return string text, string|nil caption +function M.describe(target, series_title) + local label = M.label(target.entry, series_title) + local text, caption + if target.kind == "done" then + text = T(_("重读 · %1"), label) + elseif target.kind == "fresh" then + text = T(_("开始阅读 · %1"), label) + if target.total_pages > 0 then caption = T(_("共 %1 页"), target.total_pages) end + else + text = T(_("继续阅读 · %1"), label) + if target.total_pages > 0 then + caption = T(_("第 %1/%2 页 · %3%"), target.page, target.total_pages, + math.floor(target.fraction * 100 + 0.5)) + end + end + return text, caption +end + +---@class ContinueTarget +---@field entry table 要打开的卷 +---@field kind "fresh"|"continue"|"done" +---@field fraction number 这一卷的进度 0..1 +---@field page number 已读页(用于「第 x/y 页」) +---@field total_pages number +---@field browsed table|nil 上次翻阅且不是主线的卷 + +--- 选主线。 +---@param toc table[] 卷目录(toc 顺序即阅读顺序) +---@param opts table { fraction = fun(entry):number|nil, updated_at = fun(entry):number|nil, +--- page = fun(entry):{page:number,total:number}|nil, +--- complete = fun(entry):boolean } +---@return ContinueTarget|nil +function M.pick(toc, opts) + opts = opts or {} + local entries = {} + for _i, e in ipairs(toc or {}) do + local pages = tonumber(e.pages) or 0 + if pages > 0 then + local fraction = opts.fraction and tonumber(opts.fraction(e)) + if fraction == nil then + fraction = (tonumber(e.pagesRead) or 0) / pages + end + fraction = math.max(0, math.min(1, fraction)) + -- 服务端 / 调用方说这卷已经读完:本机重新打开留下的低进度不改变「已读完」, + -- 否则回顾旧卷会把主线拖回去,列表也会出现「已读 · 1/194 页」。 + if (tonumber(e.pagesRead) or 0) >= pages + or (opts.complete and opts.complete(e)) then + fraction = 1 + end + entries[#entries + 1] = { entry = e, fraction = fraction } + end + end + if #entries == 0 then return nil end + + local last + for i, item in ipairs(entries) do + if item.fraction > 0 then last = i end + end + + local target, kind + if not last then + target, kind = entries[1], "fresh" + elseif entries[last].fraction < 1 then + target, kind = entries[last], "continue" + else + local next_item + for i = last + 1, #entries do + if entries[i].fraction < 1 then next_item = entries[i] break end + end + if next_item then + target, kind = next_item, "continue" + else + target, kind = entries[1], "done" + end + end + + local total = tonumber(target.entry.pages) or 0 + local page + if opts.page then + local got = opts.page(target.entry) + if got then + page = tonumber(got.page) + total = tonumber(got.total) or total + end + end + if not page then page = math.floor(target.fraction * total + 0.5) end + if kind == "fresh" then page = 0 end + + -- 「上次翻阅」:本机更新时间最新的一卷;和主线同一卷就不标。 + local browsed, browsed_at + if opts.updated_at then + for _i, item in ipairs(entries) do + local ts = tonumber(opts.updated_at(item.entry)) or 0 + if ts > 0 and (not browsed_at or ts > browsed_at) then + browsed, browsed_at = item, ts + end + end + end + + return { + entry = target.entry, + kind = kind, + fraction = target.fraction, + page = page, + total_pages = total, + browsed = browsed and tostring(browsed.entry.chapterId) ~= tostring(target.entry.chapterId) + and browsed.entry or nil, + } +end + +return M diff --git a/moonsource-kavita.koplugin/moonsource_kavita/kamare_update.lua b/moonsource-kavita.koplugin/moonsource_kavita/kamare_update.lua new file mode 100644 index 0000000..d39777f --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/kamare_update.lua @@ -0,0 +1,48 @@ +--[[-- +kamare 增强版在线更新:流程在 utils.plugin_update,这里只给 kamare 的目标描述。 + +版本和 digest 先问 api.ankio.net 的 GitHub 转发,挂了回落 api.github.com。 +kamare 已装就地替换,没装装进月读同级插件目录。装好立即重启:旧模块还在内存里。 + +@module moonsource_kavita.kamare_update +--]] + +local Cache = require("moonsource_kavita.cache") +local Updater = require("utils.plugin_update") +local _ = require("l10n").get("moonsource_kavita") +local T = require("ffi/util").template + +local NAME = "kamare.koplugin" + +local Update = Updater.new({ + repo = "backtracker/kamare.koplugin", + api_urls = { + "https://api.ankio.net/gh/repos/backtracker/kamare.koplugin/releases/latest", + "https://api.github.com/repos/backtracker/kamare.koplugin/releases/latest", + }, + asset = function() return "kamare.koplugin.zip" end, + archive = "kamare-update.zip", + job = "kamare.update", + installed = function() + local probe = Cache.probe() + return probe.ok and probe.version or nil + end, + name = NAME, + parent = function(plugin) return Cache.pluginsDir(plugin and plugin.path) end, + text = { + checking = _("正在检查 kamare 更新…"), + downloading = _("正在下载 kamare 更新…"), + installing = _("正在安装 kamare 更新…"), + failed = _("kamare 更新失败:%1"), + title = _("更新 kamare"), + latest = function(release) return "kamare " .. release.installed end, + header = function(release) + if release.installed then + return T(_("发现 kamare %1(当前 %2)。下载并完整替换插件目录?"), release.version, release.installed) + end + return T(_("当前未安装可用的 kamare 增强版。安装最新版 %1?"), release.version) + end, + }, +}) + +return Update diff --git a/moonsource-kavita.koplugin/moonsource_kavita/l10n/en.lua b/moonsource-kavita.koplugin/moonsource_kavita/l10n/en.lua new file mode 100644 index 0000000..14ea852 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/l10n/en.lua @@ -0,0 +1,207 @@ +return { + ["EPUB 划线同步"] = "EPUB highlight sync", + ["书架与卷目录同步(只读)"] = "Bookshelf and volume list sync (read-only)", + ["同步 Kavita 书架、电子书与漫画"] = "Sync Kavita bookshelves, ebooks and comics", + ["漫画在线阅读与缓存(需 kamare 增强版)"] = "Read and cache comics online (requires enhanced kamare)", + ["阅读历史拉取"] = "Fetch reading history", + ["下载文件校验失败"] = "Downloaded file failed verification", + ["确定退出 Kavita 账号?"] = "Sign out of Kavita?", + ["正在下载…"] = "Downloading…", + ["章节目录保存失败"] = "Failed to save chapter list", + ["请求失败 (HTTP %1)"] = "Request failed (HTTP %1)", + ["连接失败"] = "Connection failed", + ["打开漫画阅读器失败"] = "Could not open the comic viewer", + ["漫画阅读器已在运行"] = "A comic viewer is already running", + ["这一卷还没缓存,联网后可下载"] = "This volume is not cached yet; connect to download it", + ["这一卷没有可显示的页面"] = "This volume has no pages to show", + ["下一卷不在目录里"] = "The next volume is not in the table of contents", + ["无法写入 kamare 配置"] = "Could not write the kamare settings", + ["没有可重试的任务"] = "Nothing to retry", + ["正在阅读这一卷,关闭后可以删除"] = "This volume is open; close it before deleting", + ["需要安装带缓存接口的增强版 kamare"] = "Install the enhanced kamare build with the cache API", + ["无法同步配置到 kamare"] = "Could not sync settings to kamare", + ["%1 MB"] = "%1 MB", + ["空间不足:需要 %1,可用 %2"] = "Not enough space: %1 needed, %2 available", + ["缓存空间已满:需要 %1,上限 %2"] = "Cache limit reached: %1 needed, %2 limit", + ["可用空间低于 %1,清理后再下载"] = "Available space is below %1; free some space and try again", + ["缓存操作失败"] = "Cache operation failed", + ["全部已缓存或正在下载"] = "Everything is already cached or downloading", + ["可用空间不足(剩余 %1),清理后再下载"] = "Not enough free space (%1 left); free some space and try again", + ["服务器拒绝下载(403),检查 API Key / 权限"] = "Server refused the download (403); check the API key / permissions", + ["下载内容不完整或不是有效压缩包"] = "The download is incomplete or not a valid archive", + ["存储空间不足或写入失败"] = "Out of storage space or write failed", + ["网络中断或服务器不可达"] = "Network interrupted or server unreachable", + ["缓存失败:%1"] = "Cache failed: %1", + ["配置同步失败"] = "Settings sync failed", + ["增强版 v%1"] = "Enhanced v%1", + ["增强版"] = "Enhanced", + ["版本不兼容"] = "Incompatible version", + ["官方版(无缓存接口)"] = "Official build (no cache API)", + ["未安装 / 未启用"] = "Not installed / not enabled", + ["连接正常"] = "Connected", + ["Kavita %1"] = "Kavita %1", + ["未加载"] = "Not loaded", + ["获取增强版"] = "Get the enhanced build", + ["秒"] = "s", + ["检查 Kavita 服务器连接与版本"] = "Check the Kavita server connection and version", + ["kamare 增强版"] = "kamare enhanced build", + ["点按检查 kamare 增强版更新"] = "Tap to check for kamare enhanced-build updates", + ["点按安装 kamare 增强版"] = "Tap to install the kamare enhanced build", + ["点按安装兼容的 kamare 增强版"] = "Tap to install a compatible kamare enhanced build", + ["点按检查并安装 kamare 增强版"] = "Tap to check for and install the kamare enhanced build", + ["官方版"] = "Official build", + [" 也可点上方「kamare 增强版」检查并安装最新版。"] = " Or tap “kamare enhanced build” above to check for and install the latest version.", + ["正在检查 kamare 更新…"] = "Checking for kamare updates…", + ["更新 kamare"] = "Update kamare", + ["发现 kamare %1(当前 %2)。下载并完整替换插件目录?"] = "kamare %1 is available (current %2). Download and replace the plugin directory?", + ["当前未安装可用的 kamare 增强版。安装最新版 %1?"] = "No usable kamare enhanced build is installed. Install the latest version %1?", + ["正在下载 kamare 更新…"] = "Downloading the kamare update…", + ["正在安装 kamare 更新…"] = "Installing the kamare update…", + ["kamare 更新失败:%1"] = "kamare update failed: %1", + [" 发布页:github.com/backtracker/kamare.koplugin/releases/latest"] = " Releases: github.com/backtracker/kamare.koplugin/releases/latest", + [" 下载 kamare.koplugin.zip,解压后把 kamare.koplugin/ 放进:%1"] = " Download kamare.koplugin.zip, unzip it, and put kamare.koplugin/ into: %1", + [" 重启 KOReader。包里要有 kamarecache.lua(没有就是官方版);"] = " Restart KOReader. The archive must contain kamarecache.lua (otherwise it is the official build);", + [" 增强版与官方版目录同名,不能共存;替换前先删掉旧的 kamare.koplugin/。"] = " Enhanced and official share the same directory name and cannot coexist; delete the old kamare.koplugin/ before replacing it.", + [" 如该目录不可写,可改用:%1"] = " If that directory is not writable, use: %1", + ["%1 · 已缓存"] = "%1 · Cached", + ["%1 · 待同步"] = "%1 · Pending sync", + ["%1 · 离线"] = "%1 · Offline", + ["%1 卷成功,%2 卷失败"] = "%1 volumes succeeded, %2 failed", + ["%1 等 %2 卷"] = "%1 and %2 volumes", + ["下载中 %1%"] = "Downloading %1%", + ["全部已缓存"] = "Everything is cached", + ["删除「%1」的缓存?将释放 %2。"] = "Delete the cache for %1? This frees %2.", + ["删除会取消这一卷的下载。"] = "Deleting also cancels this volume's download.", + ["删除后离线不可读。"] = "It will not be readable offline after deletion.", + ["删除缓存"] = "Delete cache", + ["去清理空间"] = "Free up space", + ["另有 %1 卷失败将重试"] = "%1 failed volumes will be retried", + ["完成后剩余 %1"] = "%1 left afterwards", + ["将缓存:%1"] = "To cache: %1", + ["将重试:%1"] = "To retry: %1", + ["已排队"] = "Queued", + ["已暂停"] = "Paused", + ["已暂停整个下载队列"] = "Paused the whole download queue", + ["已暂停 %1%"] = "Paused %1%", + ["已暂停(仅 Wi-Fi 下载)"] = "Paused (Wi-Fi only)", + ["已暂停(启动恢复)"] = "Paused (restored at startup)", + ["已暂停(断网)"] = "Paused (offline)", + ["已暂停(连续下载失败)"] = "Paused (repeated download failures)", + ["已缓存 %1 卷"] = "Cached %1 volumes", + ["缓存已中断"] = "Caching was interrupted", + ["开始缓存"] = "Start caching", + ["当前下载已暂停,开始缓存会恢复整个队列"] = "Downloads are paused; starting will resume the whole queue", + ["未缓存"] = "Not cached", + ["查看失败原因"] = "View failure reasons", + ["正在缓存 %1/%2 卷"] = "Caching volume %1/%2", + ["清理后再下载"] = "Free up space before downloading", + ["空间不足"] = "Not enough space", + ["空间不足,已暂停"] = "Not enough space, paused", + ["空间不足,已暂停。清理后再下载"] = "Not enough space, paused. Free up space before downloading.", + ["缓存 %1 卷"] = "Cache %1 volumes", + ["缓存这一卷"] = "Cache this volume", + ["设备可用 %1"] = "%1 available", + ["部分失败"] = "Partly failed", + ["重试"] = "Retry", + ["重试失败项并继续"] = "Retry failures and continue", + ["重试缓存"] = "Retry cache", + ["预计占用 %1(峰值)"] = "Estimated use %1 (peak)", + ["缓存整部"] = "Cache whole series", + ["缓存未读"] = "Cache unread", + ["没有未读的卷"] = "No unread volumes", + ["缓存后 N 卷…"] = "Cache next N volumes…", + ["缓存后 N 卷"] = "Cache next N volumes", + ["卷数"] = "Volumes", + ["增强版 v%1(旧接口)"] = "Enhanced v%1 (legacy API)", + ["增强版(旧接口)"] = "Enhanced (legacy API)", + ["kamare API v%1 与当前支持的 v1 不兼容;装回支持 v1 的增强版后可管理缓存"] = "kamare API v%1 is not compatible with the supported v1; install an enhanced build that supports v1 to manage the cache", + ["版本与获取"] = "Version and getting the enhanced build", + ["正在统计…"] = "Measuring…", + ["正在清理…"] = "Cleaning up…", + ["增强版功能"] = "Enhanced features", + ["加载路径"] = "Loaded from", + ["缓存占用"] = "Cache usage", + ["已用 %1%2,可用 %3"] = "%1 used%2, %3 available", + ["(含未关联服务器)"] = " (unlinked servers included)", + ["重试同步"] = "Retry sync", + ["已重新同步配置"] = "Settings synced again", + ["服务器配置没能写入 kamare,缓存操作可能找不到服务器"] = "The server settings could not be written to kamare; cache actions may not find the server", + ["未配置服务器"] = "No server configured", + ["填写服务器地址与 API Key 后,可按服务器清理已读或全部缓存"] = "Fill in the server address and API key to clean up read or all cache per server", + ["清理已读"] = "Clean up read", + ["清理本服务器"] = "Clean up this server", + ["清理全部"] = "Clean up all", + ["清理全部缓存"] = "Clean up all cache", + ["清理本系列"] = "Clean up this series", + ["清理本系列已读"] = "Clean up read in this series", + ["没有可清理的缓存"] = "No cache to clean up", + ["没有已读完的缓存"] = "No finished cache to clean up", + ["%1 章"] = "%1 chapters", + ["%1 卷"] = "%1 volumes", + ["%1 章 · 约 %2"] = "%1 chapters · about %2", + ["含未关联服务器"] = "Includes unlinked servers", + ["含未关联服务器 · %1 章 · 约 %2"] = "Includes unlinked servers · %1 chapters · about %2", + ["将删除 %1 章已读完的缓存(约 %2)。"] = "This deletes %1 finished chapters from the cache (about %2).", + ["将删除本服务器的 %1 章(约 %2)。"] = "This deletes %1 chapters from this server (about %2).", + ["将删除所有服务器(含未关联服务器)共 %1 章(约 %2)。"] = "This deletes %1 chapters from all servers (unlinked servers included; about %2).", + ["将删除本系列 %1 卷缓存(约 %2)。"] = "This deletes the cache for %1 volumes in this series (about %2).", + ["将删除本系列 %1 卷已读完的缓存(约 %2)。"] = "This deletes the cache for %1 finished volumes in this series (about %2).", + ["会中止正在下载的 %1 章,已下载的部分会被删除。"] = "This aborts %1 downloading chapters; what was downloaded will be removed.", + ["会中止正在下载的 %1 卷,已下载的部分会被删除。"] = "This aborts %1 downloading volumes; what was downloaded will be removed.", + ["此操作不可撤销,之后阅读需要重新下载。"] = "This cannot be undone; reading again requires downloading again.", + ["阅读进度与 kamare journal 保留。"] = "Reading progress and the kamare journal are kept.", + ["已清理 %1 章,释放约 %2"] = "Cleaned %1 chapters, freeing about %2", + ["已清理 %1 章,%2 章未能删除"] = "Cleaned %1 chapters; %2 could not be deleted", + ["已清理 %1 卷,释放约 %2"] = "Cleaned %1 volumes, freeing about %2", + ["已清理 %1 卷,%2 卷未能删除"] = "Cleaned %1 volumes; %2 could not be deleted", + ["已清理全部缓存,释放约 %1"] = "Cleaned all cache, freeing about %1", + ["当前 kamare 没有清理接口"] = "This kamare build has no cleanup API", + ["升级到带 chapters / delete_all 的版本后才能清理"] = "Upgrade to a build with chapters / delete_all to clean up", + ["增强版功能随版本不同,以实际安装的版本为准。"] = "Enhanced-build features vary by version; the installed build is authoritative.", + ["漫画缓存"] = "Comic cache", + ["清理已读、按系列或全部清理"] = "Clean up read, per series, or all", + ["状态与获取增强版"] = "Status and getting the enhanced build", + ["批量操作"] = "Batch actions", + ["请先打开月读桌面"] = "Open the Moon Reader desktop first", + ["无法识别 Kavita 版本"] = "Could not identify the Kavita version", + ["Kavita %1 过旧,需要 0.9 及以上"] = "Kavita %1 is too old; 0.9 or later is required", + ["部分缓存未能删除(权限或存储错误)"] = "Some cache files could not be deleted (permission or storage error)", + ["缓存与同步"] = "Cache & sync", + ["诊断"] = "Diagnostics", + ["进度心跳间隔"] = "Progress heartbeat interval", + ["阅读时补推进度,0 关闭"] = "Push progress while reading; 0 = off", + ["请求超时"] = "Request timeout", + ["%1 · 已下载"] = "%1 · Downloaded", + ["API Key"] = "API Key", + ["Kavita"] = "Kavita", + ["Kavita API Key 无效或无权限"] = "Kavita API key is invalid or lacks permission", + ["Kavita 上没有在读的书"] = "No books in progress on Kavita", + ["Kavita 未确认注解已创建"] = "Kavita did not confirm the annotation was created", + ["Kavita 注解删除后复核失败"] = "Kavita could not verify the annotation deletion", + ["Kavita 注解删除失败"] = "Kavita annotation deletion failed", + ["Kavita 用户设置 → API Key"] = "Kavita user settings → API Key", + ["Kavita 继续阅读"] = "Continue reading on Kavita", + ["划线无法定位,本轮暂不推送:%1"] = "Highlight could not be anchored; not pushed this round: %1", + ["响应不是 JSON"] = "Response is not JSON", + ["图片目录格式需要安装 kamare 插件在线阅读"] = "Image-directory format requires the kamare plugin to read online", + ["正在拉取书架(%1 本)"] = "Fetching shelf (%1 books)", + ["正在连接 Kavita…"] = "Connecting to Kavita…", + ["联网后显示 Kavita 上在读的书"] = "Books in progress on Kavita appear when online", + ["请先在设置里填写 Kavita 服务器并选择书库"] = "Set the Kavita server and select a library in settings first", + ["请先填写服务器地址和 API Key"] = "Fill in the server address and API key first", + ["这一卷已不在 Kavita 上"] = "This volume is no longer on Kavita", + ["这本书在 Kavita 上没有可读的卷"] = "No readable volumes for this book on Kavita", + ["选择书库"] = "Select libraries", + ["进度同步"] = "Progress sync", + ["漫画缓存(需 kamare 增强版)"] = "Comic cache (needs kamare enhanced build)", + ["连接 Kavita 服务器的漫画与电子书"] = "Comics and e-books from a Kavita server", + ["第 %1 卷"] = "Vol. %1", + ["上次翻阅"] = "Last opened", + ["已读完 · 共 %1 卷"] = "Finished · %1 volumes", + ["开始阅读 · %1"] = "Start reading · %1", + ["第 %1/%2 页 · %3%"] = "Page %1/%2 · %3%", + ["继续阅读 · %1"] = "Continue reading · %1", + ["重读 · %1"] = "Read again · %1", + ["共 %1 页"] = "%1 pages total", + ["选择卷"] = "Choose a volume", +} diff --git a/moonsource-kavita.koplugin/moonsource_kavita/l10n/zh_TW.lua b/moonsource-kavita.koplugin/moonsource_kavita/l10n/zh_TW.lua new file mode 100644 index 0000000..bd16f03 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/l10n/zh_TW.lua @@ -0,0 +1,207 @@ +return { + ["EPUB 划线同步"] = "EPUB 畫線同步", + ["书架与卷目录同步(只读)"] = "書架與卷目錄同步(唯讀)", + ["同步 Kavita 书架、电子书与漫画"] = "同步 Kavita 書架、電子書與漫畫", + ["漫画在线阅读与缓存(需 kamare 增强版)"] = "漫畫線上閱讀與快取(需 kamare 增強版)", + ["阅读历史拉取"] = "取得閱讀歷史", + ["下载文件校验失败"] = "下載檔案校驗失敗", + ["确定退出 Kavita 账号?"] = "確定登出 Kavita 帳號?", + ["正在下载…"] = "正在下載…", + ["章节目录保存失败"] = "章節目錄儲存失敗", + ["请求失败 (HTTP %1)"] = "請求失敗 (HTTP %1)", + ["连接失败"] = "連接失敗", + ["打开漫画阅读器失败"] = "無法開啟漫畫閱讀器", + ["漫画阅读器已在运行"] = "漫畫閱讀器已在執行", + ["这一卷还没缓存,联网后可下载"] = "這一卷還沒快取,連網後可下載", + ["这一卷没有可显示的页面"] = "這一卷沒有可顯示的頁面", + ["下一卷不在目录里"] = "下一卷不在目錄裡", + ["无法写入 kamare 配置"] = "無法寫入 kamare 設定", + ["没有可重试的任务"] = "沒有可重試的任務", + ["正在阅读这一卷,关闭后可以删除"] = "正在閱讀這一卷,關閉後可以刪除", + ["需要安装带缓存接口的增强版 kamare"] = "需要安裝帶快取介面的增強版 kamare", + ["无法同步配置到 kamare"] = "無法同步設定到 kamare", + ["%1 MB"] = "%1 MB", + ["空间不足:需要 %1,可用 %2"] = "空間不足:需要 %1,可用 %2", + ["缓存空间已满:需要 %1,上限 %2"] = "快取空間已滿:需要 %1,上限 %2", + ["可用空间低于 %1,清理后再下载"] = "可用空間低於 %1,清理後再下載", + ["缓存操作失败"] = "快取操作失敗", + ["全部已缓存或正在下载"] = "全部已快取或正在下載", + ["可用空间不足(剩余 %1),清理后再下载"] = "可用空間不足(剩餘 %1),清理後再下載", + ["服务器拒绝下载(403),检查 API Key / 权限"] = "伺服器拒絕下載(403),檢查 API Key / 權限", + ["下载内容不完整或不是有效压缩包"] = "下載內容不完整或不是有效壓縮檔", + ["存储空间不足或写入失败"] = "儲存空間不足或寫入失敗", + ["网络中断或服务器不可达"] = "網路中斷或伺服器無法連線", + ["缓存失败:%1"] = "快取失敗:%1", + ["配置同步失败"] = "設定同步失敗", + ["增强版 v%1"] = "增強版 v%1", + ["增强版"] = "增強版", + ["版本不兼容"] = "版本不相容", + ["官方版(无缓存接口)"] = "官方版(無快取介面)", + ["未安装 / 未启用"] = "未安裝 / 未啟用", + ["连接正常"] = "連線正常", + ["Kavita %1"] = "Kavita %1", + ["未加载"] = "未載入", + ["获取增强版"] = "取得增強版", + ["秒"] = "秒", + ["检查 Kavita 服务器连接与版本"] = "檢查 Kavita 伺服器連線與版本", + ["kamare 增强版"] = "kamare 增強版", + ["点按检查 kamare 增强版更新"] = "點按檢查 kamare 增強版更新", + ["点按安装 kamare 增强版"] = "點按安裝 kamare 增強版", + ["点按安装兼容的 kamare 增强版"] = "點按安裝相容的 kamare 增強版", + ["点按检查并安装 kamare 增强版"] = "點按檢查並安裝 kamare 增強版", + ["官方版"] = "官方版", + [" 也可点上方「kamare 增强版」检查并安装最新版。"] = " 也可點上方「kamare 增強版」檢查並安裝最新版。", + ["正在检查 kamare 更新…"] = "正在檢查 kamare 更新…", + ["更新 kamare"] = "更新 kamare", + ["发现 kamare %1(当前 %2)。下载并完整替换插件目录?"] = "發現 kamare %1(目前 %2)。下載並完整取代外掛目錄?", + ["当前未安装可用的 kamare 增强版。安装最新版 %1?"] = "目前未安裝可用的 kamare 增強版。安裝最新版 %1?", + ["正在下载 kamare 更新…"] = "正在下載 kamare 更新…", + ["正在安装 kamare 更新…"] = "正在安裝 kamare 更新…", + ["kamare 更新失败:%1"] = "kamare 更新失敗:%1", + [" 发布页:github.com/backtracker/kamare.koplugin/releases/latest"] = " 發布頁:github.com/backtracker/kamare.koplugin/releases/latest", + [" 下载 kamare.koplugin.zip,解压后把 kamare.koplugin/ 放进:%1"] = " 下載 kamare.koplugin.zip,解壓後把 kamare.koplugin/ 放進:%1", + [" 重启 KOReader。包里要有 kamarecache.lua(没有就是官方版);"] = " 重新啟動 KOReader。壓縮檔裡要有 kamarecache.lua(沒有就是官方版);", + [" 增强版与官方版目录同名,不能共存;替换前先删掉旧的 kamare.koplugin/。"] = " 增強版與官方版目錄同名,不能共存;替換前先刪掉舊的 kamare.koplugin/。", + [" 如该目录不可写,可改用:%1"] = " 如該目錄不可寫,可改用:%1", + ["%1 · 已缓存"] = "%1 · 已快取", + ["%1 · 待同步"] = "%1 · 待同步", + ["%1 · 离线"] = "%1 · 離線", + ["%1 卷成功,%2 卷失败"] = "%1 卷成功,%2 卷失敗", + ["%1 等 %2 卷"] = "%1 等 %2 卷", + ["下载中 %1%"] = "下載中 %1%", + ["全部已缓存"] = "全部已快取", + ["删除「%1」的缓存?将释放 %2。"] = "刪除「%1」的快取?將釋放 %2。", + ["删除会取消这一卷的下载。"] = "刪除會取消這一卷的下載。", + ["删除后离线不可读。"] = "刪除後離線不可讀。", + ["删除缓存"] = "刪除快取", + ["去清理空间"] = "去清理空間", + ["另有 %1 卷失败将重试"] = "另有 %1 卷失敗將重試", + ["完成后剩余 %1"] = "完成後剩餘 %1", + ["将缓存:%1"] = "將快取:%1", + ["将重试:%1"] = "將重試:%1", + ["已排队"] = "已排隊", + ["已暂停"] = "已暫停", + ["已暂停整个下载队列"] = "已暫停整個下載佇列", + ["已暂停 %1%"] = "已暫停 %1%", + ["已暂停(仅 Wi-Fi 下载)"] = "已暫停(僅 Wi-Fi 下載)", + ["已暂停(启动恢复)"] = "已暫停(啟動恢復)", + ["已暂停(断网)"] = "已暫停(斷網)", + ["已暂停(连续下载失败)"] = "已暫停(連續下載失敗)", + ["已缓存 %1 卷"] = "已快取 %1 卷", + ["缓存已中断"] = "快取已中斷", + ["开始缓存"] = "開始快取", + ["当前下载已暂停,开始缓存会恢复整个队列"] = "目前下載已暫停,開始快取會恢復整個佇列", + ["未缓存"] = "未快取", + ["查看失败原因"] = "查看失敗原因", + ["正在缓存 %1/%2 卷"] = "正在快取 %1/%2 卷", + ["清理后再下载"] = "清理後再下載", + ["空间不足"] = "空間不足", + ["空间不足,已暂停"] = "空間不足,已暫停", + ["空间不足,已暂停。清理后再下载"] = "空間不足,已暫停。清理後再下載", + ["缓存 %1 卷"] = "快取 %1 卷", + ["缓存这一卷"] = "快取這一卷", + ["设备可用 %1"] = "裝置可用 %1", + ["部分失败"] = "部分失敗", + ["重试"] = "重試", + ["重试失败项并继续"] = "重試失敗項並繼續", + ["重试缓存"] = "重試快取", + ["预计占用 %1(峰值)"] = "預計佔用 %1(峰值)", + ["缓存整部"] = "快取整部", + ["缓存未读"] = "快取未讀", + ["没有未读的卷"] = "沒有未讀的卷", + ["缓存后 N 卷…"] = "快取後 N 卷…", + ["缓存后 N 卷"] = "快取後 N 卷", + ["卷数"] = "卷數", + ["增强版 v%1(旧接口)"] = "增強版 v%1(舊介面)", + ["增强版(旧接口)"] = "增強版(舊介面)", + ["kamare API v%1 与当前支持的 v1 不兼容;装回支持 v1 的增强版后可管理缓存"] = "kamare API v%1 與目前支援的 v1 不相容;裝回支援 v1 的增強版後可管理快取", + ["版本与获取"] = "版本與取得", + ["正在统计…"] = "正在統計…", + ["正在清理…"] = "正在清理…", + ["增强版功能"] = "增強版功能", + ["加载路径"] = "載入路徑", + ["缓存占用"] = "快取佔用", + ["已用 %1%2,可用 %3"] = "已用 %1%2,可用 %3", + ["(含未关联服务器)"] = "(含未關聯伺服器)", + ["重试同步"] = "重試同步", + ["已重新同步配置"] = "已重新同步設定", + ["服务器配置没能写入 kamare,缓存操作可能找不到服务器"] = "伺服器設定沒能寫入 kamare,快取操作可能找不到伺服器", + ["未配置服务器"] = "未設定伺服器", + ["填写服务器地址与 API Key 后,可按服务器清理已读或全部缓存"] = "填寫伺服器位址與 API Key 後,可按伺服器清理已讀或全部快取", + ["清理已读"] = "清理已讀", + ["清理本服务器"] = "清理本伺服器", + ["清理全部"] = "清理全部", + ["清理全部缓存"] = "清理全部快取", + ["清理本系列"] = "清理本系列", + ["清理本系列已读"] = "清理本系列已讀", + ["没有可清理的缓存"] = "沒有可清理的快取", + ["没有已读完的缓存"] = "沒有已讀完的快取", + ["%1 章"] = "%1 章", + ["%1 卷"] = "%1 卷", + ["%1 章 · 约 %2"] = "%1 章 · 約 %2", + ["含未关联服务器"] = "含未關聯伺服器", + ["含未关联服务器 · %1 章 · 约 %2"] = "含未關聯伺服器 · %1 章 · 約 %2", + ["将删除 %1 章已读完的缓存(约 %2)。"] = "將刪除 %1 章已讀完的快取(約 %2)。", + ["将删除本服务器的 %1 章(约 %2)。"] = "將刪除本伺服器的 %1 章(約 %2)。", + ["将删除所有服务器(含未关联服务器)共 %1 章(约 %2)。"] = "將刪除所有伺服器(含未關聯伺服器)共 %1 章(約 %2)。", + ["将删除本系列 %1 卷缓存(约 %2)。"] = "將刪除本系列 %1 卷快取(約 %2)。", + ["将删除本系列 %1 卷已读完的缓存(约 %2)。"] = "將刪除本系列 %1 卷已讀完的快取(約 %2)。", + ["会中止正在下载的 %1 章,已下载的部分会被删除。"] = "會中止正在下載的 %1 章,已下載的部分會被刪除。", + ["会中止正在下载的 %1 卷,已下载的部分会被删除。"] = "會中止正在下載的 %1 卷,已下載的部分會被刪除。", + ["此操作不可撤销,之后阅读需要重新下载。"] = "此操作無法復原,之後閱讀需要重新下載。", + ["阅读进度与 kamare journal 保留。"] = "閱讀進度與 kamare journal 保留。", + ["已清理 %1 章,释放约 %2"] = "已清理 %1 章,釋放約 %2", + ["已清理 %1 章,%2 章未能删除"] = "已清理 %1 章,%2 章未能刪除", + ["已清理 %1 卷,释放约 %2"] = "已清理 %1 卷,釋放約 %2", + ["已清理 %1 卷,%2 卷未能删除"] = "已清理 %1 卷,%2 卷未能刪除", + ["已清理全部缓存,释放约 %1"] = "已清理全部快取,釋放約 %1", + ["当前 kamare 没有清理接口"] = "目前 kamare 沒有清理介面", + ["升级到带 chapters / delete_all 的版本后才能清理"] = "升級到帶 chapters / delete_all 的版本後才能清理", + ["增强版功能随版本不同,以实际安装的版本为准。"] = "增強版功能隨版本不同,以實際安裝的版本為準。", + ["漫画缓存"] = "漫畫快取", + ["清理已读、按系列或全部清理"] = "清理已讀、按系列或全部清理", + ["状态与获取增强版"] = "狀態與取得增強版", + ["批量操作"] = "批次操作", + ["请先打开月读桌面"] = "請先開啟月讀桌面", + ["无法识别 Kavita 版本"] = "無法辨識 Kavita 版本", + ["Kavita %1 过旧,需要 0.9 及以上"] = "Kavita %1 過舊,需要 0.9 及以上", + ["部分缓存未能删除(权限或存储错误)"] = "部分快取未能刪除(權限或儲存錯誤)", + ["缓存与同步"] = "快取與同步", + ["诊断"] = "診斷", + ["进度心跳间隔"] = "進度心跳間隔", + ["阅读时补推进度,0 关闭"] = "閱讀時補推進度,0 關閉", + ["请求超时"] = "請求逾時", + ["%1 · 已下载"] = "%1 · 已下載", + ["API Key"] = "API Key", + ["Kavita"] = "Kavita", + ["Kavita API Key 无效或无权限"] = "Kavita API Key 無效或無權限", + ["Kavita 上没有在读的书"] = "Kavita 上沒有在讀的書", + ["Kavita 未确认注解已创建"] = "Kavita 未確認註解已建立", + ["Kavita 注解删除后复核失败"] = "Kavita 註解刪除後複核失敗", + ["Kavita 注解删除失败"] = "Kavita 註解刪除失敗", + ["Kavita 用户设置 → API Key"] = "Kavita 使用者設定 → API Key", + ["Kavita 继续阅读"] = "Kavita 繼續閱讀", + ["划线无法定位,本轮暂不推送:%1"] = "劃線無法定位,本輪暫不推送:%1", + ["响应不是 JSON"] = "回應不是 JSON", + ["图片目录格式需要安装 kamare 插件在线阅读"] = "圖片目錄格式需要安裝 kamare 外掛線上閱讀", + ["正在拉取书架(%1 本)"] = "正在拉取書架(%1 本)", + ["正在连接 Kavita…"] = "正在連線 Kavita…", + ["联网后显示 Kavita 上在读的书"] = "連網後顯示 Kavita 上在讀的書", + ["请先在设置里填写 Kavita 服务器并选择书库"] = "請先在設定裡填寫 Kavita 伺服器並選擇書庫", + ["请先填写服务器地址和 API Key"] = "請先填寫伺服器位址和 API Key", + ["这一卷已不在 Kavita 上"] = "這一卷已不在 Kavita 上", + ["这本书在 Kavita 上没有可读的卷"] = "這本書在 Kavita 上沒有可讀的卷", + ["选择书库"] = "選擇書庫", + ["进度同步"] = "進度同步", + ["漫画缓存(需 kamare 增强版)"] = "漫畫快取(需 kamare 增強版)", + ["连接 Kavita 服务器的漫画与电子书"] = "連接 Kavita 伺服器的漫畫與電子書", + ["第 %1 卷"] = "第 %1 卷", + ["上次翻阅"] = "上次翻閱", + ["已读完 · 共 %1 卷"] = "已讀完 · 共 %1 卷", + ["开始阅读 · %1"] = "開始閱讀 · %1", + ["第 %1/%2 页 · %3%"] = "第 %1/%2 頁 · %3%", + ["继续阅读 · %1"] = "繼續閱讀 · %1", + ["重读 · %1"] = "重讀 · %1", + ["共 %1 页"] = "共 %1 頁", + ["选择卷"] = "選擇卷", +} diff --git a/moonsource-kavita.koplugin/moonsource_kavita/loadmeta.lua b/moonsource-kavita.koplugin/moonsource_kavita/loadmeta.lua new file mode 100644 index 0000000..3b8cbff --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/loadmeta.lua @@ -0,0 +1,5 @@ +return function() + local copy = {} + for k, v in pairs(require("moonsource_kavita._meta")) do copy[k] = v end + return copy +end diff --git a/moonsource-kavita.koplugin/moonsource_kavita/mapper.lua b/moonsource-kavita.koplugin/moonsource_kavita/mapper.lua new file mode 100644 index 0000000..5e53543 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/mapper.lua @@ -0,0 +1,41 @@ +--[[-- +Kavita 系列书评映射;个人评价列表和章节评价不混入系列书评。 + +@module moonsource_kavita.mapper +--]] + +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kavita") + +local Mapper = {} + +---@param wire table +---@param series_id string +---@return table|nil, string|nil +function Mapper.bookReviewPage(wire, series_id) + local rows = type(wire) == "table" and wire.reviews + if type(rows) ~= "table" then return nil, _("响应无效") end + local items = {} + for _idx, row in ipairs(rows) do + if type(row) ~= "table" or type(row.body) ~= "string" + or type(row.chapterId) ~= "number" or type(row.username) ~= "string" then + return nil, _("响应无效") + end + if row.isExternal ~= true and tostring(row.seriesId) ~= series_id then + return nil, _("响应无效") + end + if row.chapterId == 0 then + local body = type(row.bodyJustText) == "string" and row.bodyJustText ~= "" + and row.bodyJustText or Text.stripHtml(row.body) + local title = type(row.tagline) == "string" and Text.trim(row.tagline) or "" + local text = title ~= "" and title .. "\n" .. body or body + if Text.trim(text) ~= "" then + items[#items + 1] = { author = row.username, text = text, time = "", + grade = tonumber(row.rating), likes = tonumber(row.totalVotes) } + end + end + end + return { items = items, total = #items, pages = 1, title = _("书评") } +end + +return Mapper diff --git a/moonsource-kavita.koplugin/moonsource_kavita/on_deck.lua b/moonsource-kavita.koplugin/moonsource_kavita/on_deck.lua new file mode 100644 index 0000000..5a9fb7f --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/on_deck.lua @@ -0,0 +1,188 @@ +--[[-- +首页组件:Kavita「继续阅读」(On Deck)。在线且已配置时拉一次,5 分钟内复用; +跟首页「最近阅读列表」同一套封面网格(CoverCell.denseCoverMetrics + Book.widget): +每页 4 本,多了分页;点开走月读开书流程(多卷 series 会先选卷)。 + +@module moonsource_kavita.on_deck +--]] + +local Base = require("desktop.pages.home.base") +local Book = require("ui.widgets.book") +local CenterContainer = require("ui/widget/container/centercontainer") +local CoverCell = require("ui.widgets.cover") +local Geom = require("ui/geometry") +local HorizontalGroup = require("ui/widget/horizontalgroup") +local HorizontalSpan = require("ui/widget/horizontalspan") +local VerticalGroup = require("ui/widget/verticalgroup") +local VerticalSpan = require("ui/widget/verticalspan") +local Pager = require("ui.themes.widgets.pager") +local Theme = require("ui.themes") +local Tap = require("ui.themes.widgets.tap") +local Text = require("ui.themes.widgets.text") +local _ = require("l10n").get("moonsource_kavita") + +local ID = "kavita" +local MAX_BOOKS = 10 +local TTL = 300 +-- 跟首页「最近阅读」一页一样:一行 4 本(封面大),多的分页。 +local COLS = 4 +local ROWS = 1 + +---@class KavitaOnDeck : BookHomeComponent +---@field job { cancel: fun() }|nil +---@field loaded_at integer|nil +---@field err string|nil +local M = { + id = "kavita.on_deck", + label = _("Kavita 继续阅读"), + icon = "collections_bookmark", +} +setmetatable(M, Base) +M.__index = M + +--- 网格尺寸:跟首页「最近阅读列表」共用 CoverCell.denseCoverMetrics,封面与槽位口径一致 +---(封面在固定宽的槽里居中,标题按槽宽居中,不会一本书看着变小/错位)。 +--- 列数固定 4(一页 4 本,封面才够大);area_h 有值时再收到放得下。 +---@param width integer +---@param area_h integer|nil 分配到的可用高度 +---@return integer slot_w +---@return integer cw +---@return integer ch +---@return integer gap +---@return integer row_gap +---@return integer cell_h +local function gridMetrics(width, area_h) + local extra = Book.captionExtra(true, false) + local max_h = CoverCell.gridCoverMaxH(area_h) + local slot_w, cw, ch, _cols, gap, row_gap, cell_h = CoverCell.denseCoverMetrics( + math.max(1, math.floor(tonumber(width) or 1)), 0, { + title_extra = extra, + max_h = max_h, + min_cols = COLS, + max_cols = COLS, + }) + if ch > max_h then + ch = max_h + cw = math.max(1, math.min(slot_w, math.floor(ch * 2 / 3))) + cell_h = ch + extra + end + area_h = math.floor(tonumber(area_h) or 0) + if area_h > 0 then + local gaps = row_gap * (ROWS - 1) + if cell_h * ROWS + gaps > area_h then + local fit_cell = math.max(1, math.floor((area_h - gaps) / ROWS)) + ch = math.max(1, math.min(ch, fit_cell - extra)) + cw = math.max(1, math.min(slot_w, math.floor(ch * 2 / 3))) + cell_h = math.min(ch + extra, fit_cell) + end + end + return slot_w, cw, ch, gap, row_gap, cell_h +end + +--- 分页条高度:On Deck 最多 10 本 > 一页 4 本,恒有分页。 +---@return integer +local function pagerHeight() + return MAX_BOOKS > COLS * ROWS and Theme.px(Theme.current().control.height) or 0 +end + +function M:heightRange(_ctx, opts) + local _slot_w, _cw, _ch, _gap, row_gap, cell_h = gridMetrics(tonumber(opts and opts.width) or 0) + return { height = cell_h * ROWS + row_gap * (ROWS - 1) + pagerHeight() } +end + +function M:onActivate() + if self.job or (self.loaded_at and os.time() - self.loaded_at < TTL) then return end + local source = require("source.registry").resolve(ID) --[[@as KavitaSource|nil]] + if not (source and source:configured() and require("ui/network/manager"):isConnected()) then return end + self.job = source.client:json("POST", "/api/Series/on-deck", { pageNumber = 1, pageSize = MAX_BOOKS }, {}, + function(list, err) + self.job = nil + self.loaded_at, self.err = os.time(), err + if list then + local books = {} + for idx, series in ipairs(list) do + local pages = tonumber(series.pages) or 0 + books[idx] = { + source_id = ID, + stable_id = tostring(series.id), + title = series.name, + percent = pages > 0 and math.min(100, (tonumber(series.pagesRead) or 0) * 100 / pages) or 0, + } + end + self.data = books + end + self:refresh() + end) +end + +function M:onDeactivate() + if self.job then + self.job:cancel() + self.job = nil + end +end + +---@param w integer +---@param h integer +---@param text string +---@return table +local function hint(w, h, text) + return CenterContainer:new{ + dimen = Geom:new{ w = w, h = h }, + Text.line("body", text, { width = w, color = Theme.current().color.muted }), + } +end + +function M:createWidget() + local ctx, w, h = self.ctx, self.opts.width, self.opts.height + local books = self.data + if not books then return hint(w, h, self.err or _("联网后显示 Kavita 上在读的书")) end + if #books == 0 then return hint(w, h, _("Kavita 上没有在读的书")) end + local page_size = COLS * ROWS + local pages = math.max(1, math.ceil(#books / page_size)) + local pager_h = pages > 1 and Theme.px(Theme.current().control.height) or 0 + local grid_h = math.max(1, h - pager_h) + local slot_w, cw, ch, gap, row_gap = gridMetrics(w, grid_h) + local page = math.max(1, math.min(self.page or 1, pages)) + self.page = page + local first = (page - 1) * page_size + 1 + local last = math.min(#books, first + page_size - 1) + local grid = VerticalGroup:new{ align = "center" } + local row, col = nil, 0 + for i = first, last do + if not row or col == COLS then + if row then grid[#grid + 1] = VerticalSpan:new{ width = row_gap } end + row, col = HorizontalGroup:new{ align = "top" }, 0 + grid[#grid + 1] = row + end + col = col + 1 + if col > 1 then row[#row + 1] = HorizontalSpan:new{ width = gap } end + local book = books[i] + -- 跟最近阅读列表同一条路:Book.widget 居中封面 + 标题,槽宽用 slot_w。 + local cell = Book.widget(ctx.plugin, nil, book, cw, ch, { + slot_w = slot_w, + badge = false, + ribbon = false, + download = false, + show_parent = ctx.desktop, + home = true, + }) + row[#row + 1] = Tap.wrap(cell, function() Base.openBook(ctx, book) end) + end + local out = VerticalGroup:new{ + align = "center", + CenterContainer:new{ dimen = Geom:new{ w = w, h = grid_h }, grid }, + } + if pages > 1 then + out[#out + 1] = Pager.widget({ + width = w, + page = page, + pages = pages, + on_prev = function() self.page = page - 1; self:refresh() end, + on_next = function() self.page = page + 1; self:refresh() end, + }) + end + return out +end + +return M diff --git a/moonsource-kavita.koplugin/moonsource_kavita/position.lua b/moonsource-kavita.koplugin/moonsource_kavita/position.lua new file mode 100644 index 0000000..6bdcdd6 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/position.lua @@ -0,0 +1,259 @@ +--[[-- +KOReader xpointer ↔ Kavita 书籍进度(pageNum + bookScrollId)。 + +Kavita 的 epub 进度以 spine 为单位:pageNum 是 0-based spine 序号(KOReader 的 +`DocFragment[D]` = spine D-1),pageNum == pages 表示读完;bookScrollId 是章内锚点, +本插件上报 `//body/...` 路径,Kavita 网页端上报 `id("X")`,后者要读本地 epub 才能还原成路径。 + +@module moonsource_kavita.position +--]] + +local Position = {} + +local VOID = { + br = true, img = true, hr = true, meta = true, link = true, input = true, + area = true, base = true, col = true, embed = true, source = true, track = true, wbr = true, +} + +--- xpointer 所在 spine(0-based)。单 spine 书 crengine 写 `DocFragment/body`(无下标)。 +---@param locator string|nil +---@return integer|nil +function Position.spine(locator) + if type(locator) ~= "string" then return nil end + local d = locator:match("DocFragment%[(%d+)%]") + if d then return tonumber(d) - 1 end + if locator:match("/DocFragment/") then return 0 end + return nil +end + +--- xpointer → `//body/...`(同名兄弟下标补全为 [1],丢弃文本偏移)。body 内无元素返回 nil。 +---@param locator string|nil +---@return string|nil +function Position.toScrollId(locator) + if type(locator) ~= "string" then return nil end + -- crengine 两种写法都有:`/body/DocFragment[N]/body/...` 与归一化的 `/body[1]/DocFragment[N]/body[1]/...`。 + local rest = locator:match("^/body%[%d+%]/DocFragment%[?%d*%]?/body%[%d+%](.*)$") + or locator:match("^/body/DocFragment%[?%d*%]?/body(.*)$") + if not rest then return nil end + local parts = {} + for seg in rest:gmatch("[^/]+") do + if not seg:match("^text%(") then + local name, index = seg:match("^([%w:_%-]+)%[(%d+)%]$") + name = name or seg:match("^([%w:_%-]+)") + if name then parts[#parts + 1] = name .. "[" .. (index or "1") .. "]" end + end + end + if #parts == 0 then return nil end + return "//body/" .. table.concat(parts, "/") +end + +--- spine + `//body/...` → xpointer。pageNum == pages(读完)落回最后一个 spine。 +---@param spine integer +---@param scroll_id string|nil +---@param pages integer spine 总数 +---@return string +function Position.toXPointer(spine, scroll_id, pages) + local n = math.max(0, math.min(spine, pages - 1)) + local tail = "" + local path = type(scroll_id) == "string" and scroll_id:match("^//body/(.+)$") + if path then + for seg in path:gmatch("[^/]+") do + -- crengine 规范:[1] 省略。 + tail = tail .. "/" .. (seg:gsub("%[1%]$", "")) + end + end + local fragment = pages == 1 and "DocFragment" or ("DocFragment[" .. (n + 1) .. "]") + return "/body/" .. fragment .. "/body" .. tail +end + +---@param base string +---@param href string +---@return string +local function joinPath(base, href) + local parts = {} + for seg in ((base ~= "" and base .. "/" or "") .. href):gmatch("[^/]+") do + if seg == ".." then + table.remove(parts) + elseif seg ~= "." then + parts[#parts + 1] = seg + end + end + return table.concat(parts, "/") +end + +--- 打开 epub 交给 fn({ count, html(spine) })。用户的 epub 什么样都有: +--- 打不开、解析抛错一律返回 nil,调用方降级(只按 spine 定位 / 不带锚点),不能让开书或同步失败。 +---@param epub_path string|nil +---@param fn fun(doc: { count: integer, html: fun(spine: integer): string|nil }): any +---@return any +local function withEpub(epub_path, fn) + if not epub_path then return nil end + local arc = require("ffi/archiver").Reader:new() + if not arc:open(epub_path) then return nil end + local ok, result = pcall(function() + -- archiver 要先扫一遍条目,extractToMemory 才找得到文件。 + for _entry in arc:iterate() do end + local opf_path = (arc:extractToMemory("META-INF/container.xml") or ""):match('full%-path="([^"]+)"') + local opf = opf_path and arc:extractToMemory(opf_path) or "" + local manifest, hrefs = {}, {} + for tag in opf:gmatch("]*>") do + local id, href = tag:match('%sid="([^"]*)"'), tag:match('%shref="([^"]*)"') + if id and href then manifest[id] = href end + end + for idref in (opf:match("]*>(.-)") or ""):gmatch('idref="([^"]*)"') do + hrefs[#hrefs + 1] = manifest[idref] + end + local base = opf_path and opf_path:match("^(.*)/") or "" + return fn({ + count = #hrefs, + html = function(spine) + local href = hrefs[spine + 1] + return href and arc:extractToMemory(joinPath(base, href)) + end, + }) + end) + arc:close() + return ok and result or nil +end + +---@class KavitaElement +---@field name string +---@field tag string 开标签原文(不含尖括号) +---@field path string 相对 body 的路径,同名兄弟下标补全:`section[1]/p[3]` +---@field text string[] 元素内(含后代)的文本片段 + +--- body 内元素按文档顺序展开,路径口径与 Kavita 的 `//body/...` 一致。 +---@param html string +---@return KavitaElement[] +local function elements(html) + local body = html:match("]*>(.-)") or html + local out, stack = {}, { { path = "", counts = {} } } + local pos = 1 + while true do + local lt = body:find("<", pos, true) + local text = body:sub(pos, (lt or 0) - 1) + if text ~= "" then + for i = 2, #stack do stack[i].text[#stack[i].text + 1] = text end + end + if not lt then break end + local gt = body:find(">", lt, true) + if not gt then break end + local tag = body:sub(lt + 1, gt - 1) + pos = gt + 1 + local close = tag:match("^/%s*([%w:_%-]+)") + local name = not close and tag:match("^([%w:_%-]+)") + if close then + for i = #stack, 2, -1 do + if stack[i].name == close then + for j = #stack, i, -1 do stack[j] = nil end + break + end + end + elseif name then + local parent = stack[#stack] + local idx = (parent.counts[name] or 0) + 1 + parent.counts[name] = idx + local el = { + name = name, tag = tag, text = {}, counts = {}, + path = (parent.path == "" and "" or parent.path .. "/") .. name .. "[" .. idx .. "]", + } + out[#out + 1] = el + if not VOID[name] and tag:sub(-1) ~= "/" then stack[#stack + 1] = el end + end + end + return out +end + +--- 远端 bookScrollId → `//body/...`。`id("X")` 需读本地 epub 第 spine 个文档定位; +--- 读不到 / 找不到返回 nil,调用方退回只按 spine 定位。 +---@param epub_path string|nil +---@param spine integer +---@param scroll_id string|nil +---@return string|nil +function Position.resolveScrollId(epub_path, spine, scroll_id) + if type(scroll_id) ~= "string" then return nil end + if scroll_id:match("^//body/") then return scroll_id end + local id = scroll_id:match('^id%("(.-)"%)$') or scroll_id:match("^id%('(.-)'%)$") + if not id or id == "" then return nil end + return withEpub(epub_path, function(doc) + for _idx, el in ipairs(elements(doc.html(spine) or "")) do + if (el.tag:match("%sid%s*=%s*\"([^\"]*)\"") or el.tag:match("%sid%s*=%s*'([^']*)'")) == id then + return "//body/" .. el.path + end + end + end) +end + +--- 段落匹配用:解实体,去脚注标记(上标数字与 [N])和全部空白。 +---@param s string|nil +---@return string +local function normalizeText(s) + s = require("utils.text").xmlDecode(s or "") + s = s:gsub("%[%d+%]", ""):gsub("\194[\185\178\179]", ""):gsub("\226\129[\176-\185]", "") + return (s:gsub("%s+", "")) +end + +--- 选中文本落在哪几段:首行定起始段(探针由长到短:整行 → 前 32 / 16 字节,容忍段内差异), +--- 末行尾部定结束段。KOReader 跨段选区按段换行,所以首末行各自落在一段里。 +---@param paras { path: string, text: string }[] +---@param head string 首行(已规范化) +---@param tail string 末行(已规范化) +---@return integer|nil first, integer|nil last +local function findRange(paras, head, tail) + local probes = { head } + if #head > 32 then probes[#probes + 1] = head:sub(1, 32) end + if #head > 16 then probes[#probes + 1] = head:sub(1, 16) end + tail = tail:sub(-math.min(24, #tail)) + for _pidx, probe in ipairs(probes) do + for i, para in ipairs(paras) do + if para.text:find(probe, 1, true) then + for j = i, #paras do + if paras[j].text:find(tail, 1, true) then return i, j end + end + return i, i + end + end + end + return nil +end + +--- KOReader 划线 → Kavita 注解锚点 { pageNumber, xPath, endingXPath }。 +--- 先在 pos0 所在 spine 找,找不到由近及远搜其它 spine;都找不到返回 nil(调用方只带 spine)。 +---@param text string|nil 划线原文 +---@param pos0 string|nil 起点 xpointer +---@param epub_path string|nil +---@return { pageNumber: integer, xPath: string, endingXPath: string }|nil +function Position.anchor(text, pos0, epub_path) + local lines = {} + for line in (text or ""):gmatch("[^\n]+") do + local clean = normalizeText(line) + if clean ~= "" then lines[#lines + 1] = clean end + end + if #table.concat(lines) < 2 then return nil end + local primary = Position.spine(pos0) or 0 + return withEpub(epub_path, function(doc) + local function try(spine) + local html = doc.html(spine) + if not html then return nil end + local paras = {} + for _idx, el in ipairs(elements(html)) do + if el.name == "p" then + paras[#paras + 1] = { path = el.path, text = normalizeText(table.concat(el.text)) } + end + end + local first, last = findRange(paras, lines[1], lines[#lines]) + return first and { + pageNumber = spine, + xPath = "//body/" .. paras[first].path, + endingXPath = "//body/" .. paras[last].path, + } + end + local hit = try(primary) + for distance = 1, doc.count do + hit = hit or try(primary - distance) or try(primary + distance) + end + return hit + end) +end + +return Position diff --git a/moonsource-kavita.koplugin/moonsource_kavita/setting.lua b/moonsource-kavita.koplugin/moonsource_kavita/setting.lua new file mode 100644 index 0000000..a3372de --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/setting.lua @@ -0,0 +1,750 @@ +--[[-- +Kavita 源设置:服务器地址、API Key、书库选择、测试连接。 +配置经月读 utils.settings.getSource / saveSource("kavita") 落盘。 + +@module moonsource_kavita.setting +--]] + +local Text = require("utils.text") +local Cache = require("moonsource_kavita.cache") +local KamareUpdate = require("moonsource_kavita.kamare_update") +local _ = require("l10n").get("moonsource_kavita") +local T = require("ffi/util").template + +local ID = "kavita" + +local Setting = {} + +---@return table +local function config() + return require("utils.settings").getSource(ID) +end + +---@param text string +---@param timeout number|nil 秒,缺省 3 +local function toast(text, timeout) + require("ui.themes.widgets.toast"):new{ text = text, timeout = timeout or 3 }:show() +end + +---@param plugin table|nil +local function repaint(plugin) + local desktop = plugin and plugin.desktop + if desktop and desktop.settings_overlay then desktop.settings_overlay:updateView() end +end + +---@param plugin table|nil +local function shelfChanged(plugin) + if plugin and plugin.desktop then plugin.desktop:onEvent("shelf_changed") end +end + +--- 服务器身份:地址 + API Key。换了就是另一套书架(seriesId 会撞)。 +local function libraryFingerprint(cfg) + return table.concat({ + Text.rtrimSlashes(Text.stripWhitespace(cfg.base_url)), + Text.stripWhitespace(cfg.api_key), + }, "\0") +end + +--- 落盘并作废源实例,让新地址 / Key / 书库立即生效。 +--- 不走 SourceChanged:那会把设置页复位到根目录;这里只重画当前叠层。 +--- 保存后把配置镜像给 kamare(02 A5 第二处);kamare 侧失败只提示,不阻断 moon 自己的保存。 +--- 换服务器 / Key:整源撕本地书架(replaceLibrary 会 reload),不再只靠下次 reconcile。 +---@param cfg table +---@param plugin table|nil +---@param refresh_shelf boolean|nil 连接配置 / 书库变了才让书架作废旧数据 +---@param previous_fingerprint string|nil 保存前的库身份;与现在不同则清书架 +local function save(cfg, plugin, refresh_shelf, previous_fingerprint) + local function commit() + require("utils.settings").saveSource(ID, cfg) + end + local replaced = previous_fingerprint and previous_fingerprint ~= libraryFingerprint(cfg) + if replaced then + if not require("source.logout").replaceLibrary(ID, commit) then + toast(_("准备本地同步失败")) + return false + end + else + commit() + require("source.registry").invalidate() + end + local configured = (cfg.base_url or "") ~= "" and (cfg.api_key or "") ~= "" + if configured and Cache.probe().ok then + local server_key, code = Cache.registerServer(cfg.base_url, cfg.api_key) + if not server_key or code then toast(_("无法同步配置到 kamare")) end + end + repaint(plugin) + if refresh_shelf and not replaced then shelfChanged(plugin) end + return true +end + +--- 未配置 / 断网当场提示;否则带忙碌提示调 fn(client, done),fn 结束时必须调 done()。 +---@param fn fun(client: KavitaClient, done: fun()) +local function withServer(fn) + local client = require("moonsource_kavita.client").new(config()) + if not client:configured() then + toast(_("请先填写服务器地址和 API Key")) + return + end + if not require("ui/network/manager"):isConnected() then + toast(_("网络不可用,请先连接 Wi-Fi")) + return + end + local busy = require("ui.themes.widgets.toast"):new{ text = _("正在连接 Kavita…"), dismissable = false } + busy:show() + fn(client, function() busy:close() end) +end + +---@param key string +---@param title string +---@param hint string +---@param password boolean +---@param normalize fun(value: string|nil): string +---@param icon string +---@return fun(iw: number): table +local function field(plugin, key, title, hint, password, normalize, icon) + return function(iw) + local value = config()[key] or "" + return require("ui.themes.widgets.row").widget({ + width = iw, chevron = true, + kind = "nav", icon = icon, title = title, + status = value ~= "" and (password and "******" or value) or _("未设置"), + status_on = value ~= "", + callback = function() + local cfg = config() + require("ui.themes.widgets.input"):new{ + title = title, + fields = { { text = cfg[key] or "", hint = hint, text_type = password and "password" or nil } }, + ok_text = _("保存"), + callback = function(input) + local before = libraryFingerprint(cfg) + local next_cfg = require("util").tableDeepCopy(cfg) + next_cfg[key] = normalize(input) + save(next_cfg, plugin, true, before) + end, + }:show() + end, + }) + end +end + +--- 多选书库:只同步选中的库,书架分类即库名。 +local function pickLibraries(plugin) + withServer(function(client, done) + client:json("GET", "/api/Library/libraries", nil, nil, function(libraries, err) + done() + if not libraries then + toast(err) + return + end + local cfg = config() + local chosen = cfg.libraries or {} + local items = {} + for _idx, lib in ipairs(libraries) do + local id = tostring(lib.id) + items[#items + 1] = { text = lib.name or id, value = id, checked = chosen[id] == true } + end + require("ui.themes.widgets.list"):new{ + title = _("选择书库"), + multi = true, + items = items, + close_callback = function() + local picked = {} + for _idx, item in ipairs(items) do + if item.checked then picked[item.value] = true end + end + cfg.libraries = picked + save(cfg, plugin, true) + end, + }:show() + end) + end) +end + +--- 请求超时(秒):全量书架(all-v2)在慢设备 / 慢服务器上一次要几十秒, +--- 硬上限会让整轮同步中断、书架永远加载不出来。留个设置行按设备调大。 +---@return fun(iw: number): table +local function timeoutRow(plugin) + return function(iw) + local client = require("moonsource_kavita.client") + local value = tonumber(config().timeout) or client.DEFAULT_TIMEOUT + return require("ui.themes.widgets.row").widget({ + width = iw, chevron = true, + kind = "nav", icon = "hourglass_top", title = _("请求超时"), + status = T(_("%1 秒"), value), + status_on = value ~= client.DEFAULT_TIMEOUT, + callback = function() + local cfg = config() + require("ui.themes.widgets.spin"):new{ + title = _("请求超时"), + fields = { { + value = tonumber(cfg.timeout) or client.DEFAULT_TIMEOUT, + min = 10, max = client.MAX_TIMEOUT, step = 10, + label = _("秒"), + } }, + callback = function(seconds) + cfg.timeout = seconds ~= client.DEFAULT_TIMEOUT and math.floor(seconds) or nil + save(cfg, plugin) + end, + }:show() + end, + }) + end +end + +--- 进度心跳间隔(秒):Kavita 的阅读会话时长 = 相邻两次进度写入的间隔,只在关书推一次会是 +--- 0 秒会话;阅读期按这个间隔补推当前位置。0 = 关闭(关书 / 切章 / 休眠的推送不受影响)。 +---@return fun(iw: number): table +local function heartbeatRow(plugin) + return function(iw) + local Source = require("moonsource_kavita.source") + local default = Source.DEFAULT_HEARTBEAT_INTERVAL + local value = tonumber(config().heartbeat_interval) or default + return require("ui.themes.widgets.row").widget({ + width = iw, chevron = true, + kind = "nav", icon = "favorite", title = _("进度心跳间隔"), + -- 行副标题是单行截断的(TextWidget 带 max_width 不换行),这行还有状态与箭头, + -- 右边留给文字的位置很窄:副标题必须短,长解释放不进来。 + subtitle = _("阅读时补推进度,0 关闭"), + status = value > 0 and T(_("%1 秒"), value) or _("已关闭"), + status_on = value > 0, + callback = function() + local cfg = config() + require("ui.themes.widgets.spin"):new{ + title = _("进度心跳间隔"), + fields = { { + value = tonumber(cfg.heartbeat_interval) or default, + min = 0, max = 600, step = 10, + label = _("秒"), + } }, + callback = function(seconds) + cfg.heartbeat_interval = seconds ~= default and math.floor(seconds) or nil + save(cfg, plugin) + end, + }:show() + end, + }) + end +end + +--- 探测结果是否带清理接口(03 A):只有能用且具备 chapters + delete 才能按章删除。 +--- 缺任一项就是「旧接口」,设置行与详情页都据此降级。 +---@param probe table +---@return boolean +local function cleanupReady(probe) + if not probe.ok then return false end + local caps = probe.capabilities or {} + return caps.chapters == true and caps.delete == true +end + +--- 五态文案(02 A8):镜像失败优先于「增强版」,其余按探测态。 +--- 增强版再分「能力齐 / 旧接口」两态(03 A 七态矩阵);旧接口不高亮。 +--- 行副标题只留结论,API 版本 / 能力清单不再展示(用户不需要,也会误导)。 +---@param probe table +---@return string, boolean +local function cacheStatus(probe) + if probe.state == "enhanced" then + if Cache.mirrorFailed() then return _("配置同步失败"), false end + local ready = cleanupReady(probe) + if probe.version then + return ready and T(_("增强版 v%1"), probe.version) + or T(_("增强版 v%1(旧接口)"), probe.version), ready + end + return ready and _("增强版") or _("增强版(旧接口)"), ready + elseif probe.state == "incompatible" then + return _("版本不兼容"), false + elseif probe.state == "official" then + return _("官方版(无缓存接口)"), false + end + return _("未安装 / 未启用"), false +end + +--- 测试连接结果:结论一行 + 明细一行或多行(Toast 用 TextBoxWidget,换行生效)。 +---@param headline string +---@param detail string|nil +---@return string +local function connectResult(headline, detail) + return detail and (headline .. "\n" .. detail) or headline +end + +local function testConnection() + withServer(function(client, done) + client:request("GET", "/api/Plugin/version", { apiKey = client.api_key }, nil, function(version, err) + done() + local major, minor = (version or ""):match("^(%d+)%.(%d+)") + if not major then + toast(connectResult(err and _("连接失败") or _("连接正常"), + err or _("无法识别 Kavita 版本"))) + elseif tonumber(major) == 0 and tonumber(minor) < 9 then + toast(connectResult(_("连接正常"), + T(_("Kavita %1 过旧,需要 0.9 及以上"), Text.trim(version)))) + else + toast(table.concat({ + _("连接正常"), + T(_("Kavita %1"), Text.trim(version)), + }, "\n")) + end + end) + end) +end + +---@param plugin table|nil +---@return fun(iw: number): table +local function libraryRow(plugin) + return function(iw) + local count = 0 + for _id in pairs(config().libraries or {}) do count = count + 1 end + return require("ui.themes.widgets.row").widget({ + width = iw, chevron = true, + kind = "nav", icon = "library_books", title = _("书库"), + status = count > 0 and T(_("%1 个"), count) or _("未选择"), + status_on = count > 0, + callback = function() pickLibraries(plugin) end, + }) + end +end + +---@return fun(iw: number): table +local function testRow() + return function(iw) + return require("ui.themes.widgets.row").widget({ + width = iw, + kind = "action", icon = "network_check", title = _("测试连接"), + subtitle = _("检查 Kavita 服务器连接与版本"), + callback = testConnection, + }) + end +end + +--- 只读占用:当前服务器。 +---@return table|nil +local function serverUsage() + if not Cache.available("summary") then return nil end + local usage = Cache.summary() + return type(usage) == "table" and usage or nil +end + +--- 只读占用:所有服务器(含未关联)。 +---@return table|nil +local function allUsage() + if not Cache.available("summary") then return nil end + local usage = Cache.summaryAll() + return type(usage) == "table" and usage or nil +end + +--- 详情页打开时的一次统计(03 E):配置了服务器时「本服务器」与「合计」各一次; +--- 没配置时两者都是合计,只走盘一次。`need_all` 由「清理全部」是否出现决定。 +---@param need_all boolean +---@return table|nil usage, table|nil all_usage +local function loadUsage(need_all) + local configured = (config().base_url or "") ~= "" + if not configured then + local all = allUsage() + return all, all + end + return serverUsage(), need_all and allUsage() or nil +end + +--- 设置行的构建函数(sections 每次重绘都按新宽度重建)。 +local function mk(opts) + return function(iw) + opts.width = iw + return require("ui.themes.widgets.row").widget(opts) + end +end + +local function installText(plugin) + local dir = require("utils.paths").userPath(Cache.pluginsDir(plugin and plugin.path)) + return table.concat({ + _("获取增强版"), + _(" 发布页:github.com/backtracker/kamare.koplugin/releases/latest"), + T(_(" 下载 kamare.koplugin.zip,解压后把 kamare.koplugin/ 放进:%1"), dir), + _(" 也可点上方「kamare 增强版」检查并安装最新版。"), + _(" 重启 KOReader。包里要有 kamarecache.lua(没有就是官方版);"), + _(" 增强版与官方版目录同名,不能共存;替换前先删掉旧的 kamare.koplugin/。"), + T(_(" 如该目录不可写,可改用:%1"), + require("utils.paths").userPath(require("datastorage"):getDataDir() .. "/plugins")), + "", + _("增强版功能随版本不同,以实际安装的版本为准。"), + }, "\n") +end + +--- 叠层的占用是打开时算的一份;清理之后只 updateView 会留着删前的数字, +--- 所以写入路径显式标记「占用过期」,下次重建先回「正在统计…」再走盘。 +local usage_stale = false + +---@param plugin table|nil +---@param reload_usage boolean|nil 写入路径传 true(删除后占用要重算) +local function refreshOverlay(plugin, reload_usage) + if reload_usage then usage_stale = true end + repaint(plugin) +end + +--- 删除后复查:请求里属于「删除前已缓存」的章如果还在,就是没删掉。 +local function leftoverCount(entries, ids) + local wanted = {} + for __, id in ipairs(ids or {}) do wanted[tostring(id)] = true end + local left = 0 + for __, entry in ipairs(type(entries) == "table" and entries or {}) do + if wanted[tostring(entry.chapterId)] then left = left + 1 end + end + return left +end + +---@param title string +---@param fn fun(): boolean|nil, string|nil, string|nil, any +---@return boolean|nil, string|nil, string|nil, any +local function runBusy(title, fn) + return require("moonsource_kavita.busy").run(title, fn) +end + +local function runCleanup(plugin, filter, title) + local entries, code = Cache.chapters() + if not entries then + toast(Cache.message(code) or _("缓存操作失败")) + return + end + local plan = Cache.plan(entries, filter) + if plan.chapters == 0 then + toast(filter == "read" and _("没有已读完的缓存") or _("没有可清理的缓存")) + return + end + local first = filter == "read" + and T(_("将删除 %1 章已读完的缓存(约 %2)。"), plan.chapters, Cache.sizeText(plan.bytes)) + or T(_("将删除本服务器的 %1 章(约 %2)。"), plan.chapters, Cache.sizeText(plan.bytes)) + local lines = { first } + if plan.queued > 0 then + lines[#lines + 1] = T(_("会中止正在下载的 %1 章,已下载的部分会被删除。"), plan.queued) + end + lines[#lines + 1] = _("阅读进度与 kamare journal 保留。") + + require("ui.themes.widgets.confirm"):new{ + title = title, + text = table.concat(lines, "\n"), + ok_text = _("清理"), + cancel_text = _("取消"), + ok_callback = function() + local ok, err, message = runBusy(title, function() return Cache.delete(plan.ids) end) + if not ok then + toast(Cache.message(err, message)) + return + end + local left = leftoverCount(Cache.chapters(), plan.ids) + if left > 0 then + toast(T(_("已清理 %1 章,%2 章未能删除"), plan.chapters - left, left), 3) + else + toast(T(_("已清理 %1 章,释放约 %2"), plan.chapters, Cache.sizeText(plan.bytes)), 3) + end + refreshOverlay(plugin, true) + shelfChanged(plugin) + end, + }:show() +end + +local function runCleanupAll(plugin) + local usage = allUsage() + local chapters = usage and tonumber(usage.chapters) or 0 + local bytes = usage and tonumber(usage.used) or 0 + require("ui.themes.widgets.confirm"):new{ + title = _("清理全部缓存"), + text = table.concat({ + T(_("将删除所有服务器(含未关联服务器)共 %1 章(约 %2)。"), + chapters, Cache.sizeText(bytes)), + _("此操作不可撤销,之后阅读需要重新下载。"), + _("阅读进度与 kamare journal 保留。"), + }, "\n"), + ok_text = _("清理"), + cancel_text = _("取消"), + ok_callback = function() + local ok, err, message, detail = runBusy(_("清理全部缓存"), + function() return Cache.deleteAll() end) + if not ok then + toast(Cache.message(err, message)) + return + end + local freed = detail and tonumber(detail.bytes) or bytes + toast(T(_("已清理全部缓存,释放约 %1"), Cache.sizeText(freed)), 3) + refreshOverlay(plugin, true) + shelfChanged(plugin) + end, + }:show() +end + +--- 详情页状态:占用走盘,先画「正在统计…」,下一拍算完再整页刷新(03 E)。 +---@class KavitaCachePageState +---@field pending boolean 占用还在统计 +---@field usage table|nil 当前服务器(未配置时是所有服务器合计) +---@field all table|nil 所有服务器合计(「清理全部」用;拿不到就是 nil) + +--- 详情页:状态 → 清理(+ 非增强态的安装说明)。 +---@param plugin table|nil +---@param state KavitaCachePageState|nil +---@return BookThemeSection[] +local function cacheSections(plugin, state) + state = state or { pending = false } + local probe = Cache.probe() + local caps = probe.capabilities or {} + local configured = (config().base_url or "") ~= "" + local can_plan = cleanupReady(probe) + local can_all = probe.ok and caps.delete_all == true + local usage = state.usage + local all_usage = state.all + local out = {} + + local version_status, version_hint + if probe.ok then + version_status, version_hint = probe.version, _("点按检查 kamare 增强版更新") + elseif probe.state == "official" then + version_status, version_hint = _("官方版"), _("点按安装 kamare 增强版") + elseif probe.state == "incompatible" then + version_status, version_hint = _("版本不兼容"), _("点按安装兼容的 kamare 增强版") + else + version_status, version_hint = _("未安装"), _("点按检查并安装 kamare 增强版") + end + local status = { + mk({ icon = "info", title = _("kamare 增强版"), + subtitle = version_hint, + status = version_status, status_on = probe.ok == true, + chevron = true, + callback = function() KamareUpdate:manualCheck(plugin) end }), + } + if probe.ok then + local features = Cache.featureText(probe) + if features then + status[#status + 1] = mk({ icon = "book", title = _("增强版功能"), + subtitle = features, chevron = false }) + end + end + status[#status + 1] = mk({ icon = "info", title = _("加载路径"), + subtitle = probe.path and require("utils.paths").userPath(probe.path) or _("未加载"), chevron = false }) + if state.pending and Cache.available("summary") then + status[#status + 1] = mk({ + icon = "storage", title = _("缓存占用"), + subtitle = _("正在统计…"), chevron = false, + }) + elseif usage then + local scope = configured and "" or _("(含未关联服务器)") + status[#status + 1] = mk({ + icon = "storage", title = _("缓存占用"), + subtitle = T(_("已用 %1%2,可用 %3"), + Cache.sizeText(usage.used), scope, Cache.sizeText(usage.available)), + status = T(_("%1 章"), tostring(usage.chapters or 0)), + status_on = true, chevron = false, + }) + end + if probe.ok and Cache.mirrorFailed() then + status[#status + 1] = mk({ + icon = "warning", title = _("配置同步失败"), + subtitle = _("服务器配置没能写入 kamare,缓存操作可能找不到服务器"), + status = _("重试同步"), chevron = false, + callback = function() + local cfg = config() + local server_key, code = Cache.registerServer(cfg.base_url, cfg.api_key) + toast(server_key and _("已重新同步配置") or Cache.message(code) or _("同步失败")) + refreshOverlay(plugin) + end, + }) + end + out[#out + 1] = { title = _("状态"), rows = status } + + --- 「清理全部」一行:跨服务器(含未关联),数字来自 summaryAll 而不是本服务器。 + --- 统计到 0 章时置灰并写「没有可清理的缓存」(03 待确认 3);还没统计完 / + --- 拿不到统计时不猜,保持可点(删除时以 kamare 的事实为准)。 + local function cleanupAllRow() + local count = all_usage and tonumber(all_usage.chapters) or nil + local empty = count ~= nil and count <= 0 + local subtitle + if empty then + subtitle = _("没有可清理的缓存") + elseif all_usage then + subtitle = T(_("含未关联服务器 · %1 章 · 约 %2"), tostring(all_usage.chapters or 0), + Cache.sizeText(all_usage.used)) + else + subtitle = _("含未关联服务器") + end + return mk({ + icon = "delete", title = _("清理全部"), + subtitle = subtitle, + enabled = not empty, + chevron = not empty, + callback = function() runCleanupAll(plugin) end, + }) + end + + if can_plan and configured then + local entries = Cache.chapters() or {} + local read_plan = Cache.plan(entries, "read") + local all_plan = Cache.plan(entries, "all") + local cleanup = { + mk({ + icon = "delete", title = _("清理已读"), + subtitle = read_plan.chapters > 0 + and T(_("%1 章 · 约 %2"), read_plan.chapters, Cache.sizeText(read_plan.bytes)) + or _("没有可清理的缓存"), + enabled = read_plan.chapters > 0, + chevron = read_plan.chapters > 0, + callback = function() runCleanup(plugin, "read", _("清理已读")) end, + }), + mk({ + icon = "delete", title = _("清理本服务器"), + subtitle = all_plan.chapters > 0 + and T(_("%1 章 · 约 %2"), all_plan.chapters, Cache.sizeText(all_plan.bytes)) + or _("没有可清理的缓存"), + enabled = all_plan.chapters > 0, + chevron = all_plan.chapters > 0, + callback = function() runCleanup(plugin, "all", _("清理本服务器")) end, + }), + } + if can_all then + cleanup[#cleanup + 1] = cleanupAllRow() + end + out[#out + 1] = { title = _("清理"), rows = cleanup } + elseif can_all and not configured then + out[#out + 1] = { title = _("清理"), rows = { + mk({ icon = "info", title = _("未配置服务器"), + subtitle = _("填写服务器地址与 API Key 后,可按服务器清理已读或全部缓存"), + chevron = false }), + cleanupAllRow(), + } } + elseif probe.ok and not can_plan then + out[#out + 1] = { title = _("清理"), rows = { + mk({ icon = "info", title = _("当前 kamare 没有清理接口"), + subtitle = _("升级到带 chapters / delete_all 的版本后才能清理"), + chevron = false }), + } } + end + + if not probe.ok then + local rows = {} + if probe.state == "incompatible" and probe.api_version then + rows[#rows + 1] = mk({ + icon = "warning", title = _("版本不兼容"), + subtitle = T(_("kamare API v%1 与当前支持的 v1 不兼容;装回支持 v1 的增强版后可管理缓存"), + tostring(probe.api_version)), + chevron = false, + }) + end + local text = installText(plugin) + rows[#rows + 1] = function(iw) return require("ui.themes.widgets.row").note(iw, text) end + out[#out + 1] = { + title = probe.state == "incompatible" and _("版本与获取") or _("获取增强版"), + rows = rows, + } + end + return out +end + +---@param plugin table|nil +local function showCachePage(plugin) + local desktop = plugin and plugin.desktop + if not desktop then + toast(_("请先打开月读桌面")) + return + end + local state = { pending = true } + local scheduled = false + require("desktop.pages.setting.overlay").push(desktop, { + title = _("漫画缓存"), + sections = function() + -- 占用走盘:先让叠层用「正在统计…」画出来,下一拍算完再刷新(03 E)。 + -- 删除后 refreshOverlay(…, true) 把占用标脏,这里重新走一遍同一条路径。 + if usage_stale then + usage_stale = false + state.pending = true + state.usage, state.all = nil, nil + end + if state.pending and not scheduled then + scheduled = true + require("ui/uimanager"):nextTick(function() + scheduled = false + local probe = Cache.probe() + local need_all = probe.ok and (probe.capabilities or {}).delete_all == true + state.usage, state.all = loadUsage(need_all) + state.pending = false + refreshOverlay(plugin) + end) + end + return cacheSections(plugin, state) + end, + }) +end + +---@param plugin table|nil +---@return fun(iw: number): table +local function cacheRow(plugin) + return function(iw) + local probe = Cache.probe() + local status, on = cacheStatus(probe) + return require("ui.themes.widgets.row").widget({ + width = iw, chevron = true, + kind = "nav", icon = "download_done", title = _("漫画缓存"), + -- 副标题只承诺真能做到的事:旧接口没有清理入口。 + subtitle = cleanupReady(probe) + and _("清理已读、按系列或全部清理") + or _("状态与获取增强版"), + status = status, status_on = on, + callback = function() showCachePage(plugin) end, + }) + end +end + +---@param value string|nil +---@return string +local function normalizeUrl(value) + return Text.rtrimSlashes(Text.stripWhitespace(value)) +end + +--- 设置页按 03 原型分三块:连接 / 缓存与同步 / 诊断。 +---@param plugin table|nil 月读插件实例(取 plugin.path 定位实际安装目录) +---@return BookThemeSection[] +function Setting.sections(plugin) + local connect = { + field(plugin, "base_url", _("服务器地址"), "https://kavita.example.com", false, normalizeUrl, "dns"), + field(plugin, "api_key", _("API Key"), _("Kavita 用户设置 → API Key"), true, Text.stripWhitespace, "key"), + libraryRow(plugin), + } + if (config().api_key or "") ~= "" then + connect[#connect + 1] = require("source.logout").row(ID, _("确定退出 Kavita 账号?"), function() + local cfg = config() + cfg.api_key = "" + require("utils.settings").saveSource(ID, cfg) + local Cache = require("moonsource_kavita.cache") + Cache.deleteAll() + Cache.reset() + end) + end + return { + { + title = _("连接"), + rows = connect, + }, + { + title = _("缓存与同步"), + rows = { cacheRow(plugin), heartbeatRow(plugin), timeoutRow(plugin) }, + }, + { + title = _("诊断"), + rows = { testRow() }, + }, + } +end + +--- 扁平行列表(兼容只认 rows 的调用方与测试);顺序与分组一致。 +---@param plugin table|nil +---@return table[] +function Setting.rows(plugin) + local rows = {} + for _idx, section in ipairs(Setting.sections(plugin)) do + for _row_idx, row in ipairs(section.rows) do rows[#rows + 1] = row end + end + return rows +end + +--- 远程管理「连接配置」网页上的表单;书库要连服务器挑,仍在设备上选。 +Setting.remote = { + { key = "base_url", label = _("服务器地址"), type = "url", placeholder = "https://kavita.example.com", + normalize = normalizeUrl }, + { key = "api_key", label = _("API Key"), secret = true, normalize = Text.stripWhitespace }, +} +Setting.replace_on_remote = { "base_url", "api_key" } + +return Setting diff --git a/moonsource-kavita.koplugin/moonsource_kavita/source.lua b/moonsource-kavita.koplugin/moonsource_kavita/source.lua new file mode 100644 index 0000000..df3e365 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/source.lua @@ -0,0 +1,2963 @@ +--[[-- +Kavita 书源(整本模式)。 + +身份: + - 书架一行 = 一个 series,stable_id = seriesId,分类 = 库名。 + - 单卷 series 直接下载到 series 行;多卷 series 打开时选卷,每卷一行隐藏的书 + (stable_id = "seriesId:chapterId",不上书架,只在最近阅读里出现),进度按卷同步。 +目录缓存(source.toc,挂在 series 行)存每卷的 chapterId/volumeId/libraryId/format/pages, +是进度上报所需 id 的唯一来源;离线时目录过期也照用旧的。 + +进度:epub 按 spine(Kavita pageNum)+ bookScrollId,pdf/cbz 按页。 +远端只有 spine 粒度(网页端没带锚点、或锚点在本机 epub 里解不出)且本地在同一 spine / 页时 +交回本地位置:Kavita 的精度只到 spine,不能拿它把本地章内位置判成冲突、把人拽回节首。 +远端能给得出页内锚点时必须用远端:网页端在同一条里往后读几页就是这种情况, +先返回本地会让 core 的 synced 基线永远判不出「云端动过」。 +关书 / 切章 / 休眠各推一次,另在阅读期做「进度心跳」(间隔见设置项 heartbeat_interval,0 可关): +Kavita 的阅读会话按相邻两次进度写入的间隔计时,只在关书推一次时长恒为 0 秒;而且它只在 +pageNum / bookScrollId 真的变了才建会话、续会话,所以心跳是「位置一变就补推」而非纯定时。 +书架:快照指纹不变就跳过对账;对账后后台逐本补简介 / 作者;漫画 series 的已读页回填成本地进度。 +统计:纯本地确认推送(Kavita 自己按会话记录),另全量拉取服务端阅读历史 → 按「身份 × 日」的行 +与替换指令写成本地统计快照;身份判定(单卷 / 多卷)与上次身份、卷名记在扩展状态文件里。 +划线:epub 的划线按段落文本在本地 epub 里找锚点,新建 / 改备注推到 Kavita,注解 id 存在笔记快照里。 +漫画:缓存判定 / 起始页 / 离线全归 kamare cache(03 A1),moon 只按返回码路由; +缓存不可用或失败时回退旧 cbz,再不行才下载 cbz 用内置阅读器。 + +@module moonsource_kavita.source +--]] + +local Client = require("moonsource_kavita.client") +local Annotation = require("moonsource_kavita.annotation") +local Position = require("moonsource_kavita.position") +local Stats = require("moonsource_kavita.stats") +local Cache = require("moonsource_kavita.cache") +local ContinuePoint = require("moonsource_kavita.continue_point") +local VolumeList = require("moonsource_kavita.volume_list") +local SourceBase = require("source.base") +local Normalize = require("book.note.normalize") +local logger = require("utils.log") +local Text = require("utils.text") +local _ = require("l10n").get("moonsource_kavita") +local T = require("ffi/util").template + +local ID = "kavita" +local PAGE_SIZE = 500 +-- 书架快照格式版本:参与指纹计算。改了写入字段(如补 series / inserted_at)时 +1, +-- 让老库下次同步重对账一次,否则只在本地存过的指纹会一直跳过。 +local SHELF_SNAPSHOT_VERSION = "v3" +local FORMATS = { [0] = "image", [1] = "cbz", [3] = "epub", [4] = "pdf" } +local MAGIC = { epub = "PK\3\4", cbz = "PK\3\4", pdf = "%PDF" } +-- 阅读历史分页大小(服务端上限实测 200)与页数上限:全量只有 2 页, +-- 上限只是分页头异常(缺失 / 乱报)时的兜底,不让拉取死循环。 +local STATS_PAGE_SIZE = 200 +local STATS_MAX_PAGES = 50 +-- 统计状态文件(与书架指纹 / 回填 done 同机制):上次身份 + 每系列章数判定 + 卷名。 +local STATS_STATE_FILE = "/moonsource_kavita_stats.lua" +-- 投影预热失败只记一行:同一进程反复同步不该刷屏(项目审计口径:不静默 pcall)。 +local shelf_prewarm_failed = false + +---@class KavitaSource : SourceBase +---@field client KavitaClient +---@field _heartbeat KavitaHeartbeat|nil 阅读期进度心跳;无则未在跑 +---@field _owner_id integer|nil 当前 Kavita 用户 id(`/api/Users/me`);nil = 没取过 / 取不到 +local Source = setmetatable({}, { __index = SourceBase }) +Source.__index = Source + +---@return BookSourceMeta +local function meta() + return require("moonsource_kavita.loadmeta")() +end + +--- 旧版本把卷行写成了书架行(deleted=0),还把整部简介 / 作者只写进部分卷行。 +--- 卷行只是进度身份,列表只该出现系列:一次性把空字段从容器补齐,再改回隐藏。 +--- 每次 new() 都会走到,状态文件里的 schema_version 保证只真正执行一次。 +local function migrateLegacyVolumes() + local state = require("luasettings"):open(require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") + if (tonumber(state:readSetting("schema_version")) or 0) >= 1 then return end + local ok, err = pcall(function() + local DB = require("utils.db") + if (tonumber(DB.rowexec("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='books';")) or 0) == 0 then + return -- 书库还没建表(新装 / 测试打桩):下次再来。 + end + -- 卷行的空作者 / 简介从容器行补:旧版本只写了其中一项,或写成空串。 + local filled = DB.exec([[ + UPDATE books SET + authors = COALESCE(NULLIF(authors, ''), ( + SELECT p.authors FROM books p + WHERE p.source_id = books.source_id + AND p.stable_id = substr(books.stable_id, 1, instr(books.stable_id, ':') - 1) + )), + intro = COALESCE(NULLIF(intro, ''), ( + SELECT p.intro FROM books p + WHERE p.source_id = books.source_id + AND p.stable_id = substr(books.stable_id, 1, instr(books.stable_id, ':') - 1) + )) + WHERE source_id = ? + AND instr(stable_id, ':') > 0 + AND (COALESCE(authors, '') = '' OR COALESCE(intro, '') = ''); + ]], ID) + if not filled then return end + -- 卷行不上书架:旧版本写成 deleted=0 的一律收回(进度 / 缓存文件保留)。 + if not DB.exec([[UPDATE books SET deleted=1, sync_status=1 + WHERE source_id=? AND deleted=0 AND instr(stable_id, ':')>0;]], ID) then + return + end + state:saveSetting("schema_version", 1) + state:flush() + end) + -- 迁移失败不能拖垮源:下次 new() 还会再试(schema_version 没落盘)。 + if not ok then require("utils.log").warn("kavita legacy volume migration failed", err) end +end + +---@return KavitaSource +local function new() + -- 换源 / 改配置经 Registry.reload() 重建实例:顺手丢掉旧服务器的书架投影(05 A1)。 + Cache.resetShelf() + local settings = require("utils.settings") + local cfg = settings.getSource(ID) + -- 「多设备统计合并」开关已删除:Kavita 的统计以云端 reading-history 为准,本机离线差额不再补。 + -- 旧版本可能已把键落盘成 true(核心只认 == true),这里清掉,避免删了开关反而锁死在开启。 + if cfg.merge_local_stats ~= nil then + cfg.merge_local_stats = nil + settings.saveSource(ID) + end + local self = setmetatable(meta(), Source) --[[@as KavitaSource]] + self.client = Client.new(cfg) + migrateLegacyVolumes() + return self +end + +function Source:configured() + return self.client:configured() +end + +--- 能力:书架 + 统计拉取(推送是纯本地确认,见 pushStatsAsync),其余走基类默认(全 false)。 +--- shelf_cache:断网时书架按适配层的缓存投影收窄可见集(05 A2)。 +--- shelf_push = false:Kavita 的书架只拉不推,推脏任务里跳过书架域(进度 / 笔记 / 统计照常)。 +---@return SourceCapabilities +function Source:capabilities() + local caps = SourceBase.capabilities(self) + caps.stats_pull = true + caps.shelf_cache = true + caps.shelf_push = false + return caps +end + +--- 书架缓存投影:同步交回适配层记忆的三张表(series_ids / mark / cover)。 +--- 未配置或 kamare 没给 index 时返回 nil;不触网,翻页复用同一份记忆(05 A1/A2)。 +---@return ShelfCacheProjection|nil +function Source:shelfCache() + if not self:configured() then return nil end + return Cache.shelf() +end + +---@return boolean +local function online() + return require("ui/network/manager"):isConnected() +end + +--- Kavita 标题:`-100000` 是「未命名」哨兵,纯数字卷名只是卷号。 +---@param value any +---@return string|nil +local function title(value) + if type(value) ~= "string" then return nil end + value = Text.trim(value) + if value == "" or value:match("^%-?%d+$") then return nil end + return value +end + +--- 卷摘要:Kavita 把它挂在章节上(`chapter.summary`),VolumeDto 没有 summary 字段。 +--- 空串 / 纯空白当作没有,好让调用方退回容器简介。 +---@param value any +---@return string|nil +local function summary(value) + if type(value) ~= "string" then return nil end + value = Text.trim(value) + return value ~= "" and value or nil +end + +--- 文件头对得上格式才算下载完整(非 2xx 的错误页、截断的文件都过不了)。 +---@param path string|nil +---@param format string|nil +---@return boolean +local function validFile(path, format) + local file = path and io.open(path, "rb") + if not file then return false end + local head = file:read(4) + file:close() + return head == MAGIC[format] +end + +---@param stable_id string +---@return string series_id, string|nil chapter_id +local function splitId(stable_id) + local series_id, chapter_id = stable_id:match("^(%d+):(%d+)$") + return series_id or stable_id, chapter_id +end + +--- 身份对应的卷:有 chapterId 按它找,没有(series 行没下载过)且只有一卷时取唯一一卷。 +---@param toc table[] +---@param chapter_id string|nil +---@return table|nil +local function findEntry(toc, chapter_id) + if not chapter_id then return #toc == 1 and toc[1] or nil end + for _idx, item in ipairs(toc) do + if tostring(item.chapterId) == chapter_id then return item end + end + return nil +end + +--- 已登记且完整的本地文件。 +---@param source_id string +---@param stable_id string +---@return string|nil +local function downloaded(source_id, stable_id) + local book = require("book.books_db").get(source_id, stable_id) + local path = book and book.path + if path and validFile(path, path:match("%.(%w+)$")) then return path end + return nil +end + +---@param metadata table Kavita SeriesMetadataDto +---@return string|nil +local function authorsOf(metadata) + local authors = {} + for _idx, writer in ipairs(metadata.writers or {}) do authors[#authors + 1] = writer.name end + return #authors > 0 and table.concat(authors, " / ") or nil +end + +--- SeriesMetadataDto 写回书库的字段(作者 / 简介 / 出版社 / 年份 / 语言)。 +--- Kavita 的未知值是空串 / 0 / 空表,入库时由 BookDB 规范化丢掉。 +---@param row table 至少带 source_id / stable_id +---@param metadata table +---@return table row +local function withMetadata(row, metadata) + local publishers = {} + for _idx, person in ipairs(metadata.publishers or {}) do publishers[#publishers + 1] = person.name end + row.authors, row.intro = authorsOf(metadata), summary(metadata.summary) + row.meta = { + publisher = table.concat(publishers, " / "), + published = metadata.releaseYear, + language = metadata.language, + } + return row +end + +--- Kwita 的 ISO 时间(不带时区)→ 按本地时钟解析成 epoch;解析不了返回 nil。 +---@param value any +---@return integer|nil +local function parseWall(value) + local y, mo, d, h, mi, s = tostring(value or ""):match("^(%d+)-(%d+)-(%d+)T(%d+):(%d+):(%d+)") + if not y or tonumber(y) < 1971 then return nil end + return os.time({ year = tonumber(y), month = tonumber(mo), day = tonumber(d), + hour = tonumber(h), min = tonumber(mi), sec = tonumber(s) }) +end + +--- 客户端时区偏移(秒):os.time 按本地解析 UTC 时钟得到的差值。 +---@return integer +local function clientOffset() + local now = os.time() + return now - os.time(os.date("!*t", now) --[[@as osdate]]) +end + +--- `xxxUtc` 字段是真的 UTC(`2026-09-29T20:07:19.193`):按本地解析后补回客户端偏移。 +---@param value any +---@return integer|nil +local function utcTime(value) + local t = parseWall(value) + if not t then return nil end + return t + clientOffset() +end + +--- 服务器时区偏移(秒):Kavita 同时给 `lastChapterAdded`(服务器本地)与 +--- `lastChapterAddedUtc`(UTC),两者差值就是服务器时区(实测服务器在 UTC+8 时为 28800)。 +---@param series table Kavita SeriesDto +---@return integer +local function serverOffset(series) + local local_t, utc_t = parseWall(series.lastChapterAdded), parseWall(series.lastChapterAddedUtc) + if not (local_t and utc_t) then return 0 end + return local_t - utc_t +end + +--- 阅读时间:`latestReadDate` 没有 Utc 后缀 —— 它是**服务器本地时间**,不是 UTC。 +--- 按 UTC 解析会存成 8 小时后的「未来」时间,刚读完的书反而被它压在下面。 +---@param series table Kavita SeriesDto +---@return integer|nil +local function readTime(series) + local t = parseWall(series.latestReadDate) + if not t then return nil end + return t - serverOffset(series) + clientOffset() +end + +--- series 的目录缓存(打开过才有)+ 其中已经在本地读过(有进度)的卷。 +--- 多卷 series 的进度分别记在各卷行上(stable_id = seriesId:chapterId): +--- 回填要跳过容器行,而读过的卷行要继承容器元数据。 +--- 目录过期也照用:卷的身份与数量不随时间变,而「只看新鲜目录」会让容器行在目录 +--- 过期后重新拿到真实时间戳、以系列封面挤进最近阅读,和卷行(扫描版封面)来回换。 +---@param source_id string +---@param series_id string +---@param ProgressDB table +---@return table[]|nil toc +---@return table[] progressed 读过的卷表项 +local function progressedVolumes(source_id, series_id, ProgressDB) + local toc = require("source.toc").read(source_id, series_id, true) + -- 单卷也要看:漫画单卷同样读在卷行上(openEntry 一律用 seriesId:chapterId), + -- 回到容器行会让同一本书在最近阅读里出现两条。 + if type(toc) ~= "table" or #toc == 0 then return nil, {} end + local out = {} + for _idx, entry in ipairs(toc) do + local chapter_id = entry.chapterId or entry.uid + if chapter_id ~= nil and ProgressDB.get(source_id, series_id .. ":" .. tostring(chapter_id)) then + out[#out + 1] = entry + end + end + return toc, out +end + +--- 容器行百分比:**卷级聚合** = (已读完卷数 + 在读卷最大 fraction) / toc 卷数。 +--- 卷行存真实位置、容器行只做聚合(06 A1)。以前容器行还有两种算法(关查看器用「本卷 fraction」、 +--- 回填用服务端 `pagesRead/pages`),同一本书在两者之间来回跳 1~N 个百分点;这里统一成一处。 +--- 目录不可得时退调用方给的 fallback(关查看器给本卷 fraction,回填给服务端比例)。 +---@param source_id string +---@param series_id string +---@param toc table[]|nil +---@param current_id string|nil 刚写过的那一卷(调用方手里有现成 fraction,不必回读库) +---@param current_fraction number|nil +--- 缺任何一卷的本地行时返回 nil:**缺行不等于未读**(只在别的设备读过、卷行是后加的 +--- 都会缺),拿 0 填会把书架百分比压到远低于真实值(实测 27 卷只认识 7 卷 → 0.13 vs 0.65)。 +---@return number|nil +local function volumeAggregate(source_id, series_id, toc, current_id, current_fraction) + if type(toc) ~= "table" or #toc == 0 then return nil end + local ProgressDB = require("book.progress_db") + local finished, best = 0, 0 + for _idx, entry in ipairs(toc) do + local id = tostring(entry.chapterId or entry.uid) + local fraction + if current_id and id == current_id then + fraction = tonumber(current_fraction) or 0 + else + local row = ProgressDB.get(source_id, series_id .. ":" .. id) + if not row then return nil end + fraction = tonumber(row.fraction) or 0 + end + if fraction >= 1 then + finished = finished + 1 + elseif fraction > best then + best = fraction + end + end + return math.min(1, (finished + best) / #toc) +end + +--- 卷行继承的元数据字段。 +local VOLUME_META_FIELDS = { "title", "authors", "intro", "category", "series" } + +--- 源这行写下去会不会真的改动库里的行。nil 字段经 COALESCE 不覆盖(同 BookDB.upsertRemote), +--- 本地脏行(sync_status=0)书库一律保留远端盖不动 —— 两种情况都不算变更。 +---@param cur Book|nil 库里的卷行 +---@param row table 待写的元数据字段 +---@return boolean +local function untouched(cur, row) + if not cur then return false end + if cur.sync_status == 0 then return true end + for _idx, field in ipairs(VOLUME_META_FIELDS) do + if row[field] ~= nil and cur[field] ~= row[field] then return false end + end + return true +end + +--- 卷行简介:这一卷的摘要(Kavita 的章节 summary)优先;没有就保留行里已有的简介 +--- (旧版目录缓存还没带上卷摘要,别把已经正确的卷简介改回整部简介),最后才退回容器简介。 +---@param volume_summary string|nil +---@param cur Book|nil 库里已有的卷行 +---@param series Book|table 容器书行 +---@return string|nil +local function volumeIntro(volume_summary, cur, series) + return summary(volume_summary) or (cur and cur.intro) or series.intro +end + +--- 卷行的元数据形状(先例 syncVolumeMeta / openBookAsync):标题「系列 · 卷名」,其余继承容器。 +--- 简介用调用方解析好的 `volumeIntro`(卷摘要 > 已有简介 > 整部简介)。 +--- 封面不写进行:卷行也由 coverRequest 取**这一卷的封面**(chapter-cover 是扫描页,不能当封面)。 +---@param series Book|table 容器书行 +---@param stable_id string "seriesId:chapterId" +---@param volume_title string|nil 卷名;拿不到时退容器名,宁可重复也不留裸 ID +---@param volume_intro string|nil 卷简介(见 volumeIntro) +---@return table +local function volumeRow(series, stable_id, volume_title, volume_intro) + return { + source_id = ID, + stable_id = stable_id, + title = T("%1 · %2", series.title or "", volume_title or series.title or ""), + authors = series.authors, + intro = summary(volume_intro) or series.intro, + category = series.category, + series = series.title, + } +end + +--- 状态文件里的卷名表(seriesId → chapterId → 卷名)规范成字符串键:dump 会把数字键写成 `[7453]`, +--- 读回来就是数字键,而条目 / 身份侧的 id 全是字符串。 +---@param raw table|nil +---@return table> +local function normalizeTitles(raw) + local out = {} + for series_key, names in pairs(type(raw) == "table" and raw or {}) do + local named = {} + if type(names) == "table" then + for chapter_key, name in pairs(names) do + if type(name) == "string" and name ~= "" then named[tostring(chapter_key)] = name end + end + end + out[tostring(series_key)] = named + end + return out +end + +--- 读过的卷行继承容器元数据(作者 / 简介 / 分类 / 系列)。 +--- 容器补全后卷行也跟着对齐(每次同步跑一遍,幂等)。只写真会改动库的行,并把改动的行数 +--- 回给调用方:对齐不算进同步变更的话,首页「当前阅读」收不到 shelf_changed, +--- 卡片会一直停在未知作者(库里其实已经补上了)。 +---@param series Book|nil 容器书行 +---@param series_id string +---@param entries table[] 读过的卷表项 +---@return integer changed 真正改动的卷行数 +local function syncVolumeMeta(series, series_id, entries) + if not series or #entries == 0 then return 0 end + local BookDB = require("book.books_db") + local rows, changed = {}, 0 + for _idx, entry in ipairs(entries) do + local stable_id = series_id .. ":" .. tostring(entry.chapterId or entry.uid) + local cur = BookDB.get(ID, stable_id) + local row = volumeRow(series, stable_id, entry.title, volumeIntro(entry.summary, cur, series)) + if cur and cur.sync_status == 0 then + -- 脏行:用户改过的非空字段保留,只把空的作者 / 简介补上。 + if BookDB.fillEmptyMeta(ID, stable_id, row.authors, row.intro) then + changed = changed + 1 + end + elseif not untouched(cur, row) then + rows[#rows + 1] = row + end + end + if #rows > 0 then require("book.store").rememberMany(rows) end + return #rows + changed +end + +--- 缺行卷物化:本次拉取里读到、但本机没有书行的卷补一条轻量身份行。 +--- 云端读过的卷可能在本机从未下载 / 打开过:没有书行,洞察「当日书单」、单书详情(补齐才进得去)、 +--- 锁屏账单就只能显示裸 ID。写入形状同卷行先例(volumeRow),书库按 upsertRemote 的默认把它落成 +--- deleted=1 + sync_status=1 的隐藏身份行:不进书架、不影响对账,也压不掉本地脏行(同 untouched)。 +--- 容器行缺失时跳过(连标题都拼不出来),统计行不受影响、照常落库。 +--- 兜底标题(容器名)只用于新行 / 本来就是兜底的旧行:既有行的真实标题(本机开过、或上一轮 +--- 用卷名物化的)不因本轮拿不到卷名而被改写。 +--- 物化只服务统计展示刷新(本次同步的 stats_changed),不回调对账、不进书架同步结果。 +---@param identities string[] 本次拉取出现的身份(单卷 = seriesId,多卷 = seriesId:chapterId) +---@param titles table> seriesId → chapterId → 卷名(身份判定时记下并持久化) +---@return integer written 真正写入的行数 +local function materializeVolumes(identities, titles) + local BookDB = require("book.books_db") + local rows = {} + for _idx, identity in ipairs(identities) do + local series_id, chapter_id = identity:match("^(%d+):(%d+)$") + local series = series_id and BookDB.get(ID, series_id) + if series then + local named = titles[series_id] + local volume_title = named and chapter_id and named[chapter_id] + local cur = BookDB.get(ID, identity) + local row = volumeRow(series, identity, volume_title, volumeIntro(nil, cur, series)) + if volume_title or not (cur and cur.title and cur.title ~= row.title) then + if not untouched(cur, row) then rows[#rows + 1] = row end + end + end + end + if #rows == 0 then return 0 end + require("book.store").rememberMany(rows) + return #rows +end + +--- 服务端已读回填成本地进度(远端版,本地脏行不覆盖),书架 /「最近阅读」/「已读」都看得到。 +--- Kavita 只在 series 级记 pagesRead/pages 与 latestReadDate: +--- - 漫画:series 级页数就是阅读页,本地同页不重写。 +--- - 书籍:series 级页数是 spine 比例,粒度太粗;只在本地还没有这本书进度时补一条占位 +--- (网页端 / 别的设备读过的书也能进「最近阅读」并标已读),绝不用它覆盖本地精确位置。 +---@param source_id string +---@param series_list table[] Kavita SeriesDto +---@return integer changed +local function backfillRead(source_id, series_list) + local ProgressDB = require("book.progress_db") + local now = os.time() + local changed = 0 + for _idx, series in ipairs(series_list) do + local pages, read = tonumber(series.pages) or 0, tonumber(series.pagesRead) or 0 + if pages > 0 and read > 0 then + local stable_id = tostring(series.id) + local comic = tonumber(series.format) == 1 + local here = ProgressDB.get(source_id, stable_id) + local at = readTime(series) + -- 旧版把 latestReadDate(服务器本地时间)当 UTC 解析,存成了 8 小时后的「未来」时间, + -- 结果刚读完的书被它挤到后面;显式拉回来(只降不升,只动干净行)。 + if here and at and (tonumber(here.updated_at) or 0) > now + 60 then + ProgressDB.fixRemoteTime(source_id, stable_id, at) + end + local toc, progressed = progressedVolumes(source_id, stable_id, ProgressDB) + if #progressed > 0 then + -- 读过的卷行继承容器元数据(作者 / 简介 / 分类),否则最近阅读里那几卷是未知作者。 + -- 对齐计入 changed:同步只会报「变了」的域,首页 / 图书馆据此重画。 + changed = changed + syncVolumeMeta( + require("book.books_db").get(source_id, stable_id), stable_id, progressed) + -- 真实位置在卷行上;容器行保留服务端 series 级聚合,并带上最近阅读时间: + -- 图书馆「最近阅读」按系列行排(点开再选卷),首页「当前阅读」仍取卷行。 + -- 不写 page:整部书的聚合进度不是「读到第几页」。 + -- 显式允许回落:旧版本存过非零 / 未来时间,MAX 会把它留住(US 24)。 + -- 卷行齐全才用卷级聚合;否则退回服务端比例(宁可两套口径,也不要低报)。 + local aggregate = volumeAggregate(source_id, stable_id, toc) + or math.min(1, read / pages) + if ProgressDB.upsertRemote(source_id, stable_id, { + fraction = aggregate, + updated_at = at or 0, + }, { reset_updated_at = true }) then + changed = changed + 1 + end + elseif comic then + -- 漫画:服务端 pageNum 是 0-based 图像序号(读完 = pages),落库的 page 是 1-based + -- (ProgressPosition 的口径),所以 +1;fraction 与 page 同口径,避免同一行自相矛盾。 + -- 只前进不后退:本机回退后的位置不被服务端旧值拉回去(回退由 kamare 的 base 判定处理)。 + local page = math.min(read + 1, pages) + if not here or (tonumber(here.page) or 0) < page then + if ProgressDB.upsertRemote(source_id, stable_id, { + fraction = page / pages, + page = page, + total_pages = pages, + updated_at = at, + }) then + changed = changed + 1 + end + end + elseif here == nil then + -- epub:series 级 pagesRead/pages 是 spine 比例,只给没有本机进度的书补占位。 + if ProgressDB.upsertRemote(source_id, stable_id, { + fraction = math.min(1, read / pages), + updated_at = at, + }) then + changed = changed + 1 + end + end + end + end + return changed +end + +--- 同步时最多问几部「当前读到哪一卷」:首页「当前阅读」只取最近一部,留几部余量。 +local CURRENT_VOLUME_LIMIT = 3 + +--- 服务端「当前读到哪一卷」:all-v2 只有 series 级聚合(pagesRead / latestReadDate), +--- 另一台设备读的卷在本机没有任何卷行,首页「当前阅读」只能退到系列行或本机残留的旧卷。 +--- Kavita 的 continue-point 一次给一章(volumeId / pagesRead / 最后阅读时间),响应只有几 KB, +--- 所以只问最近在读的几部漫画,不为整架书发请求。 +---@param source KavitaSource 源实例(要 client / id) +---@param series_list table[] Kavita SeriesDto(本次同步里 pagesRead > 0 的那些) +---@param cb fun(changed: integer) 候选跑完(可能 0 个)后回调 +---@return { cancel: fun() } +local function backfillCurrentVolume(source, series_list, cb) + local targets = {} + for _idx, series in ipairs(series_list) do + local pages, read = tonumber(series.pages) or 0, tonumber(series.pagesRead) or 0 + -- 只处理漫画:epub 的进度本来就记在系列行上;读完 / 没读过的不需要「当前卷」。 + if tonumber(series.format) == 1 and pages > 0 and read > 0 and read < pages then + targets[#targets + 1] = { id = tostring(series.id), at = readTime(series) or 0 } + end + end + table.sort(targets, function(a, b) + if a.at ~= b.at then return a.at > b.at end + return a.id < b.id + end) + local limit = math.min(#targets, CURRENT_VOLUME_LIMIT) + local index, changed, cancelled, job = 0, 0, false, nil + + --- 服务端说在读的这一章 → 本地卷行。没有卷行就补一条;本机已有且服务器没更新的不重写 + --- (每次同步重写同一行会白白触发首页重画),但卷摘要 / 卷名这类元数据仍会对齐 + --- (旧版本写下的卷行带着整部简介,靠这一步纠正成这一卷的摘要)。 + ---@param target table 候选(id / at) + ---@param chapter table Kavita ChapterDto + ---@return integer 变更数 + local function write(target, chapter) + local pages = tonumber(chapter.pages) or 0 + local read = tonumber(chapter.pagesRead) or 0 + local chapter_id = chapter.id or chapter.chapterId + -- 读完一卷后 continue-point 给的是「下一章」(pagesRead = 0):那不是正在读。 + if not chapter_id or pages <= 0 or read <= 0 or read >= pages then return 0 end + local stable_id = target.id .. ":" .. tostring(chapter_id) + local BookDB = require("book.books_db") + local container = BookDB.get(source.id, target.id) + if not container then return 0 end + local ProgressDB = require("book.progress_db") + local at = utcTime(chapter.lastReadingProgressUtc) or target.at or 0 + local changed = 0 + local cur = BookDB.get(source.id, stable_id) + local row = volumeRow(container, stable_id, + title(chapter.titleName) or title(chapter.title) or title(chapter.volumeTitle), + volumeIntro(chapter.summary, cur, container)) + if not untouched(cur, row) then + require("book.store").rememberMany({ row }) + changed = changed + 1 + end + local here = ProgressDB.get(source.id, stable_id) + -- 服务端 pageNum 是 0-based 图像序号,本地 page 是 1-based:+1 后再比。 + local page = math.min(read + 1, pages) + -- 只前进:服务端更靠后才采纳,**不比时间戳**。`at` 是服务器时间、`here.updated_at` 是本机 + -- 时钟,跨设备时钟偏差会让「明显更新」永久不成立(旧实现正是拿 `at > updated_at + 60` 卡的)。 + -- 本机允许回退(kamare 的 base 判定),这种行不能被服务端旧值拉回去。 + if here and (tonumber(here.page) or 0) >= page then return changed end + if not ProgressDB.upsertRemote(source.id, stable_id, { + fraction = page / pages, + page = page, + total_pages = pages, + updated_at = (tonumber(at) or 0) > 0 and at or os.time(), + }) then return changed end + return changed + 1 + end + + local function step() + if cancelled then return end + index = index + 1 + if index > limit then return cb(changed) end + local target = targets[index] + job = source.client:json("GET", "/api/Reader/continue-point", { seriesId = target.id }, nil, + function(chapter) + if cancelled then return end + if chapter then changed = changed + write(target, chapter) end + step() + end) + end + if online() then step() else cb(0) end + return { cancel = function() + cancelled = true + if job and job.cancel then job:cancel() end + end } +end + +--- 补全状态 TTL:缺数据的行到期重试,完整行永久跳过。 +local META_TTL = 7 * 86400 +--- 单轮补全的时间预算:到点停,下次同步靠 checked_at 接着补。 +local META_BUDGET = 60 +--- 每处理多少本落一次状态:进程被杀也不丢整轮进度。 +local META_FLUSH_EVERY = 20 +--- 补全期间首页刷新的节流间隔。 +local META_NOTIFY_EVERY = 10 + +--- 字段是否有内容:空串 / 纯空白都算缺。 +---@param value any +---@return boolean +local function filled(value) + return type(value) == "string" and value:match("%S") ~= nil +end + +--- 系列行是否完整:简介与作者都有值。完整性每轮从行实时判断, +--- 不把 complete 落进状态文件(那会变成第二个「终身判据」)。 +---@param book table|nil +---@return boolean +local function complete(book) + return book ~= nil and filled(book.intro) and filled(book.authors) +end + +--- 后台逐本补简介 / 作者(all-v2 不带,metadata 一本一请求)。 +--- 完整行永久跳过;缺数据的行按 `checked_at + TTL` 重试。状态记在 +--- settings/moonsource_kavita_meta.lua,顶层按 base_url 分区:换服务器不继承旧标记。 +--- 单本失败跳过(不推进 checked_at),连续失败才当网络问题整轮收工。 +---@param series_ids string[] +---@param opts { force?: boolean, on_changed?: fun() }|nil force 忽略 TTL;on_changed 有写入时通知 UI +function Source:backfillMeta(series_ids, opts) + opts = opts or {} + if self.backfill then self.backfill.cancel() end + local BookDB = require("book.books_db") + local UIManager = require("ui/uimanager") + local state = require("luasettings"):open(require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") + -- 换服务器 / 换回旧服务器都不继承旧标记:同一个 seriesId 在另一台服务器上可能是别的书。 + local server = self.client.base_url + if state:readSetting("server") ~= server then + state:saveSetting("server", server) + state:saveSetting("done", {}) + end + local stored = state:readSetting("done", {}) + if type(stored) ~= "table" then stored = {} end + -- 书架 id 里混着卷行(seriesId:chapterId,快照没变时 syncBooksAsync 直接取全量书架 id): + -- 卷行不补 series 级元数据,拿它请求 /Series/metadata 会被 Kavita 判 400。 + local ids = {} + for _idx, id in ipairs(series_ids) do + local key = tostring(id) + if not key:find(":", 1, true) then ids[#ids + 1] = key end + end + local done = {} + if #ids > 0 then + -- 只保留本轮书架里的 series:系列删除 / 取消勾选库后状态不会无限增长。 + local keep = {} + for _idx, id in ipairs(ids) do keep[id] = true end + for id, value in pairs(stored) do + -- 旧版本的布尔 true 当作「很久以前检查过」:完整行照样跳过,缺数据行补一次。 + local key = tostring(id) + if keep[key] then done[key] = type(value) == "number" and value or 0 end + end + else + -- 空书架(接口抖动 / 还没拉到)不能当成「全部消失」。 + for id, value in pairs(stored) do + done[tostring(id)] = type(value) == "number" and value or 0 + end + end + state:saveSetting("done", done) + + local started, index, fails, cancelled, job, timer, guarded_step = os.time(), 0, 0, false, nil, nil, nil + local writes, last_notify, notify_pending = 0, nil, false + + local function notify() + if not opts.on_changed then return end + local now = os.time() + if last_notify and now - last_notify < META_NOTIFY_EVERY then return end + last_notify, notify_pending = now, false + opts.on_changed() + end + + local function stop() + self.backfill = nil + state:flush() + -- 收工补发:节流窗口内攒下的写入也要让首页看到。 + if notify_pending and opts.on_changed then + notify_pending = false + opts.on_changed() + end + end + + --- 这一行要不要跳过:不存在 / 已完整 / TTL 内检查过都跳过。 + local function settled(series_id, book) + if not book or complete(book) then return true end + if opts.force then return false end + local checked = done[tostring(series_id)] + if type(checked) ~= "number" then return false end + local age = os.time() - checked + -- 未来时间(时钟回拨)当成已过期,别把行永久锁住。 + return age >= 0 and age < META_TTL + end + + local function step() + local series_id, book + repeat + index = index + 1 + series_id = ids[index] + book = series_id and BookDB.get(self.id, series_id) + until not series_id or not settled(series_id, book) + if not series_id or not online() then return stop() end + if os.time() - started >= META_BUDGET then return stop() end + job = self.client:json("GET", "/api/Series/metadata", { seriesId = series_id }, nil, function(metadata) + if cancelled then return end + if type(metadata) ~= "table" then + -- 单本失败不拖住后面:不推进 checked_at,下次同步接着补。 + fails = fails + 1 + if fails >= 3 then return stop() end + timer = guarded_step + UIManager:scheduleIn(0.3, timer) + return + end + fails = 0 + local updated = withMetadata({ source_id = self.id, stable_id = tostring(series_id) }, metadata) + require("book.store").rememberMany({ updated }) + -- 脏行(用户编辑过)书库不覆盖;空字段仍从服务端补上,别让「未知作者」永远留着。 + if book and book.sync_status == 0 then + BookDB.fillEmptyMeta(self.id, tostring(series_id), updated.authors, updated.intro) + end + -- 空 DTO 也算「检查过」:服务端这次没给,TTL 后再看。 + done[tostring(series_id)] = os.time() + writes = writes + 1 + notify_pending = true + if writes % META_FLUSH_EVERY == 0 then state:flush() end + notify() + timer = guarded_step + UIManager:scheduleIn(0.3, timer) + end) + end + guarded_step = require("ui.guard").wrap("kavita backfill meta", step) + + self.backfill = { cancel = function() + cancelled = true + if job then job:cancel() end + if timer then UIManager:unschedule(timer) end + stop() + end } + step() +end + +--- 详情页缺简介时补:series 的 metadata 写回这一行(卷行用所属 series 的)。 +---@param identity BookIdentity +---@param cb fun(book: Book|nil, err: string|nil) +---@return { cancel: fun() } +function Source:getDetailAsync(identity, cb) + local series_id, chapter_id = splitId(identity.stable_id) + local job, cancelled = nil, false + local function finish(book, err) + if cancelled then return end + cb(book, err) + end + + --- 卷简介:目录里的章节摘要 > 行里已有的卷简介 > 单章接口 > 整部简介。 + --- 行里的简介如果与整部简介相同,说明是旧版本回退写下的,不算「已有卷摘要」。 + local function detail(metadata) + local book = withMetadata({ source_id = self.id, stable_id = identity.stable_id }, metadata) + if not chapter_id then + require("book.store").rememberMany({ book }) + return finish(book) + end + local series_intro = summary(metadata.summary) + local here = require("book.books_db").get(self.id, identity.stable_id) + local here_intro = here and summary(here.intro) + local toc = require("source.toc").read(self.id, series_id, true) + local entry = toc and findEntry(toc, chapter_id) + local known = summary(entry and entry.summary) + or (here_intro and here_intro ~= series_intro and here_intro) + local function store(intro) + book.intro = intro + require("book.store").rememberMany({ book }) + finish(book) + end + if known then return store(known) end + -- 旧目录缓存没带卷摘要(升级前拉的目录):单章接口只有几 KB,补一次。 + job = self.client:json("GET", "/api/Series/chapter", { chapterId = chapter_id }, nil, + function(chapter) + store(summary(chapter and chapter.summary) or here_intro or book.intro) + end) + end + + job = self.client:json("GET", "/api/Series/metadata", { seriesId = series_id }, nil, + function(metadata, err) + if not metadata then return finish(nil, err) end + detail(metadata) + end) + return { cancel = function() + cancelled = true + if job and job.cancel then job:cancel() end + end } +end + +--- Kavita 的阅读会话时长 = 相邻两次进度写入的时间跨度(10 分钟无写入即封会话)。 +--- 月读只在关书 / 切章 / 休眠各推一次,单次写入在 Kavita 侧就是 StartTime == EndTime 的 +--- 「0 秒会话」(字数也会被 Kavita 的锚点 diff 误算成到页尾的一大段)。阅读期补推当前位置, +--- 一个阅读时段在 Kavita 侧才有多次写入、时长和字数才算得准;补推要跟在真实位置变化上 +--- (见 heartbeat_interval):Kavita 对同位置的写入直接 early-return,纯定时的整拍等于没推。 +--- 会话开始时间 = 第一次有效写入,所以 heartbeat_interval 也是会话起点的最大滞后。 +--- 两次补推之间的最小间隔默认值(秒),也是设置项 heartbeat_interval 的默认值。 +--- 把密集翻页合并成最多一拍一次,别每页一发。0 = 关闭阅读期心跳。 +local DEFAULT_HEARTBEAT_INTERVAL = 30 + +--- 阅读期进度心跳的补推间隔(秒)。设置项 heartbeat_interval:默认 30; +--- 0 = 关闭阅读期心跳(关书 / 切章 / 休眠的推送不受影响)。 +---@return integer +local function heartbeatInterval() + local value = tonumber(require("utils.settings").getSource(ID).heartbeat_interval) + if value == nil then return DEFAULT_HEARTBEAT_INTERVAL end + value = math.floor(value) + return value > 0 and value or 0 +end + +---@class KavitaHeartbeat +---@field identity BookIdentity 正在读的书 +---@field position ProgressPosition 最近一次事件报来的位置 +---@field pushed string|nil 上次推上去的位置标识(位置没变就别推,Kavita 也会丢) +---@field last_push integer 上次补推的 Unix 时间戳(建表即当作刚推过,避开开书拉取的竞态) +---@field interval integer 本会话的补推最小间隔(秒),起心跳时从设置读入 +---@field tick function 兜底定时器(慢读没有翻页事件时也定期补推) +---@field busy boolean|nil 上一拍还在飞,本拍跳过(不补报) + +--- 停掉阅读期进度心跳。 +---@param self KavitaSource +local function stopHeartbeat(self) + local hb = self._heartbeat + if not hb then return end + self._heartbeat = nil + require("ui/uimanager"):unschedule(hb.tick) +end + +--- 位置的标识:epub 用锚点,其余用页码 / 比例。 +---@param position ProgressPosition +---@return string +local function positionKey(position) + return position.locator or tostring(position.page or position.fraction or "") +end + +--- 推一次当前位置。开书拉取未落定(前 interval 秒)/ 并发 / 离线 / 距上次太近 / 位置没变, +--- 都跳过,这次的位置留给下一拍。 +---@param self KavitaSource +---@param hb KavitaHeartbeat +local function pushProgress(self, hb) + if self._heartbeat ~= hb then return end + if hb.busy or not require("book.progress").canPush(hb.identity) or not online() then return end + if os.time() - hb.last_push < hb.interval then return end + local key = positionKey(hb.position) + if key == hb.pushed then return end + hb.busy, hb.last_push, hb.pushed = true, os.time(), key + logger.dbg("kavita heartbeat push", hb.identity.stable_id, key) + self:putProgressAsync(hb.identity, hb.position, function(ok, err) + hb.busy = false + if ok ~= true then + hb.pushed = nil -- 失败留个待重试的位置,下一拍再补 + logger.warn("kavita progress heartbeat failed", hb.identity.stable_id, err) + end + end) +end + +--- 兜底拍:慢读没有翻页事件时也定期补推一次当前位置。间隔取 max(60, 补推间隔): +--- 不会比节流间隔更频繁,设置调大后也不白醒。 +---@param self KavitaSource +---@param hb KavitaHeartbeat +local function beat(self, hb) + if self._heartbeat ~= hb then return end + require("ui/uimanager"):scheduleIn(hb.interval, hb.tick) + pushProgress(self, hb) +end + +--- 翻页 / 切章 / 唤醒:起或续阅读期进度心跳,并更新最近位置。换书 / 间隔改了则先停旧心跳。 +---@param self KavitaSource +---@param identity BookIdentity|nil +---@param position ProgressPosition|nil +local function touchHeartbeat(self, identity, position) + if not identity or not self:configured() then return end + local interval = heartbeatInterval() + if interval <= 0 then + stopHeartbeat(self) + return + end + local hb = self._heartbeat + if hb and (hb.identity.stable_id ~= identity.stable_id or hb.interval ~= interval) then + stopHeartbeat(self) + hb = nil + end + if not hb then + hb = { + identity = identity, + position = position or { fraction = 0 }, + last_push = os.time(), + interval = interval, + tick = require("ui.guard").wrap("kavita heartbeat", function() beat(self, hb) end), + } + self._heartbeat = hb + require("ui/uimanager"):scheduleIn(interval, hb.tick) + end + hb.identity = identity + hb.position = position or hb.position + -- 位置刚变过就立刻推:Kavita 认的是写入之间的跨度,定时拍若整拍都撞在同一个位置 + -- 上等于没推,会话仍会退化成 0 秒。 + pushProgress(self, hb) +end + +--- 翻页 / 切章 / 唤醒起进度心跳并更新位置,关书 / 休眠停掉;其余事件交给基类。 +---@param event string +---@param payload table|nil +function Source:onEvent(event, payload) + if event == "page_changed" or event == "chapter_changed" or event == "reading_resumed" then + if payload then touchHeartbeat(self, payload.identity, payload.position) end + return + end + if event == "reading_stopped" then + stopHeartbeat(self) + return + end + return SourceBase.onEvent(self, event, payload) +end + +function Source:close() + stopHeartbeat(self) + if self.backfill then self.backfill.cancel() end +end + +--- 书架:所选库的全部 series 交给书库对账。Kavita 没有删书接口,dirty_only 跳过, +--- 本地删除留墓碑,对账不会复活。 +--- 远端快照(库 + 每本 id/名称/库名/字数)的指纹没变、本地书架也非空时跳过对账: +--- 本地书架只会被对账和删除改动,删除留墓碑本来就不用对账;force 刷新照常对账。 +---@param opts { dirty_only?: boolean, force?: boolean, on_progress?: fun(text: string|nil, done: integer|nil, total: integer|nil), on_changed?: fun() }|nil +---@param cb fun(result: SyncResult|nil, err: any) +---@return { cancel: fun() } +function Source:syncBooksAsync(opts, cb) + opts = opts or {} + if opts.dirty_only then return SourceBase.skipped(cb, "no remote delete") end + -- 手动刷新 / 书库重扫 = 05 A1 的第二类失效:投影必须重建, + -- 否则用户点了刷新、缓存状态变了,书架标记还是旧的。后台同步复用记忆(无 TTL、不重拉)。 + if opts.force then Cache.resetShelf() end + local libraries = {} + for id in pairs(require("utils.settings").getSource(ID).libraries or {}) do + libraries[#libraries + 1] = id + end + if not self:configured() or #libraries == 0 then + return SourceBase.defer(cb, nil, _("请先在设置里填写 Kavita 服务器并选择书库")) + end + table.sort(libraries) + local report = opts.on_progress or function() end + local books, reads, prints, lib_index, page, cancelled = + {}, {}, { SHELF_SNAPSHOT_VERSION, table.concat(libraries, ",") }, 1, 1, false + ---@type HttpJob + local job + + local function finish() + local settings = require("utils.settings") + local cfg = settings.getSource(ID) + local fingerprint = require("ffi/sha2").md5(table.concat(prints, "\n")) + local BookDB = require("book.books_db") + local result, err, ids + if not opts.force and cfg.shelf_fingerprint == fingerprint then + ids = BookDB.libraryStableIdsBySource(self.id) + end + if ids and #ids > 0 then + result = { pulled = 0, pushed = 0, hidden = 0, conflicts = 0, skipped = false } + else + result, err = require("source.shelf").reconcile(self.id, books, opts.force, true) + if not result then return cb(nil, err) end + cfg.shelf_fingerprint = fingerprint + settings.saveSource(ID, cfg) + ids = {} + for idx, book in ipairs(books) do ids[idx] = book.stable_id end + end + -- 简介 / 作者是逐本后台补的,跟快照变不变无关:换源 / 断网中断过,下次同步必须接着补, + -- 否则没补到的书永远停在「未知作者」。 + self:backfillMeta(ids, { force = opts.force, on_changed = opts.on_changed }) + -- 服务端已读进度同理:网页端 / 别的设备读过,书架也得进「最近阅读」与「已读」。 + -- 逐行写各自成败,包一层只为合成一次提交。 + require("utils.db").transaction(function() + result.pulled = result.pulled + backfillRead(self.id, reads) + return true + end) + -- 书架投影预热:开桌面必跑本方法,进书架时命中记忆(05 A1)。失败不影响同步结果, + -- 但不能静默:同一故障本进程只记一行(缓存模块异常通常意味着 kamare 侧坏了)。 + local function settle(changed) + if cancelled then return end + result.pulled = result.pulled + changed + local ok, shelf_err = pcall(Cache.shelf) + if not ok and not shelf_prewarm_failed then + shelf_prewarm_failed = true + logger.warn("kavita shelf cache prewarm failed", shelf_err) + end + cb(result) + end + -- 系列级聚合不知道「当前读到哪一卷」:另一台设备读的新卷本机没有卷行,首页「当前阅读」 + -- 会停在旧卷。按服务器给的 continue-point 补上(离线直接跳过)。 + job = backfillCurrentVolume(self, reads, settle) + end + + local function fetch() + report(T(_("正在拉取书架(%1 本)"), #books)) + local query = { pageNumber = page, pageSize = PAGE_SIZE } + -- Field 19 = 库,Comparison 0 = 等于,SortField 1 = 按名称。 + local body = { + Statements = { { Field = 19, Comparison = 0, Value = libraries[lib_index] } }, + Combination = 1, + SortOptions = { SortField = 1, IsAscending = true }, + } + job = self.client:json("POST", "/api/Series/all-v2", query, body, function(list, err) + if cancelled then return end + if not list then return cb(nil, err) end + for _idx, series in ipairs(list) do + books[#books + 1] = { + stable_id = tostring(series.id), + title = series.name, + category = series.libraryName, + -- Kavita 的书架一行就是一个 series:系列列填自己的名字, + -- 否则图书馆的「系列」页签把整库都归到「无系列」。 + series = series.name, + -- 「最近添加」按 Kavita 的最近更新排,而不是全库同一次同步的上架时间。 + -- lastChapterAddedUtc 是真的 UTC(created 没有 Utc 后缀、是服务器本地时间,不拿来做时间)。 + inserted_at = utcTime(series.lastChapterAddedUtc), + meta = { words = series.wordCount }, + } + prints[#prints + 1] = table.concat({ series.id, series.name or "", series.libraryName or "", + tonumber(series.wordCount) or 0, series.lastChapterAddedUtc or "" }, "\31") + if (tonumber(series.pagesRead) or 0) > 0 then reads[#reads + 1] = series end + end + if #list >= PAGE_SIZE then + page = page + 1 + elseif lib_index < #libraries then + lib_index, page = lib_index + 1, 1 + else + return finish() + end + fetch() + end) + end + fetch() + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +--- 本地统计行只在本地确认,不发请求(先例微信)。 +--- +--- Kavita 的阅读历史是服务端按会话自己记的,本机没有对应的上报接口;确认后这些行不再是脏行, +--- 展示仍按「云端快照 + 拉取后本地新读」合并。 +--- 当场就能回也走 defer 下一帧回调(源契约):调用方先拿到可取消句柄,取消后不再回调。 +---@param rows BookStatsRow[]|nil +---@param cb fun(data: BookStatsPushResult|nil, err: string|nil) +---@return { cancel: fun() } +function Source:pushStatsAsync(rows, cb) + local ids = {} + for _idx, row in ipairs(rows or {}) do ids[#ids + 1] = row.id end + return SourceBase.defer(cb, { ok = true, synced_ids = ids }) +end + +--- 拉取 Kavita 全局阅读历史(全量)→ reading_stats 行 + 替换指令。 +--- +--- 分页:`PageSize=200`,按响应头 `Pagination` 循环(页数上限兜底);`Libraries` 必传(重复键, +--- 逗号串会被服务端当成一个库、恒返回 0 条),时区取设备时钟映射(未知回退 UTC),不带日期范围。 +--- 身份:单卷系列读在 series 行、多卷逐卷(1 章 = 单卷,见 Stats),判定结果与「本次身份」记在 +--- 扩展状态文件里,避免每轮重复请求目录;目录不可得的系列本轮跳过,不中断其它系列。 +--- 失败一律 cb(nil, err) 静默(本地统计不受影响,下次同步自然重试),取消后不回调。 +---@param cb fun(result: BookStatsPullResult|nil, err: string|nil) +---@return { cancel: fun() } +function Source:pullStatsAsync(cb) + local libraries = {} + for id in pairs(require("utils.settings").getSource(ID).libraries or {}) do + libraries[#libraries + 1] = id + end + if not self:configured() or #libraries == 0 then + return SourceBase.defer(cb, nil, _("请先在设置里填写 Kavita 服务器并选择书库")) + end + table.sort(libraries) + local timezone = Stats.ianaTimezone(os.getenv("TZ")) + -- 快照时刻取发起拉取的时刻:展示端以它为界把「拉取后本地新读」叠加在云端快照上。 + local fetched_at = os.time() + local state = require("luasettings"):open( + require("datastorage"):getSettingsDir() .. STATS_STATE_FILE) + --- 系列 → 本地目录章数(1 = 单卷):上次判定 + 本轮新判定,注给 Stats 用。 + --- 状态文件被写坏(不是表)时当作没判过:本轮全部重新判定,别让索引报错断掉整次拉取。 + local volumes = state:readSetting("volumes", {}) + if type(volumes) ~= "table" then volumes = {} end + local seen = state:readSetting("identities", {}) + if type(seen) ~= "table" then seen = {} end + -- 卷名(seriesId → chapterId → 卷名):章数判定时目录已到手,顺带记下、随 commit 落盘。 + -- 后续轮次章数已知 → 不再读目录,物化标题靠它才不会退容器名(「系列 · 系列」)。 + local titles = normalizeTitles(state:readSetting("titles", {})) + local entries, pending, pending_idx = {}, {}, 1 + local cancelled = false + ---@type HttpJob|nil + local job + + --- 终结:取消后不回调。 + local function finish(result, err) + if cancelled then return end + cb(result, err) + end + + --- 身份定完 → 纯核心聚合。12 号票的「缺行卷物化」挂在这一步:身份与条目都已就绪, + --- 物化要用的 series / 章节信息也能从同一批数据里取。 + local function build() + local result = Stats.fromHistory(entries, { + source_id = self.id, fetched_at = fetched_at, volumes = volumes, seen = seen, + }) + -- 缺行卷物化(12 号票):身份与条目都已就绪,用同一批数据补本机没有书行的卷, + -- 展示端(洞察当日书单 / 单书详情 / 锁屏账单)才有书名。不进书架同步结果、不调对账。 + -- 不做独立变更信号:物化行只在统计视图里可见,可见的前提是同一次拉取写入了统计行 → + -- pulled > 0 已让桌面发 stats_changed;零统计行的纯物化没有任何可见变化。 + -- 也不为此改核心:spec 硬约束「核心插件零改动,只以扩展接入既有契约」。 + materializeVolumes(result.identities, titles) + -- 落库成功(核心的 result.commit)才更新状态:失败不前进, + -- 上次身份还在,身份漂移留下的孤儿行下次还能清。 + ---@diagnostic disable-next-line: inject-field + result.commit = function() + state:saveSetting("volumes", volumes) + state:saveSetting("titles", titles) + state:saveSetting("identities", result.identities) + state:flush() + end + finish(result) + end + + --- 逐个判定待定系列的章数:状态文件里有的不请求,缺的走 Source:toc + --- (新鲜缓存 > 在线拉目录 > 离线过期缓存)。 + local function resolveNext() + if cancelled then return end + local series_id = pending[pending_idx] + pending_idx = pending_idx + 1 + if not series_id then return build() end + job = self:toc(series_id, function(toc, toc_err) + if cancelled then return end + local count = type(toc) == "table" and #toc or 0 + if count > 0 then + volumes[series_id] = count + -- 目录已到手:卷名顺带记下(已有的同名卷名保留:目录缓存过期时不会反而丢名字)。 + local named = titles[series_id] + if not named then + named = {} + titles[series_id] = named + end + for _i, item in ipairs(toc) do + local chapter_id = item.chapterId or item.uid + if chapter_id ~= nil and item.title ~= nil then + named[tostring(chapter_id)] = item.title + end + end + else + -- 判不出单卷 / 多卷的系列整条跳过:身份是错的比缺行更糟(Stats 侧也会记一条)。 + logger.warn("kavita stats series toc unavailable", series_id, toc_err) + end + resolveNext() + end) + end + + --- 一页历史。分页头不可信(缺失 / 解析不出)时按「本页拉满就还有下一页」续拉, + --- 仍受页数上限约束,异常头不会无限循环。 + local function fetchPage(page) + job = self.client:jsonPaged("GET", "/api/Stats/reading-history", { + TimeZoneId = timezone, Libraries = libraries, PageNumber = page, PageSize = STATS_PAGE_SIZE, + }, nil, function(list, err, _code, pages) + if cancelled then return end + if not list then return finish(nil, err) end + for _idx, entry in ipairs(list) do entries[#entries + 1] = entry end + local more = pages and page < pages or (not pages and #list >= STATS_PAGE_SIZE) + if more and page < STATS_MAX_PAGES then return fetchPage(page + 1) end + if more then logger.warn("kavita stats pull hit page cap", STATS_MAX_PAGES) end + -- 分页合并完了才知道全量里有哪些系列:这里收集章数还不知道的,逐个判定。 + local added = {} + for _idx, entry in ipairs(entries) do + local series_id = entry.seriesId ~= nil and tostring(entry.seriesId) or nil + if series_id and not volumes[series_id] and not added[series_id] then + added[series_id] = true + pending[#pending + 1] = series_id + end + end + resolveNext() + end) + end + + fetchPage(1) + return { cancel = function() + cancelled = true + if job and job.cancel then job:cancel() end + end } +end + +--- series 的卷目录:series(取 libraryId)→ volumes → metadata(作者 / 简介写回书库,失败不影响目录)。 +--- Kavita 的卷列表 → 目录条目。fetchToc 与「点开系列时立即刷新进度」共用同一份映射: +--- 标题退让顺序、卷摘要(挂在章上)、页数 / 已读页数必须两处一致,否则选卷列表会跳变。 +---@param series table Kavita SeriesDto(要 id / name / libraryId / format) +---@param volumes table[] Kavita VolumeDto[] +---@return BookChapter[]|nil +local function tocFromVolumes(series, volumes) + local toc = {} + for _vidx, volume in ipairs(volumes) do + -- 卷摘要挂在章上(VolumeDto 没有 summary):一章为空时用同卷第一个有摘要的。 + local volume_summary + for _cidx, chapter in ipairs(volume.chapters or {}) do + volume_summary = volume_summary or summary(chapter.summary) + end + for _cidx, chapter in ipairs(volume.chapters or {}) do + local file = chapter.files and chapter.files[1] and chapter.files[1].filePath + toc[#toc + 1] = { + idx = #toc + 1, + uid = tostring(chapter.id), + title = title(chapter.titleName) or title(chapter.title) or title(volume.name) + or (file and file:match("([^/\\]+)%.[^.]+$")) or series.name, + -- 卷简介:优先本章摘要,退回同卷其它章的摘要(都没有就不写,展示时回退系列简介)。 + summary = summary(chapter.summary) or volume_summary, + chapterId = chapter.id, + volumeId = volume.id, + libraryId = series.libraryId, + seriesId = series.id, + format = FORMATS[tonumber(chapter.format) or tonumber(series.format)], + pages = tonumber(chapter.pages) or 0, + pagesRead = tonumber(chapter.pagesRead) or 0, + } + end + end + return #toc > 0 and toc or nil +end + +--- 在线拉目录并落缓存;默认顺带补 series metadata。 +--- 点开系列时的按需刷新传 skip_meta:只要各卷 pagesRead / 卷名 / 卷摘要,失败时调用方继续用缓存。 +---@param series_id string +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@param skip_meta boolean|nil +---@return { cancel: fun() } +function Source:fetchToc(series_id, cb, skip_meta) + local cancelled = false + ---@type HttpJob + local job + local function step(method, path, query, done) + job = self.client:json(method, path, query, nil, function(data, err) + if not cancelled then done(data, err) end + end) + end + step("GET", "/api/Series/" .. series_id, nil, function(series, err) + if not series then return cb(nil, err) end + step("GET", "/api/Series/volumes", { seriesId = series_id }, function(volumes, verr) + if not volumes then return cb(nil, verr) end + local toc = tocFromVolumes(series, volumes) + if not toc then return cb(nil, _("这本书在 Kavita 上没有可读的卷")) end + if not require("source.toc").put(self.id, series_id, toc) then + return cb(nil, _("章节目录保存失败")) + end + if skip_meta then return cb(toc) end + step("GET", "/api/Series/metadata", { seriesId = series_id }, function(metadata) + if metadata then + require("book.store").rememberMany({ + withMetadata({ source_id = self.id, stable_id = series_id, title = series.name }, metadata), + }) + end + cb(toc) + end) + end) + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +--- 目录:新鲜缓存 > 在线拉取 > 离线时的过期缓存(已下载的卷离线也要能开、能记进度)。 +---@param series_id string +---@param cb fun(toc: BookChapter[]|nil, err: string|nil) +---@return { cancel: fun() } +function Source:toc(series_id, cb) + local cached = require("source.toc").read(self.id, series_id) + if cached then return SourceBase.defer(cb, cached) end + if online() then return self:fetchToc(series_id, cb) end + return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) +end + +--- 详情页统计并入的卷身份:多卷 series 的时长 / 会话都记在 `seriesId:chapterId` 卷行上, +--- 容器(series 行)自己没有统计。目录拿不到时返回 nil,只显示本行。 +---@param identity BookIdentity +---@return string[]|nil +function Source:statsIdentities(identity) + if type(identity) ~= "table" or type(identity.stable_id) ~= "string" then return nil end + local series_id, chapter_id = splitId(identity.stable_id) + if chapter_id then return nil end + local toc = require("source.toc").read(self.id, series_id) + if type(toc) ~= "table" or #toc <= 1 then return nil end + local ids = {} + for _idx, entry in ipairs(toc) do + if entry.chapterId ~= nil then + ids[#ids + 1] = series_id .. ":" .. tostring(entry.chapterId) + end + end + return #ids > 1 and ids or nil +end + +--- 身份对应的卷。series 行的卷号取自登记的文件名(.)。 +---@param identity BookIdentity +---@param cb fun(entry: table|nil, err: string|nil) +---@return { cancel: fun() } +function Source:entry(identity, cb) + local series_id, chapter_id = splitId(identity.stable_id) + if not chapter_id then + local path = downloaded(self.id, identity.stable_id) + chapter_id = path and path:match("(%d+)%.%w+$") + end + return self:toc(series_id, function(toc, err) + if not toc then return cb(nil, err) end + local entry = findEntry(toc, chapter_id) + cb(entry, not entry and _("这一卷已不在 Kavita 上") or nil) + end) +end + +--- 下载一卷到 ref 的工作目录并登记路径;已下载的直接登记。 +---@param ref BookIdentity +---@param entry table +---@param cb fun(path: string|nil, err: string|nil) +---@return { cancel: fun() } +function Source:fetchVolume(ref, entry, cb) + local Paths = require("utils.paths") + if not MAGIC[entry.format] then + return SourceBase.defer(cb, nil, _("图片目录格式需要安装 kamare 插件在线阅读")) + end + Paths.ensureBookWork(ref.stable_id, self.id) + local path = T("%1/%2.%3", Paths.bookWorkDir(ref.stable_id, self.id), entry.chapterId, entry.format) + local function register() + local ok, err = require("book.store").touch(path, ref) + cb(ok and path or nil, err) + end + if validFile(path, entry.format) then return SourceBase.defer(register) end + if not online() then return SourceBase.defer(cb, nil, _("网络不可用,请先连接 Wi-Fi")) end + local dialog = require("ui.themes.widgets.progress_dialog"):new{ title = entry.title, dismissable = false } + dialog:show() + dialog:set(_("正在下载…")) + local job = self.client:download(entry.chapterId, path, function(bytes, total) + if total and total > 0 then dialog:bytes(bytes, total) end + end, function(ok, err) + dialog:close() + if not ok then return cb(nil, err or _("下载失败")) end + if not validFile(path, entry.format) then + os.remove(path) + return cb(nil, _("下载文件校验失败")) + end + register() + end) + return { cancel = function() + job:cancel() + dialog:close() + end } +end + +--- 漫画查看器的提示通道:on_next 找不到下一卷时没有 cb 可回,只能自己弹。 +---@param text string +local function toast(text) + require("ui.themes.widgets.toast"):new{ text = text, timeout = 3 }:show() +end + +--- 打开一卷:漫画(cbz / 图片目录)的缓存判定、起始页、离线全归 kamare cache(03 A1/A2/A9), +--- moon 只按返回码路由;其它格式仍然下载后用内置阅读器。 +--- 关查看器写卷行真实位置 + 容器聚合(06 A1/A2);章末续读按回调 id 回目录(03 A7)。 +---@param ref BookIdentity 承载这一卷的书库行 +---@param entry table +---@param toc table[]|nil 同 series 的卷,章末续读按 chapterId 找下一卷 +---@param title string +---@param cb fun(path: string|nil, err: string|nil, meta: { handled: boolean }|nil) +---@return { cancel: fun() } +function Source:openEntry(ref, entry, toc, title, cb) + if (entry.format ~= "cbz" and entry.format ~= "image") or not Cache.available("open") then + return self:fetchVolume(ref, entry, cb) + end + + local series_id = splitId(ref.stable_id) + --- 卷身份:真实位置记在 seriesId:chapterId 上,容器行只做聚合(06 A1)。 + ---@param item table + ---@return string + local function volumeId(item) + return series_id .. ":" .. tostring(item.chapterId or item.uid) + end + + --- 卷行缺书时用目录卷名 + 容器元数据补一条(06 A2):ProgressDB.recent 的 EXISTS books + --- 会过滤掉没有书行的卷,最近阅读里就看不到它。 + ---@param item table + local function rememberVolume(item) + local BookDB = require("book.books_db") + local stable_id = volumeId(item) + if BookDB.get(self.id, stable_id) then return end + local container = BookDB.get(self.id, series_id) or ref.book or { stable_id = series_id } + require("book.store").rememberMany({ volumeRow(container, stable_id, item.title, + volumeIntro(item.summary, nil, container)) }) + end + + --- kamare 回调的是物理页 / 物理总数:卷行存真实位置,容器行只存聚合 fraction 且不进最近阅读。 + ---@param item table + ---@param page any + ---@param total any + local function closeProgress(item, page, total) + total = tonumber(total) or tonumber(item.pages) or 0 + page = tonumber(page) or 1 + if total <= 0 then return end + -- 位置以 kamare 的 **journal** 为准(它有服务端比较与 superseded 判定),不用关闭回调的瞬时页: + -- 这样书架百分比、最近阅读和下次打开的位置是同一份事实,不会「显示 50%、打开 30%」。 + -- 只认 source == "journal":snapshot 是下载时的服务端快照,可能比服务端现状旧,不能拿它覆盖。 + -- 官方 kamare / 缺 resume 能力时退回回调页(老行为)。 + local resume = Cache.resumePage(item.chapterId, series_id) + if type(resume) == "table" and resume.source == "journal" then + local journal = tonumber(resume.page) + if journal then page = math.min(math.max(1, journal), total) end + end + page = math.min(page, total) + local fraction = math.min(1, page / total) + local ProgressDB = require("book.progress_db") + ProgressDB.upsertRemote(self.id, volumeId(item), { + fraction = fraction, + page = page, + total_pages = total, + updated_at = os.time(), + }) + rememberVolume(item) + -- 容器行做聚合,并带上「刚读过」的时间戳:图书馆「最近阅读」按系列行排, + -- 读完一卷立刻就能浮上去,不必等下一次同步。位置仍只在卷行上。 + -- 聚合算不出来(本地缺卷行)时保留原值、只刷新时间,绝不拿「缺行 = 未读」低报。 + local aggregate = volumeAggregate(self.id, series_id, toc, + tostring(item.chapterId or item.uid), fraction) + if not aggregate then + local container = ProgressDB.get(self.id, series_id) + aggregate = container and tonumber(container.fraction) + end + if aggregate then + ProgressDB.upsertRemote(self.id, series_id, { + fraction = aggregate, + updated_at = os.time(), + }, { reset_updated_at = true }) + end + end + + ---@param item table + ---@param start_page integer|nil 官方 / 旧版通道的起始页;增强版由 kamare 的 journal 决定 + ---@return table|nil viewer, string|nil code, string|nil message + local function show(item, start_page) + return Cache.open({ + base_url = self.client.base_url, + api_key = self.client.api_key, + entry = item, + title = title, + start_page = start_page, + on_close = function(page, total) closeProgress(item, page, total) end, + on_next = function(next_id) + local next_entry = findEntry(toc or {}, tostring(next_id)) + if not next_entry then return toast(_("下一卷不在目录里")) end + show(next_entry) + end, + }) + end + + local cancelled, job = false, nil + + --- 官方 / 旧版 kamare 没有 journal / resume 接口:起始页得 moon 自己给(03 A2 降级通道)。 + --- 优先问 Kavita(跨设备读到哪就从哪续);云端没记录 / 请求失败时用本地卷行 + --- (关查看器时写的真实页),离线直接用本地。增强版由 kamare 的 journal 决定,不看这里。 + ---@param item table + ---@param done fun(page: integer|nil) + ---@return table|nil job + local function withStartPage(item, done) + local pages = math.max(1, tonumber(item.pages) or 1) + local function localPage() + local row = require("book.progress_db").get(self.id, volumeId(item)) + local page = row and tonumber(row.page) + if page and page > 0 then return math.min(page, pages) end + end + if not online() then + done(localPage()) + return nil + end + return self.client:json("GET", "/api/Reader/get-progress", { chapterId = item.chapterId }, nil, + function(remote) + if cancelled then return end + local read = tonumber(remote and remote.pageNum) or 0 + local local_page = localPage() + if read > 0 then + -- 服务端更靠后用服务端,本机更靠后用本机:只前进,不把读者往回拽。 + local server = math.min(read + 1, pages) + if local_page and local_page > server then return done(local_page) end + return done(server) + end + -- 云端没记录 / 请求失败:本地关书写过页就别退回第 1 页。 + done(local_page) + end) + end + + --- 增强版起始页:把云端位置当**提示**传给 kamare,由它和本机 journal 合并。 + --- 合并规则(回翻 vs 落后)只有一份,落在 kamare 的 `basePage` 判定里 —— moon 自己 + --- 取 max 会把「读者故意回翻」也当成落后。增强版 `open` 不再自己查服务端,不传就只用 + --- journal(所以「另一台设备读到 80%,这台还开在 30%」才会发生)。 + --- 离线 / 请求失败 / 云端没记录:不传,交 kamare 用 journal / 快照决定。 + ---@param item table + ---@param done fun(page: integer|nil) + ---@return table|nil job + local function resumeStartPage(item, done) + local pages = math.max(1, tonumber(item.pages) or 1) + if not online() then return done(nil) end + return self.client:json("GET", "/api/Reader/get-progress", { chapterId = item.chapterId }, nil, + function(remote) + if cancelled then return end + local read = tonumber(remote and remote.pageNum) or 0 + done(read > 0 and math.min(read + 1, pages) or nil) + end) + end + + ---@param viewer table|nil + ---@param code string|nil + ---@param message string|nil + local function afterOpen(viewer, code, message) + if cancelled then return end + if viewer then return cb(nil, nil, { handled = true }) end + if code == "offline_not_cached" then + -- A5/A6:kamare 缓存 > 旧 cbz > 下载。旧 cbz 命中时离线照开,静默保留不删。 + local old = entry.format == "cbz" and downloaded(self.id, ref.stable_id) + if old then return SourceBase.defer(cb, old) end + return cb(nil, Cache.message(code, message)) + end + if code == "viewer_running" or code == "no_pages" or code == "settings_write_failed" then + -- 查看器已在运行绝不回退下载(旧的 bug);页面为空 / 配置写失败也不该重下。 + return cb(nil, Cache.message(code, message)) + end + -- 其它失败:cbz 交给 fetchVolume 兜底(本地已有文件时只登记,不重新下载);image 下载不了。 + if entry.format == "cbz" then return self:fetchVolume(ref, entry, cb) end + return cb(nil, Cache.message(code, message)) + end + + if Cache.enhancedOpen() then + job = resumeStartPage(entry, function(start_page) + if cancelled then return end + afterOpen(show(entry, start_page)) + end) + else + job = withStartPage(entry, function(start_page) + if cancelled then return end + afterOpen(show(entry, start_page)) + end) + end + return { cancel = function() + cancelled = true + if job and job.cancel then job:cancel() end + end } +end + +--- 旧「已下载」标记:kamare 不可用时卷列表右侧仍要显示本地 cbz / epub。 +---@param series Book +---@param entry table +---@return string|nil +local function legacyVolumeState(series, entry) + local Paths = require("utils.paths") + local vid = series.stable_id .. ":" .. entry.chapterId + local state + if entry.pages > 0 and entry.pagesRead >= entry.pages then + state = _("已读") + elseif entry.pagesRead > 0 then + state = _("在读") + end + if entry.format and validFile(T("%1/%2.%3", Paths.bookWorkDir(vid, ID), entry.chapterId, entry.format), entry.format) then + state = state and T(_("%1 · 已下载"), state) or _("已下载") + end + return state +end + +--- 多卷选卷:状态字 + 行尾缓存动作,标题栏「缓存整部」(04 / 07);关窗没选算取消。 +---@param series Book +---@param toc table[] +---@param cb fun(entry: table|nil) +local function pickVolume(series, toc, cb) + local list = VolumeList.pick(series, toc, cb, { + fallback = function(entry) return legacyVolumeState(series, entry) end, + }) + list:show() + return list +end + +--- 打开:非漫画的已下载文件直接开(不联网);漫画按 kamare 缓存 > 旧 cbz > 下载的顺序(03 A5)。 +--- `downloaded()` 的早返回不能压过 kamare 缓存,否则有旧 cbz 的卷永远走不进离线缓存。 +function Source:openBookAsync(identity, _opts, cb) + local job, cancelled = nil, false + local function finish(file, err, meta) + if not cancelled then cb(file, err, meta) end + end + local series_id, chapter_id = splitId(identity.stable_id) + local local_path = downloaded(self.id, identity.stable_id) + local local_format = local_path and local_path:match("%.(%w+)$") + -- EPUB / PDF:本地文件优先,否则下载后原生阅读;漫画要先进 kamare 判缓存(A5)。 + if local_path and local_format ~= "cbz" then return SourceBase.defer(cb, local_path) end + -- 目录命中缓存才需要额外拉一次进度:本来就要 fetchToc 的话,那一次已经是最新。 + local cached_toc = require("source.toc").read(self.id, series_id) + job = self:toc(series_id, function(toc, err) + if not toc then + -- 目录拿不到但盘上有旧 cbz:本地文件仍可开,离线老用户不被缓存目录卡住。 + if local_path then return finish(local_path) end + return finish(nil, err) + end + if chapter_id or #toc == 1 then + local entry = findEntry(toc, chapter_id) + if not entry then return finish(nil, _("这一卷已不在 Kavita 上")) end + local name = identity.book and identity.book.title or entry.title + job = self:openEntry(identity, entry, toc, name, finish) + return + end + -- fetchToc 会把 series 级作者 / 简介写回容器行,而 identity.book 是开书那一刻的旧快照: + -- 这里重读一次容器行,免得新 series 第一次打开时卷行被写成「未知作者」。 + local series = require("book.books_db").get(self.id, series_id) + or identity.book or { stable_id = series_id } + local picker = pickVolume(series, toc, function(entry) + if cancelled then return end + if not entry then return finish(nil, _("已取消")) end + local ref = { source_id = self.id, stable_id = series_id .. ":" .. entry.chapterId } + -- 卷行继承容器(series 级)元数据:Kavita 只在 series 级给作者 / 简介 / 分类, + -- 卷行自己空着,最近阅读里就是「未知作者」。每次开书对齐一次,容器补全后立刻生效。 + local cur = require("book.books_db").get(self.id, ref.stable_id) + require("book.store").rememberMany({ volumeRow(series, ref.stable_id, entry.title, + volumeIntro(entry.summary, cur, series)) }) + job = self:openEntry(ref, entry, toc, series.title or entry.title, finish) + end) + -- 点开系列 = 想看最新进度:目录缓存 6 小时内不会自己更新,这里立刻问一次服务器 + -- (各卷 pagesRead),拿到后原地刷新选卷列表;离线 / 失败继续用缓存,不打断选择。 + if cached_toc and picker and type(picker.refreshToc) == "function" and online() then + job = self:fetchToc(series_id, function(fresh) + if cancelled or not fresh then return end + picker.refreshToc(fresh) + end, true) + end + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +--- 详情页只消费目标与文案,卷身份和续读状态留在源内。 +---@param series Book +---@param opts { meta_only: boolean|nil }|nil +---@return BookReadingTarget|nil +function Source:readingTarget(series, opts) + local series_id, chapter_id = splitId(series.stable_id) + if chapter_id then return nil end + local toc = require("source.toc").read(self.id, series_id) + if not toc then return nil end + local select_text = #toc > 1 and _("选择卷") or nil + if opts and opts.meta_only then + return { select_text = select_text } + end + local target = VolumeList.continueTarget(series, toc) + if not target then return nil end + local entry = target.entry + local stable_id = series.stable_id .. ":" .. tostring(entry.chapterId) + local cur = require("book.books_db").get(self.id, stable_id) + local text, caption = ContinuePoint.describe(target, series.title) + return { + book = volumeRow(series, stable_id, entry.title, volumeIntro(entry.summary, cur, series)), + text = text, + caption = caption, + select_text = select_text, + } +end + +--- 卷身份 → Kavita volumeId(按 chapterId 从目录缓存反查)。目录还没拉过就没有。 +---@param series_id string +---@param chapter_id string +---@return integer|nil +function Source:volumeId(series_id, chapter_id) + local toc = require("source.toc").read(self.id, series_id, true) + local entry = toc and findEntry(toc, chapter_id) + return entry and entry.volumeId or nil +end + +--- 卷身份(seriesId:chapterId)折叠回系列 id;不是卷身份返回 nil。 +--- 图书馆「最近阅读」按它把卷行归并成系列行(点开再选卷),首页「当前阅读」仍按卷展示。 +---@param stable_id string +---@return string|nil +function Source:volumeParent(stable_id) + if type(stable_id) ~= "string" then return nil end + return stable_id:match("^(%d+):%d+$") +end + +--- 封面:系列行取系列封面,卷行取**这一卷自己的封面**(`volume-cover`)。 +--- `chapter-cover` 是从该卷文件第一页取的图,扫描版常是跨页 / 版权页 / 白页,缩到卡片上就是坏图,不用。 +--- 离线或目录里查不到这一卷时退回 kamare 缓存的系列封面(本地文件,不需要鉴权)。 +--- `authoritative`:源封面压过同身份的本地抽页 / 旧封面缓存。 +---@param identity BookIdentity +---@return BookCoverRequest|nil, string|nil +function Source:coverRequest(identity) + if not self:configured() then return nil, _("未配置") end + local series_id, chapter_id = splitId(identity.stable_id) + -- 已缓存系列 kamare 落了本地封面:离线也能画,且不再走鉴权 URL(05 A8)。 + -- 只在文件真的存在时用:index 里记的路径可能已被用户清掉。 + local shelf = Cache.shelf() + local local_cover = shelf and shelf.cover and shelf.cover[series_id] + if not (type(local_cover) == "string" and local_cover ~= "" + and require("libs/libkoreader-lfs").attributes(local_cover, "mode") == "file") then + local_cover = nil + end + if chapter_id and online() then + local volume_id = self:volumeId(series_id, chapter_id) + if volume_id then + return { + url = self.client:url("/api/Image/volume-cover", { volumeId = volume_id }), + headers = self.client:headers(), + authoritative = true, + } + end + end + if local_cover then return { url = local_cover, authoritative = true } end + return { + url = self.client:url("/api/Image/series-cover", { seriesId = series_id }), + headers = self.client:headers(), + authoritative = true, + } +end + +--- Kavita 进度 → 月读位置;与本地同一 spine / 页时交回本地行。 +---@param identity BookIdentity +---@param entry table +---@param remote { pageNum: integer, bookScrollId: string|nil } +---@return ProgressPosition +function Source:position(identity, entry, remote) + local pages = math.max(entry.pages, 1) + local page_num = math.min(tonumber(remote.pageNum) or 0, pages) + local fraction = page_num / pages + local here = require("book.progress_db").get(self.id, identity.stable_id) + if entry.format == "epub" then + local spine = math.min(page_num, pages - 1) + local book = require("book.books_db").get(self.id, identity.stable_id) + local scroll = Position.resolveScrollId(book and book.path, spine, remote.bookScrollId) + if here and Position.spine(here.locator) == spine then + -- 同一 spine:远端只有 spine 粒度(没带锚点 / 锚点解不出),或锚点与本机上次同步的位置 + -- 一样——Kavita 的粒度不足以把同一条内的差异判成冲突,交回本地位置,不把读者拽回节首。 + -- 只有远端锚点真的变了才用远端:网页端在同一条里往后读几页正是这种情况, + -- 旧写法一律返回本地,core 的 synced 基线就永远看不到「云端动过」。 + local base = here.synced and here.synced.locator + if not scroll or Position.spine(base) ~= spine or Position.toScrollId(base) == scroll then + return here + end + end + return { fraction = fraction, locator = Position.toXPointer(spine, scroll, pages) } + end + local page = math.max(1, math.min(page_num + 1, pages)) + if here and here.page == page then return here end + return { fraction = fraction, page = page, total_pages = pages } +end + +function Source:getProgressAsync(identity, cb) + local job, cancelled = nil, false + job = self:entry(identity, function(entry, err) + if cancelled then return end + if not entry then return cb(nil, err) end + job = self.client:json("GET", "/api/Reader/get-progress", { chapterId = entry.chapterId }, nil, + function(remote, perr, code) + if cancelled then return end + -- 没读过:旧版本回 400/404,新版本回 pageNum=0 且无锚点。 + if code == 400 or code == 404 or (remote and (tonumber(remote.pageNum) or 0) == 0 + and not remote.bookScrollId) then + return cb(nil, nil, { empty = true }) + end + if not remote then return cb(nil, perr) end + -- page_level:远端只有 spine(epub)/ 页码(pdf)粒度,比例是「第几个 spine」, + -- 与本地内容页比例口径不同 → core 不能按百分比判,得按 spine 判。 + cb(self:position(identity, entry, remote), nil, { page_level = true }) + end) + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +--- 月读位置 → Kavita pageNum(0-based spine / 页),读完发 pages。 +function Source:putProgressAsync(identity, pos, cb) + local job, cancelled = nil, false + job = self:entry(identity, function(entry, err) + if cancelled then return end + if not entry then return cb(nil, err) end + local pages = math.max(entry.pages, 1) + local fraction = tonumber(pos.fraction) or 0 + local page_num + if entry.format == "epub" then + page_num = Position.spine(pos.locator) + elseif pos.page then + page_num = pos.page - 1 + end + page_num = math.max(0, math.min(page_num or math.floor(fraction * pages), pages - 1)) + if fraction >= 1 then page_num = pages end + job = self.client:json("POST", "/api/Reader/progress", nil, { + pageNum = page_num, + bookScrollId = entry.format == "epub" and Position.toScrollId(pos.locator) or nil, + chapterId = entry.chapterId, + volumeId = entry.volumeId, + libraryId = entry.libraryId, + seriesId = entry.seriesId, + }, function(data, perr) + if not cancelled then cb(data and true, perr) end + end) + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +--- 快照里要原样带住的 Kavita 私有字段(spec §3.1)。`Normalize.clean` 是白名单, +--- 漏一个 = 该字段静默消失(比如 `kavita_comment` 丢了,下次 update 会把网页富文本清空)。 +--- `pageNumber` 不是 `kavita_` 前缀,但同样是 Kavita 私有字段:它是开书定位时的 spine 提示 +--- (`locateAnnotation` 读 `annotation.pageNumber`),丢了这个字段的多 spine epub 只能试第 1/2 个 +--- DocFragment,第 3 个之后全部定位失败。update 时服务端忽略它,推送仍用现算的 `anchor.pageNumber`。 +local KAVITA_FIELDS = { + "pageNumber", + "kavita_id", "kavita_note", "kavita_comment", "kavita_comment_html", + "kavita_slot", "kavita_spoiler", "kavita_modified", + "kavita_xpath", "kavita_ending_xpath", + "kavita_unlocated", "kavita_deleted", "kavita_local_note", +} + +--- 注解快照保留 Kavita 全字段:核心只认识 KOReader 字段,源私有字段必须自己补回。 +--- 无 page 的有两类条目要放行:未定位(只有 `kavita_xpath`)与墓碑(只有 `kavita_deleted`), +--- 它们过不了 `Normalize.clean` 的「datetime + page」要求。构造期拿源坐标 / 墓碑标记当占位, +--- 清洗后再把 page 清空(同微信源的 placeholder 写法),否则一次普通保存就把它们洗掉。 +---@param items table[] +---@param total_pages integer|nil +---@return table[] +function Source:cleanAnnotations(items, total_pages) + local out = {} + for _idx, item in ipairs(items) do + if type(item) == "table" then + local placeholder = not item.page and not item.pageref + and (item.kavita_xpath or item.kavita_deleted or item.kavita_id) + local source = item + if placeholder then + source = {} + for key, value in pairs(item) do source[key] = value end + source.page = placeholder + end + local clean = Normalize.clean({ source }, total_pages)[1] + if clean then + if placeholder then clean.page = nil end + for _i, field in ipairs(KAVITA_FIELDS) do clean[field] = item[field] end + out[#out + 1] = clean + end + end + end + return out +end + +--- 删除墓碑(spec §9.1):只留远端 id 与基线备注,等推送成功出列。 +--- 没有 pos / page,`cleanAnnotations` 用 kavita_deleted 当占位放行,阅读器不画它。 +---@param old table 上一版快照里那条 +---@return table +local function tombstone(old) + return { + datetime = old.datetime or os.date("%Y-%m-%d %H:%M:%S"), + chapter_idx = old.chapter_idx, + kavita_id = old.kavita_id, + kavita_note = old.kavita_note, + kavita_deleted = true, + } +end + +--- 阅读器里的注解不带 Kavita id:按 pos0 从上一版快照接过来,免得每次保存都重建远端注解。 +--- 另外把 `previous` 里「有 id 但没有 pos0」的条目(未定位 / 墓碑)原样搬进新 payload: +--- 它们不在阅读器快照里,不搬的话一次普通保存就把「数据在、画不出」的云端条目洗掉。 +--- +--- 本次被删条目(spec §9.1,仅 `index_modified < 0` 时有值)按 pos0 找回上一版那条: +--- 没坐标 / 找不到 → 只漏删不误删;没有 id → 本来就没推到远端;其余追加墓碑。 +---@param previous table[] +---@param current table[] +---@param deleted table|nil KOReader 事件里的被删条目 +---@return table[] +function Source:prepareLocalAnnotations(previous, current, deleted) + current = type(current) == "table" and current or {} + local by_pos, present = {}, {} + for _idx, old in ipairs(previous) do + if type(old) == "table" and old.kavita_id and old.pos0 then by_pos[old.pos0] = old end + end + for _idx, item in ipairs(current) do + if item.kavita_id then present[tostring(item.kavita_id)] = true end + local old = item.pos0 and by_pos[item.pos0] + if old and not item.kavita_id then + item.kavita_id, item.kavita_note = old.kavita_id, old.kavita_note + end + end + for _idx, old in ipairs(previous) do + local id = type(old) == "table" and old.kavita_id and tostring(old.kavita_id) or nil + if id and not old.pos0 and not present[id] then + current[#current + 1] = old + present[id] = true + end + end + if type(deleted) == "table" then + local old = deleted.pos0 and by_pos[deleted.pos0] or nil + if not old then + -- pos0 对不上(换过文件版本)或事件里没坐标:记一条,下一次开书远端那条会回来。 + logger.warn("kavita annotation deleted without anchor; skip tombstone", tostring(deleted.text)) + elseif not old.kavita_id then + logger.dbg("kavita annotation deleted before push; no tombstone", tostring(deleted.text)) + elseif not present[tostring(old.kavita_id)] then + current[#current + 1] = tombstone(old) + present[tostring(old.kavita_id)] = true + end + end + return current +end + +--- 远端删除回流(spec §9.2):`seen` 按 pull 回来的**全量** id 建(含未定位), +--- 输出只画可渲染的远端条目;本地条目带 `kavita_id` 而远端集合里没有 → 丢弃并计入 `dropped`。 +--- 远端同键多条(历史推送窗口的产物,spec §6 / §13.1 B「同键取 id 最小」)只画 id 最小那条, +--- 其余被抑制、计入 `deduped`;被抑制的 id 仍留在 `seen_id`(远端没删它,本地副本不算 dropped)。 +--- 未定位条目仍占 id,所以它对应的本地副本不会被当成远端已删;纯本地划线(无 id)原样保留。 +--- `authoritative` 恒 false(spec §7),这里不改变语义,保留参数只为统一签名。 +---@param remote table[] +---@param current table[] +---@param paging boolean|nil +---@param _authoritative boolean|nil +---@return table[] merged +---@return integer dropped 远端已删(本地有 id 但远端全量里没有) +---@return integer deduped 远端同键被抑制(不画)的条数 +function Source:mergeAnnotations(remote, current, paging, _authoritative) + local merged, seen_id, shown_id, seen_pos, suppressed, suppressed_id = {}, {}, {}, {}, {}, {} + local list = type(remote) == "table" and remote or {} + + -- 第一遍:建远端全量 id 集合(含之后要被抑制的),并按键挑出每条键要画的那条。 + -- 键与推送侧认领同一条(Annotation.key 两套字段名都认);同键取 id 最小,没有 id 的排最后。 + local winner = {} + for idx, item in ipairs(list) do + if type(item) == "table" then + local id = tonumber(item.kavita_id) + if id then seen_id[id] = true end + if Normalize.renderable(item, paging) then + local key = Annotation.key(item) + local best = winner[key] + if best == nil then + winner[key] = idx + else + local best_id = tonumber(list[best].kavita_id) or math.huge + if (id or math.huge) < best_id then + suppressed[best] = true + winner[key] = idx + else + suppressed[idx] = true + end + end + end + end + end + local deduped = 0 + for idx in pairs(suppressed) do + deduped = deduped + 1 + local id = tonumber(list[idx].kavita_id) + if id then suppressed_id[id] = true end + end + + -- 第二遍:按原顺序输出保留下来的远端条目(顺序影响绘制顺序,不因去重打乱)。 + for idx, item in ipairs(list) do + if type(item) == "table" and not suppressed[idx] and Normalize.renderable(item, paging) then + local id = tonumber(item.kavita_id) + merged[#merged + 1] = item + if id then shown_id[id] = true end + if type(item.pos0) == "string" then + seen_pos[item.pos0 .. Annotation.KEY_SEP .. tostring(item.pos1)] = true + end + end + end + local dropped = 0 + for _idx, item in ipairs(type(current) == "table" and current or {}) do + if type(item) == "table" then + local id = tonumber(item.kavita_id) + if id and not seen_id[id] then + dropped = dropped + 1 + logger.warn("kavita annotation deleted remotely; drop local", id) + else + -- 远端已定位的那条会带着复用来的旧 pos0:同 id / 同坐标只画远端那份。 + -- id 在远端全量里但没画出来(未定位)→ 本地这份必须保留,否则书里就少一条。 + -- 例外:id 在远端被同键抑制 → 远端画的是同键里 id 最小的那条,本地这份不能再画一遍。 + local pos_key = type(item.pos0) == "string" + and (item.pos0 .. Annotation.KEY_SEP .. tostring(item.pos1)) or nil + local duplicate = (id and shown_id[id]) + or (id and suppressed_id[id]) + or (item.drawer and pos_key and seen_pos[pos_key]) + if not duplicate and Normalize.renderable(item, paging) then + merged[#merged + 1] = item + end + end + end + end + return merged, dropped, deduped +end + +-- --------------------------------------------------------------------------- +-- 开书定位:云端注解(元素级 xPath + selectedText)→ crengine xpointer(spec §4) +-- +-- Kavita 只给元素路径,没有偏移;文档接口又没有「节点+偏移 → xpointer」。 +-- 所以反过来让 crengine 当文本真值来源:逐个 text()[k] 取节点文本,在元素拼接文本里 +-- 找 selectedText,再把字节区间映射回 (k, codepoint offset)。合成后必须回读校验, +-- 绝不把没验过的坐标写进 doc_settings(错位的划线比不画更糟)。 +-- --------------------------------------------------------------------------- + +-- crengine 的 `.N` 单位是 codepoint(lChar32),不是 UTF-8 字节:偏移一律用 Text.len 数。 + +---@param s string +---@param i integer +---@return integer +local function charStep(s, i) + local byte = s:byte(i) + if byte < 0x80 then return 1 end + if byte < 0xE0 then return 2 end + if byte < 0xF0 then return 3 end + return 4 +end + +--- 前 count 个 codepoint 占用的字节数(1-based 最后字节位置,count=0 时为 0)。 +---@param s string +---@param count integer +---@return integer +local function bytePosOfCodepoint(s, count) + local seen, i = 0, 1 + while seen < count and i <= #s do + i = i + charStep(s, i) + seen = seen + 1 + end + return i - 1 +end + +--- 按 codepoint 取子串(1-based,含首含尾)。 +---@param s string +---@param from integer +---@param to integer +---@return string +local function codepointSub(s, from, to) + local byte_start = bytePosOfCodepoint(s, from - 1) + 1 + local byte_end = bytePosOfCodepoint(s, to) + return s:sub(byte_start, byte_end) +end + +--- 空白判定:ASCII 折叠 + NBSP + 全角空格。crengine 的 CSS 空白处理会动这三类, +--- 真实样本跨段回读只差空白,所以去空白重试必须把它们都算进去。 +---@param s string +---@param i integer +---@return integer 该字符占用的字节数;0 = 不是空白 +local function whitespaceAt(s, i) + local byte = s:byte(i) + if byte == 0x20 or byte == 0x09 or byte == 0x0A or byte == 0x0D then return 1 end + if byte == 0xC2 and s:byte(i + 1) == 0xA0 then return 2 end + if byte == 0xE3 and s:byte(i + 1) == 0x80 and s:byte(i + 2) == 0x80 then return 3 end + return 0 +end + +--- 去空白并保留「过滤后字节 → 原字节」映射,命中后能把偏移回算到原文本。 +---@param s string +---@return string, table +local function stripWhitespace(s) + local out, map = {}, {} + local i, len = 1, #s + while i <= len do + local width = whitespaceAt(s, i) + if width > 0 then + i = i + width + else + out[#out + 1] = s:sub(i, i) + map[#out] = i + i = i + 1 + end + end + return table.concat(out), map +end + +--- 最后一个非空白字符的字节位置(跨段「贴元素末尾」判定用;全空白回 0)。 +---@param s string +---@return integer +local function trimEndByte(s) + local i, last = 1, 0 + while i <= #s do + local width = whitespaceAt(s, i) + if width == 0 then + i = i + charStep(s, i) + last = i - 1 + else + i = i + width + end + end + return last +end + +--- 第一个非空白字符的字节位置(跨段「贴元素开头」判定用)。 +---@param s string +---@return integer +local function trimStartByte(s) + local i = 1 + while i <= #s do + local width = whitespaceAt(s, i) + if width == 0 then break end + i = i + width + end + return i +end + +---@param document table +---@param xp string +---@return string|nil +local function nodeText(document, xp) + local ok, text = pcall(document.getTextFromXPointer, document, xp) + if ok and type(text) == "string" then return text end + return nil +end + +--- 逐 text()[k] 取节点文本:crengine 的 `text()` 不带下标在多节点时会失败, +--- 所以合成路径一律写到 `[k]`;空节点跳过(否则字节区间会映射到零长度节点上)。 +---@param document table +---@param element string +---@return { k: integer, text: string }[] +local function textNodes(document, element) + local nodes = {} + for k = 1, 128 do + local text = nodeText(document, element .. "/text()[" .. k .. "]") + if not text then break end + if text ~= "" then nodes[#nodes + 1] = { k = k, text = text } end + end + return nodes +end + +---@param nodes { k: integer, text: string }[] +---@return string +local function concatNodes(nodes) + local parts = {} + for _idx, node in ipairs(nodes) do parts[#parts + 1] = node.text end + return table.concat(parts) +end + +--- 拼接文本里的字节区间 → (text()[k], codepoint offset)。 +---@param nodes { k: integer, text: string }[] +---@param start_byte integer 1-based,区间首字节 +---@param end_byte integer 1-based,区间尾字节 +---@return integer|nil, integer|nil, integer|nil, integer|nil +local function mapRange(nodes, start_byte, end_byte) + local acc, k0, off0, k1, off1 = 0, nil, nil, nil, nil + for _idx, node in ipairs(nodes) do + local seg_start, seg_end = acc + 1, acc + #node.text + if not k0 and start_byte >= seg_start and start_byte <= seg_end then + k0 = node.k + off0 = Text.len(node.text:sub(1, start_byte - seg_start)) + end + if end_byte >= seg_start and end_byte <= seg_end then + k1 = node.k + off1 = Text.len(node.text:sub(1, end_byte - seg_start + 1)) + end + acc = seg_end + end + return k0, off0, k1, off1 +end + +--- 在元素文本里找 selectedText:先精确找,失败再去空白找(CSS 空白折叠差异)。 +--- 同段重复文本取第一处(真实样本 0/29 歧义),由回读校验兜住错位。 +---@param document table +---@param element string +---@param selected string +---@return string|nil level "exact"|"wsnorm"|nil +---@return { k: integer, text: string }[] nodes +---@return string concat +---@return integer|nil start_byte +---@return integer|nil end_byte +local function locateInElement(document, element, selected) + local nodes = textNodes(document, element) + if #nodes == 0 then + return nil, nodes, "", nil, nil + end + local concat = concatNodes(nodes) + local start_byte = concat:find(selected, 1, true) + if start_byte then + return "exact", nodes, concat, start_byte, start_byte + #selected - 1 + end + local flat, map = stripWhitespace(concat) + local wanted = stripWhitespace(selected) + local flat_start = wanted ~= "" and flat:find(wanted, 1, true) or nil + if flat_start then + return "wsnorm", nodes, concat, map[flat_start], map[flat_start + #wanted - 1] + end + return nil, nodes, concat, nil, nil +end + +--- 起始元素里的最长可命中前缀。跨段选区的头半截在起点段落里可能不是完整 selectedText, +--- 所以从全长往短里试;同一前缀出现多次时优先取「贴元素末尾」的那次(选区的头必然贴段尾)。 +---@param document table +---@param element string +---@param selected string +---@return string|nil concat +---@return table|nil nodes +---@return integer|nil start_byte +---@return integer|nil end_byte +local function locatePrefix(document, element, selected) + local nodes = textNodes(document, element) + if #nodes == 0 then return nil end + local concat = concatNodes(nodes) + local total = Text.len(selected) + local element_end = trimEndByte(concat) + for take = total, 1, -1 do + local prefix = codepointSub(selected, 1, take) + local first = concat:find(prefix, 1, true) + if first then + local chosen = first + local pos = 1 + while true do + local hit = concat:find(prefix, pos, true) + if not hit then break end + if hit + #prefix - 1 == element_end then chosen = hit end + pos = hit + 1 + end + return concat, nodes, chosen, chosen + #prefix - 1 + end + end + return nil +end + +--- 终点元素里的最长可命中后缀。同理,优先取「从元素开头起」的那次(选区尾必然贴段首)。 +---@param document table +---@param element string +---@param selected string +---@return string|nil concat +---@return table|nil nodes +---@return integer|nil start_byte +---@return integer|nil end_byte +local function locateTail(document, element, selected) + local nodes = textNodes(document, element) + if #nodes == 0 then return nil end + local concat = concatNodes(nodes) + local total = Text.len(selected) + local element_start = trimStartByte(concat) + for take = total, 1, -1 do + local suffix = codepointSub(selected, total - take + 1, total) + local first = concat:find(suffix, 1, true) + if first then + local chosen = first + local pos = 1 + while true do + local hit = concat:find(suffix, pos, true) + if not hit then break end + if hit == element_start then chosen = hit end + pos = hit + 1 + end + return concat, nodes, chosen, chosen + #suffix - 1 + end + end + return nil +end + +--- Kavita `//body/p[9]` → `/body/DocFragment[N]/body/p[9]`;N = spine + 1。 +--- 只削一个 `/` 补前缀,不自己归一 `[1]` 下标(那是 DOM version 的事)。 +---@param xpath string|nil +---@param fragment integer +---@return string|nil +local function fragmentBase(xpath, fragment) + if type(xpath) ~= "string" or xpath == "" then return nil end + local path = xpath + if path:sub(1, 2) == "//" then + path = path:sub(2) + elseif path:sub(1, 1) ~= "/" then + path = "/" .. path + end + -- Kavita 不会给 DocFragment;真给了就原样用(跨 spine 的 endingXPath 也不至重复加前缀)。 + if path:sub(1, 17) == "/body/DocFragment" then return path end + if path:sub(1, 5) ~= "/body" then return nil end + return "/body/DocFragment[" .. fragment .. "]" .. path +end + +---@param document table +---@param xp string +---@return boolean +local function inDocument(document, xp) + local ok, present = pcall(document.isXPointerInDocument, document, xp) + return ok and present == true +end + +--- 同片段同级回扫:Kavita 的 `p[k]` 与 crengine 的元素数可能不同(HTML 自动闭合、 +--- 表格 foster parenting),下标失配时在同一父节点下扫同名兄弟,以文本为准找回。 +---@param document table +---@param element string +---@param selected string +---@return string|nil element +---@return table|nil nodes +---@return integer|nil start_byte +---@return integer|nil end_byte +local function scanSiblings(document, element, selected) + local tag = element:match("([^/%[]+)%[%d+%]$") + local parent = element:match("^(.*)/[^/]+$") + if not tag or not parent then return nil end + for index = 1, 400 do + local candidate = parent .. "/" .. tag .. "[" .. index .. "]" + if not nodeText(document, candidate) then break end + local level, nodes, _concat, start_byte, end_byte = locateInElement(document, candidate, selected) + if level then + return candidate, nodes, start_byte, end_byte + end + end + return nil +end + +--- 合成坐标的唯一成功判据:两端都在文档里,且回读文本与 selectedText 相等(允许空白差异)。 +--- 只信 isXPointerInDocument 不够——路径能解析不代表画出来的就是这段文字。 +---@return boolean, string|nil reason +local function verifySelection(document, pos0, pos1, selected) + if not inDocument(document, pos0) then return false, "pos0-missing" end + if not inDocument(document, pos1) then return false, "pos1-missing" end + if type(document.getTextFromXPointers) ~= "function" then return true end + local ok, got = pcall(document.getTextFromXPointers, document, pos0, pos1) + if not ok then return true end -- 老文档 / 桩没实现:不要因校验器缺失把能画的全判失败 + if type(got) ~= "string" then return true end + if got == selected then return true end + if stripWhitespace(got) == stripWhitespace(selected) then return true end + return false, "text-mismatch" +end + +--- 跨段:起点取最长可命中前缀、终点取最长可命中后缀,再各自映射回文本节点。 +---@param document table +---@param head_element string +---@param tail_element string +---@param selected string +---@return { pos0: string, pos1: string }|nil +local function locateCross(document, head_element, tail_element, selected) + local _head_concat, head_nodes, head_start, head_end = locatePrefix(document, head_element, selected) + if not head_nodes then return nil end + local _tail_concat, tail_nodes, tail_start, tail_end = locateTail(document, tail_element, selected) + if not tail_nodes then return nil end + local k0, off0 = mapRange(head_nodes, head_start, head_end) + local _tail_k, _tail_off, k1, off1 = mapRange(tail_nodes, tail_start, tail_end) + if not k0 or not k1 then return nil end + return { + pos0 = head_element .. "/text()[" .. k0 .. "]." .. off0, + pos1 = tail_element .. "/text()[" .. k1 .. "]." .. off1, + } +end + +--- 在指定 DocFragment 上尝试一条注解(不含滑窗)。 +---@return { pos0: string, pos1: string }|nil, string|nil reason +local function attemptLocalize(document, annotation, fragment) + local selected = annotation.text + if type(selected) ~= "string" or selected == "" then return nil, "no-text" end + local base = fragmentBase(annotation.kavita_xpath, fragment) + if not base then return nil, "bad-xpath" end + local ending = annotation.kavita_ending_xpath + local cross = type(ending) == "string" and ending ~= "" and ending ~= annotation.kavita_xpath + if cross then + local tail_base = fragmentBase(ending, fragment) + if tail_base then + local located = locateCross(document, base, tail_base, selected) + if located and verifySelection(document, located.pos0, located.pos1, selected) then + return located + end + end + -- endingXPath 不可用或起点其实含全文:退回单元素匹配,仍以回读为准。 + end + + local used, nodes, start_byte, end_byte + local level, found_nodes, _concat, found_start, found_end = locateInElement(document, base, selected) + if level then + used, nodes, start_byte, end_byte = base, found_nodes, found_start, found_end + else + local candidate, sibling_nodes, sibling_start, sibling_end = scanSiblings(document, base, selected) + if candidate then + used, nodes, start_byte, end_byte = candidate, sibling_nodes, sibling_start, sibling_end + end + end + if not used then return nil, "text-not-found" end + local k0, off0, k1, off1 = mapRange(nodes, start_byte, end_byte) + if not k0 or not k1 then return nil, "range-map" end + local pos0 = used .. "/text()[" .. k0 .. "]." .. off0 + local pos1 = used .. "/text()[" .. k1 .. "]." .. off1 + local ok, reason = verifySelection(document, pos0, pos1, selected) + if not ok then return nil, reason end + return { pos0 = pos0, pos1 = pos1 } +end + +--- pageNumber 只当提示(Kavita 旧推送窗口会差一位,实测 6/29), +--- 依次试 spine / spine+1 / spine−1,每跳都要求文本命中且回读通过。 +---@return { pos0: string, pos1: string }|nil, string|nil reason +local function locateAnnotation(document, annotation) + local hint = math.floor(tonumber(annotation.pageNumber) or 0) + local fragment = hint + 1 + local last_reason + for _idx, delta in ipairs({ 0, 1, -1 }) do + local candidate = fragment + delta + if candidate >= 1 then + local located, reason = attemptLocalize(document, annotation, candidate) + if located then return located end + last_reason = reason or last_reason + end + end + return nil, last_reason or "text-not-found" +end + +---@param document table +---@param xp string +---@return string +local function normalizedXP(document, xp) + if type(document.getNormalizedXPointer) ~= "function" then return xp end + local ok, normalized = pcall(document.getNormalizedXPointer, document, xp) + if ok and type(normalized) == "string" and normalized ~= "" then return normalized end + return xp +end + +---@param document table +---@param xp string +---@return integer|nil +local function pageOf(document, xp) + if type(document.getPageFromXPointer) ~= "function" then return nil end + local ok, page = pcall(document.getPageFromXPointer, document, xp) + if ok and tonumber(page) then return tonumber(page) end + return nil +end + +--- 把云端注解定位到当前打开的文档;返回**全量**(含未定位)。 +--- +--- 返回 nil 表示「本次不应用」:无文档 / html_path 缺失或文件不在 / 文档不是这本书。 +--- core 的 applySnapshot 见到 nil 会直接放弃,绝不覆盖 doc_settings —— 这条比多画几条更重要。 +--- 未定位条目只打 `kavita_unlocated`、不写占位坐标,merge 才不会把它误判成「远端已删」。 +--- +--- 复用放在最前:同一 `kavita_id` 已有 pos0/pos1 且仍通过 isXPointerInDocument 的, +--- 直接用旧坐标,避免每次开书重算(也避免文本微调后坐标抖动)。 +--- +---@param document table|nil 已打开的 crengine 文档 +---@param annotations table[] pull 落的原始条目 +---@param html_path string|nil 已落盘的 epub 路径(只查存在性,绝不读 ZIP 字节) +---@param current table[]|nil 阅读器当前注解 +---@return table[]|nil +function Source:localizeAnnotations(document, annotations, html_path, current) + if type(document) ~= "table" + or type(document.getTextFromXPointer) ~= "function" + or type(document.isXPointerInDocument) ~= "function" then + return nil + end + if type(html_path) ~= "string" or html_path == "" then return nil end + -- html_path 就是 core 传进来的 ui.document.file;两者不一致说明这次快照不是这本书的 + -- (派生笔记 / 切书竞态),宁可不动,也不要把这本书的坐标写到另一本书的 doc_settings。 + if type(document.file) == "string" and document.file ~= "" and document.file ~= html_path then + return nil + end + if require("libs/libkoreader-lfs").attributes(html_path, "mode") ~= "file" then return nil end + if type(annotations) ~= "table" then return {} end + + local reusable = {} + for _idx, item in ipairs(type(current) == "table" and current or {}) do + if type(item) == "table" and item.kavita_id and type(item.pos0) == "string" + and type(item.pos1) == "string" and inDocument(document, item.pos0) + and inDocument(document, item.pos1) then + local key = tostring(item.kavita_id) + reusable[key] = reusable[key] or item + end + end + + local out, unlocated, last_reason = {}, 0, nil + for _idx, item in ipairs(annotations) do + local ann = item + if type(item) == "table" then + -- 浅拷贝:定位只补坐标,pull 落的字段(备注 / 颜色 / 时间)原样带住。 + ann = {} + for key, value in pairs(item) do ann[key] = value end + local saved = item.kavita_id and reusable[tostring(item.kavita_id)] or nil + if saved then + ann.pos0, ann.pos1 = saved.pos0, saved.pos1 + ann.page = saved.page or saved.pos0 + ann.pageno = saved.pageno or pageOf(document, saved.pos0) + ann.kavita_unlocated = nil + else + local located, reason = locateAnnotation(document, ann) + if located then + local pos0 = normalizedXP(document, located.pos0) + local pos1 = normalizedXP(document, located.pos1) + ann.pos0, ann.pos1 = pos0, pos1 + -- page 填 pos0 字符串(照抄本地真实条目):数字会被 normalize 当成分页文档。 + ann.page = pos0 + ann.pageno = pageOf(document, pos0) + ann.kavita_unlocated = nil + else + ann.pos0, ann.pos1, ann.page, ann.pageno = nil, nil, nil, nil + ann.kavita_unlocated = true + unlocated = unlocated + 1 + last_reason = reason or last_reason + end + end + end + out[#out + 1] = ann + end + + -- 失败只记一条汇总,别让一本定位不了的书刷满日志。 + if unlocated > 0 then + logger.warn("kavita annotation localize failed", html_path, + unlocated .. "/" .. #annotations, last_reason or "text-not-found") + end + return out +end + +--- 颜色槽位 → KOReader 颜色名(01 §Answer):Kavita 只存用户调色板的槽位序号, +--- api key 客户端读不到 palette,按索引约定映射;越界 / 未知回落 yellow(0)。颜色不参与同一性。 +local SLOT_COLORS = { [0] = "yellow", [1] = "green", [2] = "blue", [3] = "orange", [4] = "purple" } + +---@param slot any +---@return string +local function slotColor(slot) + return SLOT_COLORS[tonumber(slot) or 0] or "yellow" +end + +--- Kavita AnnotationDto → notes payload 条目(spec §3.1 / §3.2)。 +--- 只落数据,不算坐标:`page` / `pos0` / `pos1` 是开书时 localizeAnnotations 的产物(05 §3)。 +--- `pageNumber` 只落成本地定位提示(0-based spine):`locateAnnotation` 用它挑 DocFragment, +--- update 时 Kavita 服务端忽略这个字段,推送坐标仍用现算的 `anchor.pageNumber`。 +---@param dto table +---@return table|nil +local function annotationPayload(dto) + -- 没有 id 才真的对不上任何本地条目(update / delete 的唯一依据),直接丢。 + if dto.id == nil or dto.id == "" then return nil end + local text = dto.selectedText + -- 没有选中文本的条目(Kavita 自己也不许这么建)画不出来,但**保留成未定位占位**: + -- 它的 id 必须进远端全量集合,否则 mergeAnnotations 会把本地带该 id 的那条当成「远端已删」抹掉。 + local blank = type(text) ~= "string" or Text.trim(text) == "" + if blank then text = "" end + local drawer + if not blank then drawer = "lighten" end + -- note 与 kavita_note 必须来自同一次读回:两侧一旦有差异,推送侧每轮都会判「备注改过」。 + -- 空备注落 nil,不落 "":KOReader 的 getBookmarkType 把 "" 当真值(`if bookmark.note then + -- return "note"`),默认 bookmarks_items_text_type = "note" 会把这条渲染成空行。 + -- 本地高亮本来就是 nil;sameNote(nil, "") 仍判等,推送侧不会误判「改过」。 + local note = Annotation.noteText(dto.comment, dto.commentHtml, dto.commentPlainText) + if note == "" then note = nil end + -- createdUtc 是真正的 UTC;解析不出(如 0001 占位)回退当前时间,只影响显示 / 排序。 + local created = utcTime(dto.createdUtc) + return { + datetime = os.date("%Y-%m-%d %H:%M:%S", created or os.time()), + drawer = drawer, + color = slotColor(dto.selectedSlotIndex), + text = text, + note = note, + pageNumber = tonumber(dto.pageNumber) or 0, + kavita_id = dto.id, + kavita_note = note, + kavita_comment = dto.comment, + kavita_comment_html = dto.commentHtml, + kavita_slot = dto.selectedSlotIndex, + kavita_spoiler = dto.containsSpoiler, + kavita_modified = dto.lastModifiedUtc, + kavita_xpath = dto.xPath, + kavita_ending_xpath = dto.endingXPath, + kavita_unlocated = blank or nil, + } +end + +--- 当前用户 id:注解列表在账号开了「查看他人注解」时会混入别人的条目, +--- 拉取必须按 `ownerUserId` 收窄,否则本地落一堆别人的划线、推送删改还会整批 400。 +--- 取不到(老版本 / 无权限)就降级为不过滤并记日志:多看到自己的不会丢数据,漏过滤别人的才会误删。 +---@param source KavitaSource +---@param cb fun(owner_id: integer|nil) +---@return HttpJob +local function ownerIdAsync(source, cb) + if source._owner_id ~= nil then return SourceBase.defer(cb, source._owner_id) end + return source.client:json("GET", "/api/Users/me", nil, nil, function(data, err) + local id = type(data) == "table" and tonumber(data.id) or nil + if not id then + logger.warn("kavita annotation owner unknown; pull without owner filter", err) + return cb(nil) + end + source._owner_id = id + cb(id) + end) +end + +--- 开书时全量拉取云端 epub 注解(spec §3.4):只落数据、不定位,坐标留给开书时的文档。 +--- 每章一次 `GET /api/Annotation/all`(单文件 epub 即一本书一个 chapter),与推送各发一次、不做缓存。 +--- `pageNumber` 是 localizeAnnotations 的 spine 提示,不是坐标:update 时服务端忽略它, +--- 推送仍用现算的 `anchor.pageNumber`(spec §8.4)。 +--- `authoritative` 恒 false:远端为空不代表本地该清空,删除语义不归这里。 +--- 失败回 `cb(nil, err)`,notes 表快照原样(离线开书只记日志)。 +---@param identity BookIdentity +---@param cb fun(annotations: table[]|nil, err: string|nil, meta: {authoritative: boolean}|nil) +---@return { cancel: fun() } +function Source:pullNotesAsync(identity, cb) + local job, cancelled = nil, false + local function finish(annotations, err, meta) + if not cancelled then cb(annotations, err, meta) end + end + job = self:entry(identity, function(entry, err) + if cancelled then return end + if not entry then return finish(nil, err) end + -- 非 epub 没有 Kavita 注解(与推送侧短路一致):零请求。 + if entry.format ~= "epub" then return finish({}, nil, { authoritative = false }) end + job = ownerIdAsync(self, function(owner_id) + if cancelled then return end + job = Annotation.listByChapter(self.client, entry.chapterId, owner_id, function(list, lerr) + if cancelled then return end + if not list then return finish(nil, lerr) end + local annotations = {} + for _idx, dto in ipairs(list) do + local annotation = annotationPayload(dto) + if annotation then annotations[#annotations + 1] = annotation end + end + finish(annotations, nil, { authoritative = false }) + end) + end) + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +--- Kavita 的 highlightCount 按 UTF-16 码元计。 +---@param s string +---@return integer +local function utf16Length(s) + local n = 0 + for ch in s:gmatch(Text.UTF8_CHAR) do n = n + (#ch == 4 and 2 or 1) end + return n +end + +--- 这一条要不要推:没 id 的本地新划线,或备注与上次同步的基线不同。 +--- 书签(没有 drawer)与墓碑不走这里。 +---@param ann table +---@return boolean +local function needsPush(ann) + if not (ann.drawer and type(ann.pos0) == "string" and type(ann.text) == "string") then return false end + if not ann.kavita_id then return true end + return not Annotation.sameNote(ann.note, ann.kavita_note) +end + +---@param annotations table[] +---@return table[] +function Source:resetAccountAnnotations(annotations) + for index = #annotations, 1, -1 do + local item = annotations[index] + if item.kavita_deleted then + table.remove(annotations, index) + else + item.kavita_id, item.kavita_note, item.kavita_modified = nil, nil, nil + end + end + return annotations +end + +--- 划线推到 Kavita:先按章对账一次,再逐条新建 / 更新,远端 id 原地回填给核心落库。 +--- +--- 幂等的真相源是「每次推送前按章拉一遍远端注解」,payload 里的 kavita_id 只是快路径: +--- 上传期间用户又划线(stale)、workdir 清空、pos0 漂移都靠下一轮对账自愈,不需要本地映射文件。 +--- 全有或全无:任一写请求失败就整批报错留脏(已建成的条目下轮按内容键认领,不会重复建)。 +--- 先写后删(spec §9.4):墓碑的 id 先从对账列表里剔掉(防同键认领),全部写成功后再一次 bulk-delete。 +---@param identity BookIdentity +---@param annotations table[] +---@param cb fun(ok: boolean|nil, err: string|nil, data: { pushed: integer, adopted: integer, conflicts: integer, deleted: integer }|nil) +---@return { cancel: fun() } +function Source:pushNotesAsync(identity, annotations, cb) + local job, cancelled = nil, false + job = self:entry(identity, function(entry, err) + if cancelled then return end + if not entry then return cb(nil, err) end + if entry.format ~= "epub" then return cb(true, nil, { pushed = 0, deleted = 0 }) end + local path = downloaded(self.id, identity.stable_id) + + -- 墓碑(kavita_deleted + id)不推、也不许被认领:删了又原地划一条同键的, + -- 认领会把它挂到马上要删的那条上。 + local tombstoned, pending = {}, {} + for _idx, ann in ipairs(annotations) do + local dead_id = ann.kavita_deleted and tonumber(ann.kavita_id) + if dead_id then + tombstoned[dead_id] = true + elseif needsPush(ann) then + pending[#pending + 1] = ann + end + end + -- 墓碑单独一批也要能推(删除不需要 create/update);两样都没有才算零请求。 + local delete_ids = {} + for id in pairs(tombstoned) do delete_ids[#delete_ids + 1] = id end + table.sort(delete_ids) + if #pending == 0 and #delete_ids == 0 then + -- 无可推:与「真推成功」区分开,核心才不会把 changed 谎报给首页。 + return cb(true, nil, { pushed = 0, adopted = 0, conflicts = 0, deleted = 0 }) + end + + -- 锚点先全部算好:有一条找不回段落就整批不发(空 xPath 会让一批失败项在远端挤成同键)。 + local plans = {} + for _idx, ann in ipairs(pending) do + local anchor = Position.anchor(ann.text, ann.pos0, path) + if not anchor or not anchor.xPath or anchor.xPath == "" then + return cb(nil, T(_("划线无法定位,本轮暂不推送:%1"), ann.text)) + end + plans[#plans + 1] = { ann = ann, anchor = anchor } + end + + job = ownerIdAsync(self, function(owner_id) + if cancelled then return end + -- 一批只对一次账:GET 失败宁可不推,也不盲建重复。 + job = Annotation.listByChapter(self.client, entry.chapterId, owner_id, function(list, lerr) + if cancelled then return end + if not list then return cb(nil, lerr) end + local remote, by_id = {}, {} + for _idx, item in ipairs(list) do + local id = tonumber(item.id) + if id and not tombstoned[id] then + remote[#remote + 1] = item + by_id[id] = item + end + end + + --- 认领远端那条:回填 id / 坐标 / 原值,后续 update 才有原值可回传。 + --- **不碰 kavita_note 基线**:本地备注还是空的(远端文本要等 pull 才进 note), + --- 这时候把远端备注记成基线,下一轮就会把「本地空」判成用户清空 → update 掉网页作者的内容。 + --- 基线只在真的写成功、或本地文本已经与远端相同时才补。 + ---@param ann table 本地条目(原地改写) + ---@param hit table 远端 DTO + local function adopt(ann, hit) + ann.kavita_id = tonumber(hit.id) + ann.kavita_xpath, ann.kavita_ending_xpath = hit.xPath, hit.endingXPath + ann.kavita_comment, ann.kavita_comment_html = hit.comment, hit.commentHtml + ann.kavita_slot, ann.kavita_spoiler = hit.selectedSlotIndex, hit.containsSpoiler + end + + local pushed, adopted, conflicts, index = 0, 0, 0, 0 + local step + + --- 把本批墓碑从 payload 数组里摘掉:核心随后按这个数组回写快照,出列才算数。 + local function dropTombstones() + for i = #annotations, 1, -1 do + local ann = annotations[i] + local id = ann.kavita_deleted and tonumber(ann.kavita_id) + if id and tombstoned[id] then table.remove(annotations, i) end + end + end + + --- 先写后删:全部 create / update 成功才发一次 bulk-delete(body = 裸 id 数组)。 + --- 200 ⇒ 墓碑出列;400 ⇒ 重拉一次该章确认真实状态后收尾(不无限重试); + --- 其余失败 ⇒ 整批 cb(nil),快照留脏、墓碑保留,下轮重试。 + local function finishBatch() + if #delete_ids == 0 then + return cb(true, nil, { pushed = pushed, adopted = adopted, + conflicts = conflicts, deleted = 0 }) + end + job = self.client:json("POST", "/api/Annotation/bulk-delete", nil, delete_ids, + function(_data, derr, code) + if cancelled then return end + if code and code >= 200 and code < 300 then + dropTombstones() + return cb(true, nil, { pushed = pushed, adopted = adopted, + conflicts = conflicts, deleted = #delete_ids }) + end + -- 400 是「id 不存在 / 不是你的 / 服务端拒绝」的同一分支:删除本身幂等, + -- 重拉一次按真实列表收尾,绝不循环重试。 + if code ~= 400 then + return cb(nil, derr or _("Kavita 注解删除失败")) + end + job = Annotation.listByChapter(self.client, entry.chapterId, owner_id, + function(fresh, ferr) + if cancelled then return end + if not fresh then + return cb(nil, ferr or _("Kavita 注解删除后复核失败")) + end + local alive = {} + for _idx, item in ipairs(fresh) do + alive[tonumber(item.id)] = true + end + local gone = 0 + for _idx, id in ipairs(delete_ids) do + if alive[id] then + logger.warn("kavita annotation delete rejected; drop tombstone", id) + else + gone = gone + 1 + end + end + dropTombstones() + cb(true, nil, { pushed = pushed, adopted = adopted, + conflicts = conflicts, deleted = gone }) + end) + end) + end + + --- 发一次 create / update;成功回填,失败整批收摊。 + ---@param ann table + ---@param anchor table Position.anchor 的结果 + ---@param kind string "create" | "update" + ---@param target table|nil update 的远端 DTO + local function send(ann, anchor, kind, target) + local note = ann.note or "" + local wire = Annotation.toRemote(note) + local body = { + id = kind == "update" and tonumber(target.id) or nil, + chapterId = entry.chapterId, volumeId = entry.volumeId, + libraryId = entry.libraryId, seriesId = entry.seriesId, + ownerUserId = 0, + xPath = anchor.xPath, endingXPath = anchor.endingXPath, + selectedText = ann.text, + pageNumber = anchor.pageNumber or Position.spine(ann.pos0) or 0, + highlightCount = utf16Length(ann.text), + comment = wire.comment, commentHtml = wire.commentHtml, + -- 未改动的两个可写字段回传远端原值,否则一次 update 就把颜色 / 剧透清成默认。 + selectedSlotIndex = tonumber(ann.kavita_slot) or 0, + containsSpoiler = ann.kavita_spoiler == true, + } + local api = kind == "create" and "/api/Annotation/create" or "/api/Annotation/update" + job = self.client:json("POST", api, nil, body, function(data, perr) + if cancelled then return end + local new_id = data and tonumber(data.id) + -- update 本来就带着 id:2xx 就认,回查也只可能命中同一条,不会重复建。 + if not new_id and kind == "update" then new_id = tonumber(target.id) end + if new_id then + ann.kavita_id = new_id + ann.kavita_xpath, ann.kavita_ending_xpath = anchor.xPath, anchor.endingXPath + ann.kavita_note = note + pushed = pushed + 1 + return step() + end + if not data then return cb(nil, perr) end + -- create 回了空体(反代吞掉 DTO):只查**同一轮**对账列表(§8.3,一批一次 GET), + -- 命中才认成功;仍是 200 不算成功。本轮列表是创建前取的,通常查不到 → 留脏, + -- 下轮对账按 key 认领这条已建成的,不会重复建。 + local hit = Annotation.match(remote, { + chapterId = entry.chapterId, xPath = anchor.xPath, + endingXPath = anchor.endingXPath, selectedText = ann.text, + }) + if not hit then return cb(nil, _("Kavita 未确认注解已创建")) end + adopt(ann, hit) + ann.kavita_note = note + pushed = pushed + 1 + step() + end) + end + + --- 逐条判定:有 id 走冲突表与坐标守卫,无 id 先按键认领,认不到才新建。 + --- 跳过是纯本地判断,用循环推进,避免连续跳过时递归堆栈。 + step = function() + while true do + if cancelled then return end + index = index + 1 + local plan = plans[index] + if not plan then + return finishBatch() + end + local ann, anchor = plan.ann, plan.anchor + local note = ann.note or "" + local id = tonumber(ann.kavita_id) + local current = id and by_id[id] + if id then + -- 有 id 但远端没了 = 网页端删了:不重建、不复活(拉取侧按 dropped 出列)。 + if current then + -- 坐标守卫:update 改不了坐标,锚点漂了硬发会把备注写到旧位置。 + local drifted = (ann.kavita_xpath and ann.kavita_xpath ~= "" + and ann.kavita_xpath ~= anchor.xPath) + or (ann.kavita_ending_xpath and ann.kavita_ending_xpath ~= "" + and ann.kavita_ending_xpath ~= anchor.endingXPath) + if drifted then + logger.warn("kavita annotation anchor drifted; skip update", id, + ann.kavita_xpath, anchor.xPath) + else + local base = ann.kavita_note + local remote_note = Annotation.noteText(current.comment, current.commentHtml, + current.commentPlainText) + if base == nil then + -- 没有基线(刚认领 / 老 payload):本地有备注就是真实编辑,整条替换; + -- 空则什么都不写,等 pull 把远端文本连同基线一起采纳。 + if Annotation.sameNote(note, remote_note) then + if not Annotation.sameNote(note, "") then ann.kavita_note = note end + elseif not Annotation.sameNote(note, "") then + return send(ann, anchor, "update", current) + end + -- 没改备注就不写:远端怎么变都交给 pull 采纳。 + elseif not Annotation.sameNote(note, base) then + if Annotation.sameNote(remote_note, base) then + return send(ann, anchor, "update", current) + elseif Annotation.sameNote(remote_note, note) then + -- 两边改成了同一段:只补基线,不再白写一次。 + ann.kavita_note = note + else + -- 远端赢:本地改动留在 kavita_local_note 备查,下轮 pull 采纳远端文本。 + ann.kavita_local_note = note + conflicts = conflicts + 1 + logger.warn("kavita annotation overridden by remote", id) + end + end + end + end + else + local hit = Annotation.match(remote, { + chapterId = entry.chapterId, xPath = anchor.xPath, + endingXPath = anchor.endingXPath, selectedText = ann.text, + }) + if not hit then + return send(ann, anchor, "create") + end + adopt(ann, hit) + local remote_note = Annotation.noteText(hit.comment, hit.commentHtml, + hit.commentPlainText) + -- 首次认领:本地空 / 与远端相同 → 只采纳 id,不覆盖网页作者的备注。 + -- 基线只在本地确实有这段文本时才补,否则下一轮会把「本地空」当成用户清空。 + if not Annotation.sameNote(note, "") then + if Annotation.sameNote(note, remote_note) then + ann.kavita_note = note + else + return send(ann, anchor, "update", hit) + end + end + -- 只认领 id、没写远端:算 adopted(写了的只算 pushed)。 + adopted = adopted + 1 + end + end + end + step() + end) + end) + end) + return { cancel = function() + cancelled = true + job:cancel() + end } +end + +function Source:bookReviewsAsync(identity, cb) + local series_id = splitId(identity.stable_id) + local ref = { source_id = self.id, stable_id = series_id } + return require("book.review_cache").pageAsync(ref, "book", 0, function(done) + return self.client:json("GET", "/api/Metadata/series-detail-plus", + { seriesId = tonumber(series_id) }, nil, function(wire, err) + if not wire then done(nil, err); return end + done(require("moonsource_kavita.mapper").bookReviewPage(wire, series_id)) + end) + end, cb) +end + +return { meta = meta, new = new, DEFAULT_HEARTBEAT_INTERVAL = DEFAULT_HEARTBEAT_INTERVAL } diff --git a/moonsource-kavita.koplugin/moonsource_kavita/stats.lua b/moonsource-kavita.koplugin/moonsource_kavita/stats.lua new file mode 100644 index 0000000..412ba8a --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/stats.lua @@ -0,0 +1,417 @@ +--[[-- +Kavita 阅读统计纯核心:reading-history 条目 + 身份 / 时区上下文 → reading_stats 行与替换指令。 + +条目是「会话 × 系列」切片。日 / 时归属按服务端给的 UTC 时刻(`startTimeUtc`)在**设备本地时区** +自行分桶:展示端(SQLite `localtime`、`os.date`)用的是同一个进程时区,两边同一真源才对得上账。 +服务端 `localDate` 是它按请求的 `TimeZoneId` 预先算的日期,映射不上时回退 UTC 会把整段挪一天, +所以它只当拿不到 `startTimeUtc` 时的兜底。 + +时长取各章活动段之和(有效阅读时间,不含会话内空档,与本地计时语义一致); +条目级与聚合结果 `<= 0` 一律丢弃 —— Kavita 会把「打开没读」的会话也写一条 0 时长记录。 + +身份粒度由调用方给(`volumes`:本地目录章数):1 章的单卷系列记 series 行,多卷系列记 +`seriesId:chapterId` 卷行。一条会话可以跨章(多卷)——时长 / 页数按章拆到各卷, +否则会把《2001》的时长记到《2010》头上。 + +账户日桶 `__kv:day:<当天零点>` 的页数按天**先求和再钳制**(`max(0, ·)`):服务端 pagesRead +实测有负数(退页),逐条钳制会让 +1 / -1 相抵的当天凭空多出 1 页。漫画不用 pagesRead 求和, +而是按最远进度算新推进的页数(见下),贡献本身已 >= 0。 + +账户时段桶 `__kv:hour:<整点>`:每条活动行的时长记在它起始时刻所在的那个本地整点(跨整点的活动行 +整体算起始小时,与「跨零点的会话整体算起始日」同一口径),供「阅读时段」图用;云端只有这一层 +粒度,再细就要按跨度分摊,而活动行的跨度含空档,分摊反而把空档算到隔壁小时。 + +阅读会话行(`cloud_session`):每个「会话 × 章」切片的起始时刻与时长单独落一行, +供书详情 / 统计页的「阅读记录」列出真的读了几点几分;时长不计入日 / 时段 / 总量行 +(那些桶已经包含它),只在 `sessionRows` 里读。页数(`event_count`)不另写记录类型: +核心从这一行累加单书页数。页数口径分两种: + +- 漫画(Image / Archive):`event_count` = **本次新推进的页数**,不是 `pagesRead`。 + `pagesRead` 是「这次翻了多少页」,重读会重复计入(实测 194 页的卷求和 284); + 按最远进度算,`SUM(event_count)` 才等于读到的最远页码(≤ 总页数),与 Kavita 的百分比一致。 + 所以漫画还要补 `page = endPage` / `total_pages = 卷级总页数`。 +- epub / PDF:`pagesRead` 是唯一页数来源,`event_count` 照旧;页坐标仍为 0。 + +全量重拉:日桶 / 时段桶 / 总量行按「前缀 + 覆盖到最后观测桶的时间窗」替换;单书行按「上次 ∪ 本次 +身份」精确替换,顺带清掉身份漂移(单卷 ↔ 多卷、系列重建)遗留的孤儿行。 + +纯函数(无文件 / 网络 IO、无全局状态,只经 `logger` 写日志):目录、卷名与「上次身份」由源钩子经 ctx 注入。 + +@module moonsource_kavita.stats +--]] + +local logger = require("utils.log") + +local Stats = {} + +local DAY_PREFIX = "__kv:day:" +local HOUR_PREFIX = "__kv:hour:" +local TOTAL_ID = "__kv:total" +--- 单条阅读会话(会话 × 章切片)——只给「阅读记录」列表用,不参与任何时长汇总。 +local SESSION_RECORD = "cloud_session" + +--- features/clock/init.lua 的 Clock.TIMEZONES 的 19 项 POSIX 串 → Kavita 的 TimeZoneId。 +--- 只查表:不读 /etc/localtime(KOReader 设备上不保证存在,读到的也未必是用户选的时区), +--- 不按偏移猜地区。映射不上就按 UTC 请求 —— 只影响 `localDate` 这个兜底(正常条目都带 +--- `startTimeUtc`,分日 / 分时按设备本地时区自行换算,见 utcEpoch / dayStart)。 +local IANA_BY_POSIX = { + ["HST10"] = "Pacific/Honolulu", + ["AKST9AKDT,M3.2.0,M11.1.0"] = "America/Anchorage", + ["PST8PDT,M3.2.0,M11.1.0"] = "America/Los_Angeles", + ["MST7MDT,M3.2.0,M11.1.0"] = "America/Denver", + ["CST6CDT,M3.2.0,M11.1.0"] = "America/Chicago", + ["EST5EDT,M3.2.0,M11.1.0"] = "America/New_York", + ["<-03>3"] = "America/Sao_Paulo", + ["UTC0"] = "UTC", + ["GMT0BST,M3.5.0/1,M10.5.0"] = "Europe/London", + ["CET-1CEST,M3.5.0,M10.5.0/3"] = "Europe/Berlin", + ["EET-2EEST,M3.5.0/3,M10.5.0/4"] = "Europe/Athens", + ["MSK-3"] = "Europe/Moscow", + ["<+04>-4"] = "Asia/Dubai", + ["IST-5:30"] = "Asia/Kolkata", + ["<+07>-7"] = "Asia/Bangkok", + ["CST-8"] = "Asia/Shanghai", + ["JST-9"] = "Asia/Tokyo", + ["AEST-10AEDT,M10.1.0,M4.1.0/3"] = "Australia/Sydney", + ["NZST-12NZDT,M9.5.0,M4.1.0/3"] = "Pacific/Auckland", +} + +--- 设备时钟的 POSIX 串 → IANA。未知 / 空串(跟随系统)回退 UTC 并记日志。 +---@param posix string|nil 进程 TZ 环境变量(时钟功能按设置写入) +---@return string +function Stats.ianaTimezone(posix) + local iana = type(posix) == "string" and IANA_BY_POSIX[posix] or nil + if iana then return iana end + logger.warn("kavita stats timezone unmapped, fallback to UTC", posix) + return "UTC" +end + +--- 合成 reading_stats 行;云端默认没有页坐标,page / total_pages 恒为 0。 +--- 漫画(Image / Archive)的会话行由调用方在拿到 endPage / totalPages 后补上。 +---@param source_id string +---@param stable_id string +---@param record_type string +---@param start_time number +---@param duration number +---@param last_time number +---@return BookStatsRow +local function statsRow(source_id, stable_id, record_type, start_time, duration, last_time) + return { + source_id = source_id, + stable_id = stable_id, + record_type = record_type, + page = 0, + start_time = start_time, + duration = duration, + total_pages = 0, + last_time = last_time, + } +end + +--- 服务端 localDate("2026-10-15T00:00:00")→ 当天设备本地零点;解不出返回 nil。 +--- 只取日期部分:时刻是被请求时区下的零点,换算成设备本地同一日期即可。 +---@param local_date any +---@return number|nil +local function localMidnight(local_date) + local y, m, d = tostring(local_date):match("^(%d%d%d%d)-(%d%d)-(%d%d)") + if not y then return nil end + return os.time({ year = tonumber(y), month = tonumber(m), day = tonumber(d), hour = 0 }) +end + +--- 服务端 UTC 时间戳("2026-10-15T23:51:47.4527045")→ 设备本地 epoch;解不出返回 nil。 +--- os.time 按进程 TZ(POSIX 串,自带夏令时规则)解释墙钟,所以先把 UTC 墙钟当本地算出 E', +--- 再补回一个用 E' 处的本地偏移量的差。偏移的表必须重建:os.date 给的表带 `isdst`,直接回喂 +--- os.time 会把夏令时钉成标准时、整整差一小时(跨夏令时切换的时区实测过)。 +---@param text any +---@return number|nil +local function utcEpoch(text) + local y, mo, d, h, mi, s = tostring(text):match("^(%d%d%d%d)%-(%d%d)%-(%d%d)T(%d%d):(%d%d):(%d%d)") + if not y then return nil end + local as_local = os.time({ year = tonumber(y), month = tonumber(mo), day = tonumber(d), + hour = tonumber(h), min = tonumber(mi), sec = tonumber(s) }) + if not as_local then return nil end + local u = os.date("!*t", as_local) + local back = os.time({ year = u.year, month = u.month, day = u.day, hour = u.hour, min = u.min, sec = u.sec }) + return as_local + os.difftime(as_local, back) +end + +--- 设备本地时区的当日零点。`isdst` 取自本地分解,跨切换的零点不会被挪一小时。 +---@param epoch number +---@return number +local function dayStart(epoch) + local t = os.date("*t", epoch) + return os.time({ year = t.year, month = t.month, day = t.day, hour = 0, isdst = t.isdst }) +end + +--- 时段桶键:`day` 那天的、`epoch` 所在小时。跨零点的活动行仍记在条目那天(取小时、换日期), +--- 这样「日页面逐格之和 = 当日日桶」,不会出现某天的时段和比标题少一截。 +---@param day number 当日零点 +---@param epoch number 活动行起始时刻 +---@return number +local function hourBucket(day, epoch) + local d = os.date("*t", day) + local a = os.date("*t", epoch) + return os.time({ year = d.year, month = d.month, day = d.day, hour = a.hour, isdst = a.isdst }) +end + +--- 本地目录章数:1 = 单卷(读在 series 行),>1 = 多卷(读在卷行);拿不到返回 nil。 +--- 数字 / 字符串键都收:状态文件里的 seriesId 可能两种写法。 +---@param volumes table +---@param series_id string +---@return number|nil +local function volumeCount(volumes, series_id) + local count = volumes[series_id] + if count == nil then count = volumes[tonumber(series_id) or series_id] end + count = tonumber(count) + if not count or count < 1 then return nil end + return count +end + +--- 漫画章行:页数贡献要按身份排完序才能算(见 fromHistory 里「漫画最远进度」一段)。 +---@class KavitaComicSlice +---@field identity string 卷身份(单卷 = seriesId,多卷 = seriesId:chapterId) +---@field day number 该活动行归属的本地零点(推进的页数记进这一天) +---@field epoch number|nil 会话行 start_time(也是排序键) +---@field order number 回包顺序,仅用于同一时刻的稳定排序 +---@field duration number 秒;`> 0` 才发行 +---@field page number 原始 endPage(会话行的进度坐标) +---@field end_page number 钳到总页数后的结束页(算推进页数用) +---@field total_pages number 卷级总页数 + +---@class KavitaStatsContext +---@field source_id string 本源 id(写进每行) +---@field fetched_at number|nil 拉取时刻(缺省 now);写进行 / 桶的 last_time +---@field volumes table|nil seriesId → 本地目录章数(1 = 单卷) +---@field seen string[]|nil 上次拉取的身份列表(用于清身份漂移遗留的孤儿行) + +--- reading-history 条目 → reading_stats 行 + 替换指令 + 本次身份。 +---@param entries table[]|nil reading-history 条目(wire 已解码),通常为分页合并后的全量 +---@param ctx KavitaStatsContext +---@return { rows: BookStatsRow[], replace: BookStatsPullReplace, identities: string[] } +function Stats.fromHistory(entries, ctx) + ctx = ctx or {} + local source_id = ctx.source_id + local fetched_at = tonumber(ctx.fetched_at) or os.time() + local volumes = ctx.volumes or {} + + local rows = {} + local book_days = {} ---@type table> 身份 → 日 → 秒 + local book_totals = {} ---@type table + local day_durations = {} ---@type table + local day_pages = {} ---@type table + local hour_durations = {} ---@type table 整点 → 秒(账户时段桶) + local last_day = 0 ---@type number 本次回包里最晚的观测日(零点) + local last_hour = 0 ---@type number 本次回包里最晚的观测整点 + local comic_slices = {} ---@type KavitaComicSlice[] 漫画章行,算完进度贡献再落行 + local identities, known, warned_series = {}, {}, {} + + --- 记下本次出现的身份。零时长条目也记:它上次可能有行,靠 replace.books 清掉。 + local function noteIdentity(identity) + if identity and not known[identity] then + known[identity] = true + identities[#identities + 1] = identity + end + end + + for _idx, entry in ipairs(type(entries) == "table" and entries or {}) do + local series_id = entry.seriesId ~= nil and tostring(entry.seriesId) or nil + local count = series_id and volumeCount(volumes, series_id) or nil + if not count then + -- 判不出单卷 / 多卷的系列整体跳过:身份是错的比缺行更糟(源钩子侧也会记)。 + if series_id and not warned_series[series_id] then + warned_series[series_id] = true + logger.warn("kavita stats skip series without volume info", series_id) + end + else + -- 有 UTC 时刻就按设备本地分日 / 分时;没有才退服务端按请求时区算好的 localDate(无小时)。 + local anchor = utcEpoch(entry.startTimeUtc) + local day + if anchor then + day = dayStart(anchor) + else + day = localMidnight(entry.localDate) + if day then logger.warn("kavita stats entry without usable startTimeUtc", series_id) end + end + if not day then + logger.warn("kavita stats entry without usable day", series_id) + else + if day > last_day then last_day = day end + local chapters = type(entry.chapters) == "table" and entry.chapters or {} + -- 漫画才有真实页坐标:Kavita 的 seriesFormat 0 = Image、1 = Archive 是图片页; + -- epub(3)的 chapter.pages 是 spine / 阅读单元(6 万字的书 32 个),PDF(4)同理, + -- 都不是渲染页,填进 page / total_pages 会让详情页的「读了多少页」变成假的。 + -- seriesFormat 在条目顶层,不在 chapter 上(实测响应见 history-7453-all.json)。 + local fmt = tonumber(entry.seriesFormat) + local comic = fmt == 0 or fmt == 1 + local entry_duration = 0 + for _ci, chapter in ipairs(chapters) do + entry_duration = entry_duration + (tonumber(chapter.durationSeconds) or 0) + end + -- 单卷:没有章行也读在 series 上;多卷:没有 chapterId 就拆不出来,跳过该章。 + if count == 1 then noteIdentity(series_id) end + local contributes = entry_duration > 0 + for _ci, chapter in ipairs(chapters) do + local identity = series_id + if count > 1 then + identity = chapter.chapterId ~= nil + and (series_id .. ":" .. tostring(chapter.chapterId)) or nil + if not identity then + logger.warn("kavita stats chapter without chapterId", series_id) + end + end + noteIdentity(identity) + if identity then + local duration = tonumber(chapter.durationSeconds) or 0 + -- 章活动行自己的起始时刻(时段桶 / 会话行 / 漫画排序共用);拿不到就退回条目起始时刻。 + local chapter_epoch = utcEpoch(chapter.startTimeUtc) or anchor + if contributes and duration > 0 then + local days = book_days[identity] + if not days then + days = {} + book_days[identity] = days + end + days[day] = (days[day] or 0) + duration + book_totals[identity] = (book_totals[identity] or 0) + duration + day_durations[day] = (day_durations[day] or 0) + duration + -- 时段桶:按活动行自己的起始小时;拿不到就退回条目起始时刻。 + if chapter_epoch then + local bucket = hourBucket(day, chapter_epoch) + hour_durations[bucket] = (hour_durations[bucket] or 0) + duration + if bucket > last_hour then last_hour = bucket end + end + end + if comic then + -- 漫画的页数不能边遍历边累加:`pagesRead` 是「这次翻了多少页」,重读会重复计入。 + -- 先收集,按身份(卷)× 起始时刻排序后再算「本次新推进的页数」。 + local total_pages = math.max(0, tonumber(chapter.totalPages) or 0) + local page = math.max(0, tonumber(chapter.endPage) or 0) + comic_slices[#comic_slices + 1] = { + identity = identity, + day = day, + epoch = chapter_epoch, + order = #comic_slices + 1, + duration = duration, + page = page, + -- 只有拿到总页数才钳:缺总页数时别凭空假设一个上界。 + end_page = total_pages > 0 and math.min(page, total_pages) or page, + total_pages = total_pages, + } + elseif contributes then + if duration > 0 and chapter_epoch then + -- 阅读会话行:详情「阅读记录」按真实起止时间列出这一段。 + local session = statsRow(source_id, identity, SESSION_RECORD, + chapter_epoch, duration, fetched_at) + session.event_count = math.max(0, tonumber(chapter.pagesRead) or 0) + rows[#rows + 1] = session + end + day_pages[day] = (day_pages[day] or 0) + (tonumber(chapter.pagesRead) or 0) + end + end + end + end + end + end + + -- 漫画:按身份(卷)分别按起始时刻升序走一遍,只留「比此前更远」的页数 —— 这样重读不再重复计入, + -- 跳读也只按推进到哪算,`SUM(event_count)` = 读到的最远页码(天然 ≤ 总页数),与 Kavita 百分比一致。 + -- 回包可能是新→旧(服务端按时间倒序),所以必须排序,不能依赖遍历顺序。 + table.sort(comic_slices, function(a, b) + if a.identity ~= b.identity then return a.identity < b.identity end + local ae, be = a.epoch or 0, b.epoch or 0 + if ae ~= be then return ae < be end + return a.order < b.order + end) + local reached = {} ---@type table 身份(卷)→ 此前到达的最远页码 + for _idx, slice in ipairs(comic_slices) do + local previous = reached[slice.identity] or 0 + local advance = slice.end_page - previous + if advance < 0 then advance = 0 end + if slice.end_page > previous then reached[slice.identity] = slice.end_page end + -- 零时长章行不发行(会话行说的是「这一段读了多久」),但推进照样算进当天页数: + -- 否则这次跳读会从当天页数里消失,而后续会话又因 reached 更高而少算。 + day_pages[slice.day] = (day_pages[slice.day] or 0) + advance + -- 零时长章行也要发行:Kavita 的会话是「两次进度写入之间」,只写一次(开书 / 关书各一次) + -- 就是 0 秒,但推进的页数是真的。丢掉它,详情页「已读页数 / 上次阅读」会整段消失 + -- (另一台设备刚读的那一卷尤其明显)。既没时长又没推进的(打开没翻)才跳过。 + if slice.epoch and (slice.duration > 0 or advance > 0) then + local session = statsRow(source_id, slice.identity, SESSION_RECORD, + slice.epoch, slice.duration, fetched_at) + session.event_count = advance + -- page = endPage(读到哪一页,核心 reading_stats.page 的语义);total_pages 取卷级, + -- 多卷系列汇总处取 MAX。pagesRead = 0 是合法值(打开没翻页),不是缺数据。 + session.page = slice.page + session.total_pages = slice.total_pages + rows[#rows + 1] = session + end + end + + for identity, days in pairs(book_days) do + for day, duration in pairs(days) do + if duration > 0 then + rows[#rows + 1] = statsRow(source_id, identity, "book_day", day, duration, fetched_at) + end + end + end + for identity, duration in pairs(book_totals) do + if duration > 0 then + rows[#rows + 1] = statsRow(source_id, identity, "book_total", fetched_at, duration, fetched_at) + end + end + local grand_total = 0 + for day, duration in pairs(day_durations) do + grand_total = grand_total + duration + if duration > 0 then + local row = statsRow(source_id, DAY_PREFIX .. tostring(day), "day", day, duration, fetched_at) + row.event_count = math.max(0, day_pages[day] or 0) + rows[#rows + 1] = row + end + end + for hour, duration in pairs(hour_durations) do + if duration > 0 then + rows[#rows + 1] = statsRow(source_id, HOUR_PREFIX .. tostring(hour), "hour", hour, duration, fetched_at) + end + end + if grand_total > 0 then + rows[#rows + 1] = statsRow(source_id, TOTAL_ID, "total", 0, grand_total, fetched_at) + end + + -- 稳定输出:持久化顺序与对账都别受 pairs 遍历顺序影响。 + table.sort(rows, function(a, b) + if a.record_type ~= b.record_type then return a.record_type < b.record_type end + if a.start_time ~= b.start_time then return a.start_time < b.start_time end + return a.stable_id < b.stable_id + end) + table.sort(identities) + + local books, book_known = {}, {} + local function addBook(stable_id) + if type(stable_id) == "string" and stable_id ~= "" and not book_known[stable_id] then + book_known[stable_id] = true + books[#books + 1] = stable_id + end + end + for _idx, stable_id in ipairs(type(ctx.seen) == "table" and ctx.seen or {}) do addBook(stable_id) end + for _idx, identity in ipairs(identities) do addBook(identity) end + table.sort(books) + + return { + rows = rows, + replace = { + mode = "ranges", + ranges = { + -- 全量重拉:窗口一直连到最后观测日 / 整点的桶止,清掉本次回包里已消失的桶。 + -- 上界不能只取拉取时刻:服务端「当天」可能晚于设备本地的拉取时刻(设备为负偏移), + -- 桶零点会落在窗口外、清不掉(残留到下一轮)。 + { stable_prefix = DAY_PREFIX, from_ts = 0, to_ts = math.max(fetched_at, last_day + 86399) }, + { stable_prefix = HOUR_PREFIX, from_ts = 0, to_ts = math.max(fetched_at, last_hour + 3599) }, + { stable_prefix = TOTAL_ID, from_ts = 0, to_ts = 0 }, + }, + -- 上次 ∪ 本次:身份漂移后旧身份不再出现在回包里,只能按它精确清。 + books = books, + }, + -- 交回给源持久化:下次拉取当「上次身份」用。 + identities = identities, + } +end + +return Stats diff --git a/moonsource-kavita.koplugin/moonsource_kavita/version.lua b/moonsource-kavita.koplugin/moonsource_kavita/version.lua new file mode 100644 index 0000000..25b37f6 --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/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/moonsource-kavita.koplugin/moonsource_kavita/volume_list.lua b/moonsource-kavita.koplugin/moonsource_kavita/volume_list.lua new file mode 100644 index 0000000..7dc16db --- /dev/null +++ b/moonsource-kavita.koplugin/moonsource_kavita/volume_list.lua @@ -0,0 +1,1157 @@ +--[[-- +Kavita 卷列表:选卷阅读 + 缓存管理(04 A1–A9 / 07 A1–A7)。 + +一行 = 一卷;点行阅读,行尾「状态字 + 一个图标钮」管该卷的缓存,标题栏左钮开批量预设菜单 +(整部 / 从当前进度 / 后 N 卷)。 +状态全部在打开 / 每秒轮询时现算:`Cache.status` 是内存索引,`queue_state` 按服务器过滤, +本地已读 / 在读取 toc 的 pagesRead(不按卷调 resume_page,只给有本地进度的行补「待同步」)。 +开缓存后同一批卷登记成一条 passive 后台任务(`cache_task`):顶栏能看到、缓存期间不自动休眠、 +关掉页面后由它报完成;页面自己的进度框还在时任务静音,收尾只提示一次。 + +不改 `ui/themes/widgets/list` 与 `row`:行尾控件塞 `item.widget`,靠 KOReader 的 +「先子件后自身」事件顺序吃掉点按(04 A9)。批量预设复用主题 `list` 当二级菜单 +(04 A9 的 C 变体,ticket 16),不新增控件。 + +@module moonsource_kavita.volume_list +--]] + +local _ = require("l10n").get("moonsource_kavita") +local T = require("ffi/util").template +local Cache = require("moonsource_kavita.cache") +local CacheTask = require("moonsource_kavita.cache_task") +local ContinuePoint = require("moonsource_kavita.continue_point") + +-- 主题组件一律函数内 require:没有 kamare 的安装(旧「已下载」列表)不该为了加载 +-- 这个模块把整套 ui.themes.widgets 拉进来,source.lua 的既有测试也不装它们。 + +---@class KavitaVolumeListOptions +---@field fallback? fun(entry: table): string|nil +---@field cover? fun(entry: table): string|nil, table|nil + +local VolumeList = {} + +--- 与 source.lua 的 online() 同口径:系统联网状态。 +---@return boolean +local function online() + return require("ui/network/manager"):isConnected() +end + +---@param text string|nil +---@param timeout number|nil 秒,缺省 2 +local function toast(text, timeout) + if not text then return end + require("ui.themes.widgets.toast"):new{ text = text, timeout = timeout or 2 }:show() +end + +--- 同步批量删除期间的忙碌窗(05 A):与设置页共用同一套实现。 +---@param title string +---@param ids any[] +---@return boolean|nil, string|nil, string|nil +local function deleteBusy(title, ids) + return require("moonsource_kavita.busy").run(title, function() return Cache.delete(ids) end) +end + +---@param capabilities table|nil +---@param name string +---@return boolean +local function has(capabilities, name) + return type(capabilities) == "table" and capabilities[name] == true +end + +--- 队列里还有会自己往前走的项(失败项会留在 entries 里,直到重试)。 +---@param queue table|nil +---@return boolean +local function queueRunning(queue) + for _key, entry in pairs(type(queue) == "table" and queue.entries or {}) do + if entry.state ~= "failed" then return true end + end + return false +end + +---@param entry table|nil +---@return integer|nil +local function entryPercent(entry) + local total = tonumber(entry and entry.bytes_total) or 0 + local done = tonumber(entry and entry.bytes_done) or 0 + if total <= 0 or done <= 0 then return nil end + return math.floor(done / total * 100) +end + +--- 目录条目 → 章 id 列表(批量动作的统一取数)。 +---@param entries table[] +---@return any[] +local function chapterIds(entries) + local ids = {} + for _idx, entry in ipairs(entries or {}) do ids[#ids + 1] = entry.chapterId end + return ids +end + +--- 队列里这一章的条目;缺 queue 能力时用本地入队记忆顶着(只表示「已排队」,没有百分比)。 +---@param ctx table +---@param chapter_id any +---@return table|nil +local function queuedEntry(ctx, chapter_id) + local key = tostring(chapter_id) + local queued = ctx.entries[key] + if queued then return queued end + if not ctx.queue_capable and ctx.pending[key] then return { state = "queued" } end + return nil +end + +--- 本地阅读状态:已读 / 在读 / nil(与书架百分比同源,不额外调 resume_page)。 +---@param entry table +---@return "read"|"reading"|nil +local function readState(entry) + local pages = tonumber(entry.pages) or 0 + local read = tonumber(entry.pagesRead) or 0 + if pages > 0 and read >= pages then return "read" end + if read > 0 then return "reading" end + return nil +end + +--- 本地卷进度:ProgressDB 的卷行由阅读器关闭时写回,比 toc 快照(Kavita pagesRead,TTL 6 小时)新。 +--- 读完一卷马上回列表时,服务端 / toc 里可能还是「读到 117/196」,不能因此把已读完的卷当成在读, +--- 否则「后 N 卷」会从这卷重新缓存。只认卷行(seriesId:chapterId),容器聚合行不参与。 +---@param series Book|nil +---@param toc table[] +---@return table states +---@return table rows ProgressDB 原始卷行(fraction / page / updated_at) +local function localReadStates(series, toc) + local out, rows = {}, {} + if type(series) ~= "table" or series.source_id == nil or series.stable_id == nil then + return out, rows + end + local series_id = tostring(series.stable_id) + if series_id:find(":", 1, true) then return out, rows end + local ProgressDB = require("book.progress_db") + local all = ProgressDB.list(series.source_id, series_id) + for _idx, entry in ipairs(toc) do + local stable_id = series_id .. ":" .. tostring(entry.chapterId) + local row = all[stable_id] + if row then rows[tostring(entry.chapterId)] = row end + local fraction = row and tonumber(row.fraction) or 0 + if fraction >= 1 then + out[tostring(entry.chapterId)] = "read" + elseif fraction > 0 then + out[tostring(entry.chapterId)] = "reading" + end + end + return out, rows +end + +--- 显示用阅读状态:kamare 的三源判定优先(离线读完也算已读),再退回 toc 的 pagesRead, +--- 最后用本地卷进度补上 toc 快照之后才读完 / 刚开读的卷。 +---@param ctx table +---@param entry table +---@return "read"|"reading"|nil +local function readOf(ctx, entry) + local cid = tostring(entry.chapterId) + if ctx.reads and ctx.reads[cid] then return "read" end + local local_state = ctx.local_reads and ctx.local_reads[cid] + if local_state == "read" then return "read" end + return readState(entry) or local_state +end + +--- 打开 / 轮询时的一份只读快照。 +---@param toc table[] +---@param series_id any Kavita seriesId:一次 chapters(series_id) 取整列的缓存事实 +---@param memo table|nil 上一次的 resume_page 结果:轮询复用,别每秒为整列扫 journal +---@param pending table|nil 本地入队记忆:缺 queue 能力时没有别的「排队」来源 +---@param local_reads table|nil 本地卷进度(ProgressDB),见 localReadStates +---@param opts { skip_resumes: boolean|nil }|nil 目标计算不需要「待同步」时跳过逐卷 resume_page +---@return table +local function scan(toc, series_id, memo, pending, local_reads, opts) + local probe = Cache.probe() + local capabilities = probe.ok and (probe.capabilities or {}) or {} + local queue_capable = has(capabilities, "queue") + local queue, queue_code = Cache.queueState() + -- 能力缺失或这一次读不到队列状态,都只能算「没有可用的队列」: + -- 不能拿空结果当「都下完了」(02 A4)。 + if not queue_capable or type(queue) ~= "table" then + queue_capable = false + queue = nil + end + -- unknown_server:缓存状态整块不显示,只剩阅读状态(02 A9)。 + local show_cache = probe.ok + and (has(capabilities, "status") or has(capabilities, "chapters")) + and queue_code ~= "unknown_server" + local statuses, reads = {}, {} + local resumes = memo or {} + + -- 04 A2:一次 chapters(series_id) 取代逐章 status;返回的 read 已经合并了 + -- journal 与下载快照,toc 的服务端 pagesRead 在这里补上第三源。 + local plan, plan_by_id + if show_cache and has(capabilities, "chapters") and series_id ~= nil then + local result = Cache.chapters(series_id) + if type(result) == "table" then + plan = result + plan_by_id = {} + for _idx, item in ipairs(plan) do + plan_by_id[tostring(item.chapterId)] = item + end + end + end + + if show_cache then + for _idx, entry in ipairs(toc) do + local cid = tostring(entry.chapterId) + local item = plan_by_id and plan_by_id[cid] + if item then + if readState(entry) == "read" then item.read = true end + reads[cid] = item.read == true + statuses[cid] = { state = item.stale and "stale" or "complete", bytes = item.bytes } + elseif not plan_by_id and has(capabilities, "status") then + -- 旧增强版没有 chapters:退回逐章 status。 + statuses[cid] = Cache.status(entry.chapterId) + end + -- 06 A4:只有读过 / 已缓存的行才可能有「待同步」;结果按章记忆, + -- 每秒轮询不再重复读 journal(false = 查过没有)。 + if not (opts and opts.skip_resumes) and resumes[cid] == nil then + local cached = Cache.isCached(statuses[cid]) + if cached or readState(entry) ~= nil then + resumes[cid] = Cache.resumePage(entry.chapterId) or false + end + end + end + end + pending = pending or {} + -- 缺 queue 时 kamare 的索引已报 complete 才把本地排队记忆撤掉; + -- 仍排队的继续显示「已排队」,不能假装已经缓存。 + if not queue_capable then + for cid in pairs(pending) do + if Cache.isCached(statuses[cid]) then pending[cid] = nil end + end + end + return { + capabilities = capabilities, + show_cache = show_cache, + queue_capable = queue_capable, + queue = queue, + entries = CacheTask.queueEntries(queue), + pending = pending, + paused = CacheTask.queuePaused(queue), + statuses = statuses, + reads = reads, + plan = plan, + plan_by_id = plan_by_id, + resumes = resumes, + local_reads = local_reads, + offline = not online(), + } +end + +---@param toc table[] +---@param rows table +---@param ctx table +---@return ContinueTarget|nil +local function pickTarget(toc, rows, ctx) + return ContinuePoint.pick(toc, { + fraction = function(entry) + local row = rows[tostring(entry.chapterId)] + return row and tonumber(row.fraction) + end, + updated_at = function(entry) + local row = rows[tostring(entry.chapterId)] + return row and tonumber(row.updated_at) + end, + page = function(entry) + local row = rows[tostring(entry.chapterId)] + if row and row.page and row.total_pages then + return { page = row.page, total = row.total_pages } + end + end, + complete = function(entry) return readOf(ctx, entry) == "read" end, + }) +end + +--- 与卷列表共用本地进度及 kamare 完成状态,不发网络请求。 +---@param series Book +---@param toc table[] +---@return ContinueTarget|nil +function VolumeList.continueTarget(series, toc) + local states, rows = localReadStates(series, toc) + -- 目标只看「完成/进度」;逐卷 resume_page 是列表行显示「待同步」才需要的。 + local ctx = scan(toc, series.stable_id, nil, nil, states, { skip_resumes = true }) + return pickTarget(toc, rows, ctx) +end + +--- 一行要显示的状态字与动作;优先级见 04 A2。 +---@param ctx table +---@param entry table +---@return table +local function rowState(ctx, entry) + local cid = tostring(entry.chapterId) + local queued = queuedEntry(ctx, entry.chapterId) + local status = ctx.statuses[cid] + local cached = Cache.isCached(status) + local read = readOf(ctx, entry) + local text, icon + if queued then + local percent = entryPercent(queued) + if ctx.paused and percent then + text = T(_("已暂停 %1%"), percent) + icon = "play_arrow" + elseif queued.state == "failed" then + text = _("缓存失败") + icon = "refresh" + elseif ctx.paused then + -- 排队还没开始下载就暂停:没有百分比可写。 + text = _("已暂停") + icon = "play_arrow" + else + text = percent and T(_("下载中 %1%"), percent) or _("已排队") + icon = "pause" + end + elseif cached then + local base = read == "read" and _("已读") or read == "reading" and _("在读") + text = base and T(_("%1 · 已缓存"), base) or _("已缓存") + icon = "delete" + else + local base = read == "read" and _("已读") or read == "reading" and _("在读") or _("未缓存") + text = ctx.offline and T(_("%1 · 离线"), base) or base + icon = "download" + end + -- 06 A4:kamare 还有位置没推上去(结果由 scan 按章记忆,轮询不重复取)。 + local resume = ctx.resumes[cid] + local status_code = type(resume) == "table" and resume.status or nil + if status_code == "pending" or status_code == "failed" then + text = T(_("%1 · 待同步"), text) + end + return { text = text, icon = icon, queued = queued, status = status, read = read, cached = cached } +end + +--- 图标钮:40×40 逻辑像素的触摸区。禁用态仍要能点出解释(置灰 + toast), +--- 所以只把外观交给 Button 的 enabled,点按另接一个回调。 +---@param icon string +---@param callback fun()|nil +---@param disabled_tap fun()|nil +---@return table +local function actionButton(icon, callback, disabled_tap) + local Button = require("ui.themes.widgets.button") + local Theme = require("ui.themes") + local button = Button:new{ + icon = icon, variant = "ghost", + width = Theme.px(40), height = Theme.px(40), + enabled = disabled_tap == nil, + callback = callback, + } + if disabled_tap then + button.onTapThemeButton = function() + disabled_tap() + return true + end + end + return button +end + +--- 行尾控件:状态字 + 动作钮。给了 widget 就不再传 mandatory(list.lua 的约定)。 +---@param ctx table +---@param entry table +---@param model table +---@param actions table +---@return table +local function tailWidget(ctx, entry, model, actions) + local HorizontalGroup = require("ui/widget/horizontalgroup") + local Text = require("ui.themes.widgets.text") + local group = HorizontalGroup:new{ align = "center" } + group[#group + 1] = Text.line("caption", model.text) + local icon = model.icon + local enabled = true + local disabled_tap + if icon == "download" then + enabled = has(ctx.capabilities, "enqueue") + elseif icon == "delete" then + enabled = has(ctx.capabilities, "delete") + if enabled and Cache.isChapterOpen(entry.chapterId) then + enabled = false + disabled_tap = function() + toast(Cache.message("chapter_open")) + end + end + elseif icon == "refresh" or icon == "pause" or icon == "play_arrow" then + enabled = has(ctx.capabilities, "queue_control") + end + if enabled then + group[#group + 1] = actionButton(icon, actions[icon]) + elseif disabled_tap then + group[#group + 1] = actionButton(icon, nil, disabled_tap) + end + return group +end + +--- 删除确认正文(07 A1 / A4 / A6):释放体积、离线不可读、下载中会取消。 +---@param entry table +---@param bytes number|nil +---@param downloading boolean|nil +---@return string +function VolumeList.deleteText(entry, bytes, downloading) + local text = T(_("删除「%1」的缓存?将释放 %2。"), entry.title, Cache.sizeText(bytes or 0)) + text = text .. "\n" .. _("删除后离线不可读。") + if downloading then + text = text .. "\n" .. _("删除会取消这一卷的下载。") + end + return text +end + +--- 单卷删除确认(04 A6 / 07 A1、A4)。 +---@param entry table +---@param model table +---@param done fun() +---@param pending table|nil 本地入队记忆:删成功后这一卷不再是「已排队」 +local function confirmDelete(entry, model, done, pending) + local Confirm = require("ui.themes.widgets.confirm") + local bytes = type(model.status) == "table" and tonumber(model.status.bytes) + or type(model.queued) == "table" and tonumber(model.queued.bytes_done) or 0 + Confirm:new{ + title = _("删除缓存"), + text = VolumeList.deleteText(entry, bytes, model.queued ~= nil), + ok_text = _("删除"), + ok_callback = function() + local ok, code, message = Cache.delete({ entry.chapterId }) + if ok then + if pending then pending[tostring(entry.chapterId)] = nil end + else + toast(Cache.message(code, message)) + end + done() + end, + }:show() +end + +--- 卷名清单:≤3 卷列全名,多了只写第一卷 + 总数。 +---@param entries table[] +---@return string +local function namesText(entries) + if #entries <= 3 then + local names = {} + for _idx, entry in ipairs(entries) do names[#names + 1] = entry.title end + return table.concat(names, "、") + end + return T(_("%1 等 %2 卷"), entries[1].title, #entries) +end + +--- 「缓存整部」的对象:未缓存未排队的入队;队列里失败的走 queue_retry +--- (07 A4;enqueue 对仍在队里的失败项只会回 already_queued)。 +---@param ctx table +---@param toc table[] +---@return table[] enqueue, table[] retry +local function batchTargets(ctx, toc) + local enqueue, retry = {}, {} + for _idx, entry in ipairs(toc) do + local cid = tostring(entry.chapterId) + local status = ctx.statuses[cid] + local cached = Cache.isCached(status) + local queued = queuedEntry(ctx, entry.chapterId) + if not cached then + if queued then + if queued.state == "failed" then retry[#retry + 1] = entry end + else + enqueue[#enqueue + 1] = entry + end + end + end + return enqueue, retry +end + +--- 批量预设的起点:第一个未读完的卷;全部都读完就退化为整部(ticket 16)。 +---@param ctx table +---@param toc table[] +---@return integer +local function resumeIndex(ctx, toc) + for idx, entry in ipairs(toc) do + if readOf(ctx, entry) ~= "read" then return idx end + end + return 1 +end + +--- 未读的卷:没读完的都算(包括正在读的那一卷);已读的跳过。 +--- 与「缓存后 N 卷」不同:这里不是连续后缀,中间已读的卷不会被打包进来。 +---@param ctx table +---@param toc table[] +---@return table[] +local function unreadVolumes(ctx, toc) + local out = {} + for _idx, entry in ipairs(toc) do + if readOf(ctx, entry) ~= "read" then out[#out + 1] = entry end + end + return out +end + +--- 从 first 起取 count 卷(缺省到末卷);越界截断。 +---@param toc table[] +---@param first integer +---@param count integer|nil +---@return table[] +local function volumeRange(toc, first, count) + local out = {} + local last = count and math.min(#toc, first + count - 1) or #toc + for idx = first, last do out[#out + 1] = toc[idx] end + return out +end + +--- 批量确认框正文:卷数 / 卷名 / 峰值 / 可用 / 完成后剩余(04 A4 + 07 A6)。 +---@param entries table[] 要入队的卷 +---@param estimate table Cache.estimate 结果 +---@param retry_count integer +---@param paused boolean +---@return string +local function enqueueText(entries, estimate, retry_count, paused) + local lines = { T(_("将缓存:%1"), namesText(entries)) } + lines[#lines + 1] = T(_("预计占用 %1(峰值)"), Cache.sizeText(estimate.bytes)) + lines[#lines + 1] = T(_("设备可用 %1"), Cache.sizeText(estimate.available)) + local left = (tonumber(estimate.available) or 0) - (tonumber(estimate.bytes) or 0) + lines[#lines + 1] = T(_("完成后剩余 %1"), Cache.sizeText(math.max(0, left))) + if retry_count > 0 then lines[#lines + 1] = T(_("另有 %1 卷失败将重试"), retry_count) end + -- 07 A5:enqueue 会隐式恢复整条队列,先讲清楚。 + if paused then lines[#lines + 1] = _("当前下载已暂停,开始缓存会恢复整个队列") end + return table.concat(lines, "\n") +end + +--- 重试确认框正文:逐条 lastError 用 07 A7 的表映射,不显示原始堆栈。 +---@param entries table[] +---@param ctx table +---@return string +local function retryText(entries, ctx) + local lines = { T(_("将重试:%1"), namesText(entries)) } + for _idx, entry in ipairs(entries) do + local queued = ctx.entries[tostring(entry.chapterId)] + local reason = Cache.failureText(type(queued) == "table" and queued.last_error or nil) + if reason then lines[#lines + 1] = T(_("%1:%2"), entry.title, reason) end + end + return table.concat(lines, "\n") +end + +--- 空间不足:就地换成清理提示,主按钮只 toast(07 A6)。 +---@param message string +local function confirmSpace(message) + local Confirm = require("ui.themes.widgets.confirm") + Confirm:new{ + title = _("空间不足"), + text = message .. "\n" .. _("清理后再下载"), + ok_text = _("去清理空间"), + ok_callback = function() toast(message) end, + }:show() +end + +--- 暂停原因 → 文案与主按钮(07 A5)。low_space 不给继续。 +local PAUSE_REASONS = { + user = { text = _("已暂停"), resume = true }, + restored = { text = _("已暂停(启动恢复)"), resume = true }, + offline = { text = _("已暂停(断网)"), resume = true }, + wifi = { text = _("已暂停(仅 Wi-Fi 下载)"), resume = true }, + network = { text = _("已暂停(连续下载失败)"), resume = true, retry = true }, + low_space = { text = _("空间不足,已暂停"), resume = false }, +} + +--- 打开卷列表。返回 list 控件(测试与「部分失败」后重画都要用)。 +---@param series Book +---@param toc table[] +---@param cb fun(entry: table) +---@param opts KavitaVolumeListOptions|nil +---@return table +function VolumeList.pick(series, toc, cb, opts) + opts = type(opts) == "table" and opts or {} + -- 缺 queue 能力时没有队列状态可读,只能在本地记「这一卷已经入队」(02 A4)。 + local pending = {} + -- 本地卷进度只取一次:列表开着的时候不会在后台读书,轮询没必要每秒重扫 ProgressDB。 + local local_reads, local_progress = localReadStates(series, toc) + local ctx = scan(toc, series and series.stable_id, nil, pending, local_reads) + local continue_target = pickTarget(toc, local_progress, ctx) + + --- 卷封面(按 chapterId 记忆):volume-cover 走属主源,离线退回系列封面 / 本地缓存。 + local cover_cache = {} + local function coverFor(entry) + local key = tostring(entry.chapterId) + local hit = cover_cache[key] + if hit then return hit.url, hit.headers end + local url, headers + if opts.cover then url, headers = opts.cover(entry) end + if not url and series and series.source_id and series.stable_id then + local source, err = require("source.registry").resolve(series.source_id) + if not source then error(err) end + local req = source:coverRequest({ + source_id = series.source_id, + stable_id = tostring(series.stable_id) .. ":" .. key, + }) + if req then url, headers = req.url, req.headers end + end + local out = { url = url, headers = headers } + cover_cache[key] = out + return out.url, out.headers + end + + --- 卷内页数进度(只给在读的卷;已读完的卷不显示低进度)。 + local function progressText(entry) + if readOf(ctx, entry) ~= "reading" then return nil end + local row = local_progress[tostring(entry.chapterId)] + local pages = tonumber(entry.pages) or 0 + local read = tonumber(entry.pagesRead) or 0 + local fraction = (row and tonumber(row.fraction)) or (pages > 0 and read / pages or 0) + if fraction <= 0 or fraction >= 1 then return nil end + local page = (row and tonumber(row.page)) or math.floor(fraction * pages + 0.5) + local total = (row and tonumber(row.total_pages)) or pages + return T(_("第 %1/%2 页 · %3%"), page, total, math.floor(fraction * 100 + 0.5)) + end + + --- 行副标题:在读的卷给页数;「上次翻阅」且不是主线时补一个标记。 + local function subtitleOf(entry) + local sub = progressText(entry) + if continue_target and continue_target.browsed == entry then + local mark = _("上次翻阅") + sub = sub and T(_("%1 · %2"), sub, mark) or mark + end + return sub + end + local chosen = false + local list + local dialog + -- 行、重画与确认框互相引用(重画要重建行,行要弹确认框),先声明再赋值。 + local item, items, refresh, confirmRetry, confirmEnqueue, resumeQueue, startProgress, stopPolling + + ---@param entry table + ---@return table + item = function(entry) + local label = ContinuePoint.label(entry, series and series.title) + local url, headers = coverFor(entry) + if not ctx.show_cache then + -- unknown_server / 缺 status:回到旧行为,只显示阅读状态(含旧的「已下载」)。 + local mandatory = opts.fallback and opts.fallback(entry) or nil + return { + text = label, value = entry, mandatory = mandatory, + subtitle = subtitleOf(entry), + image = url, image_w = 46, image_h = 64, image_headers = headers, + } + end + local model = rowState(ctx, entry) + local actions = {} + actions.download = function() confirmEnqueue({ entry }, {}) end + actions.delete = function() confirmDelete(entry, model, refresh, pending) end + actions.refresh = function() confirmRetry({ entry }) end + actions.pause = function() + local ok, code, message = Cache.queuePause() + -- 队列是全局的:行里的暂停作用于所有服务器的所有下载,明确告诉用户(04 A3)。 + if not ok then toast(Cache.message(code, message)) else toast(_("已暂停整个下载队列")) end + refresh() + end + actions.play_arrow = function() resumeQueue() end + local offline_uncached = ctx.offline and model.icon == "download" + and not model.queued and not model.cached + local row = { + text = label, + value = entry, + subtitle = subtitleOf(entry), + image = url, image_w = 46, image_h = 64, image_headers = headers, + widget = tailWidget(ctx, entry, model, actions), + } + -- 04 A7:离线未缓存的行仍可点,但只提示;不关窗,用户还能挑别的卷。 + if offline_uncached then + row.keep_open = true + row.callback = function() toast(Cache.message("offline_not_cached")) end + end + return row + end + + ---@return table[] + items = function() + local out = {} + for _idx, entry in ipairs(toc) do out[#out + 1] = item(entry) end + return out + end + + --- 重画:状态全在 kamare 的内存索引里,重扫一遍即可(列表停在原页)。 + ---@param reuse_resume boolean|nil 轮询用:复用 resume_page 的记忆 + refresh = function(reuse_resume) + ctx = scan(toc, series and series.stable_id, reuse_resume and ctx.resumes or nil, pending, + ctx.local_reads) + continue_target = pickTarget(toc, local_progress, ctx) + if list and not list.closed then list:setItems(items()) end + end + + ---@param entries table[] + ---@return boolean + local function enqueue(entries) + local ok, code, message, detail = Cache.enqueue(entries) + if ok then + -- 缺 queue 能力时靠这份记忆把行显示成「已排队」(02 A4)。 + for _idx, entry in ipairs(entries) do pending[tostring(entry.chapterId)] = true end + return true + end + toast(Cache.message(code, message, detail)) + return false + end + + ---@param entries table[] + ---@return boolean + local function retry(entries) + local ids = chapterIds(entries) + local ok, code, message = Cache.queueRetry(ids) + if ok then + for _idx, entry in ipairs(entries) do pending[tostring(entry.chapterId)] = true end + return true + end + toast(Cache.message(code, message)) + return false + end + + local timer + local batch + local startPolling + --- 这一批对应的后台任务句柄(登记不上 / 旧核没有 workers.tasks 时为 nil)。 + local cache_task + + --- 本批次的条目(按 chapterId 回到 toc)。 + ---@param ids integer[] + ---@return table[] + local function batchEntries(ids) + local out = {} + for _idx, id in ipairs(ids) do + for _i, entry in ipairs(toc) do + if tostring(entry.chapterId) == tostring(id) then out[#out + 1] = entry break end + end + end + return out + end + + --- 本批次里已经失败的卷(kamare 把失败项留在 entries 里)。 + ---@return table[] + local function failedEntries() + local out = {} + for _idx, entry in ipairs(batch and batchEntries(batch.ids) or {}) do + local queued = ctx.entries[tostring(entry.chapterId)] + if type(queued) == "table" and queued.state == "failed" then out[#out + 1] = entry end + end + return out + end + + stopPolling = function() + if timer then + require("ui/uimanager"):unschedule(timer) + timer = nil + end + end + + local function closeProgress() + if dialog and not dialog.closed then dialog:close() end + dialog = nil + end + + --- 本服务器范围内的聚合百分比;kamare 的 percent 是 0..1。 + ---@return number + local function aggregatePercent() + local percent = tonumber(ctx.queue and ctx.queue.percent) + if percent then return math.max(0, math.min(100, percent <= 1 and percent * 100 or percent)) end + local total = tonumber(ctx.queue and ctx.queue.bytes_total) or 0 + local done = tonumber(ctx.queue and ctx.queue.bytes_done) or 0 + if total <= 0 then return 0 end + return math.max(0, math.min(100, done / total * 100)) + end + + --- 进度框说明行:第几卷 / 共几卷 · 当前卷名。 + ---@return string + local function progressLine() + local total = batch and batch.total or 1 + local remaining = 0 + for _idx, id in ipairs(batch and batch.ids or {}) do + local queued = ctx.entries[tostring(id)] + if type(queued) == "table" and queued.state ~= "failed" then remaining = remaining + 1 end + end + local index = math.max(1, math.min(total, batch and batch.total - remaining + 1 or 1)) + local title + local current = ctx.queue and ctx.queue.current_chapter_id + if current ~= nil then + for _idx, entry in ipairs(toc) do + if tostring(entry.chapterId) == tostring(current) then title = entry.title break end + end + end + local line = T(_("正在缓存 %1/%2 卷"), index, total) + return title and T(_("%1 · %2"), line, title) or line + end + + --- 全部完成 / 只剩失败项:全成 toast,有失败给「部分失败」(04 A5)。 + local function finishDone() + local failed = failedEntries() + local total = batch and batch.total or 0 + closeProgress() + if #failed > 0 then + local lines = { T(_("%1 卷成功,%2 卷失败"), math.max(0, total - #failed), #failed) } + for _idx, entry in ipairs(failed) do + local queued = ctx.entries[tostring(entry.chapterId)] + local reason = Cache.failureText(type(queued) == "table" and queued.last_error or nil) + lines[#lines + 1] = T(_("%1:%2"), entry.title, reason or _("缓存失败")) + end + local Confirm = require("ui.themes.widgets.confirm") + Confirm:new{ + title = _("部分失败"), + text = table.concat(lines, "\n"), + ok_text = _("查看失败原因"), + cancel_text = _("关闭"), + ok_callback = refresh, + }:show() + else + toast(T(_("已缓存 %1 卷"), total)) + end + batch = nil + end + + --- 队列暂停:按 pause_reason 给文案与主按钮;low_space 不给继续(07 A5)。 + local function finishPaused() + local reason = ctx.queue and ctx.queue.pause_reason + local info = PAUSE_REASONS[reason] or { text = _("已暂停"), resume = true } + local failed = failedEntries() + closeProgress() + local Confirm = require("ui.themes.widgets.confirm") + Confirm:new{ + title = _("已暂停"), + text = info.text, + ok_text = info.resume and (info.retry and _("重试失败项并继续") or _("继续")) or _("去清理空间"), + cancel_text = _("关闭"), + ok_callback = function() + if not info.resume then + toast(_("空间不足,已暂停。清理后再下载")) + batch = nil + return + end + if info.retry and #failed > 0 then retry(failed) end + local ok, code, message = Cache.queueResume() + if not ok then + toast(Cache.message(code, message)) + return + end + local resumed = batch + batch = nil + if resumed then startProgress(resumed.ids, resumed.total) end + end, + cancel_callback = function() batch = nil end, + }:show() + end + + --- 每一拍:重画行,有进度框就更新 / 收尾;队列停住或暂停就不再排下一拍。 + local function tick() + timer = nil + -- 没有 queue 能力就没有进度可轮询,也绝不能凭「没有条目」宣布全部完成(02 A4)。 + if not ctx.queue_capable then return end + refresh(true) + if dialog then + if ctx.paused then + finishPaused() + elseif not queueRunning(ctx.queue) then + finishDone() + else + dialog:set(progressLine(), aggregatePercent()) + end + end + if queueRunning(ctx.queue) and not ctx.paused then + startPolling() + else + stopPolling() + end + end + + --- 起 1 秒轮询(已排过就不重复排)。列表自己发起的批次、打开列表时已有队列在跑、 + --- 从行尾恢复暂停的队列,都要靠它把「下载中 32%」刷成最终状态。 + startPolling = function() + if timer or not ctx.queue_capable then return end + timer = require("ui.guard").wrap("kavita volume list poll", tick) + require("ui/uimanager"):scheduleIn(1, timer) + end + + --- 进度框:1 秒轮询 queue_state(只看本服务器),后台运行不停队列。 + ---@param ids integer[] 本批次的章 id(入队 + 重试) + ---@param total integer 本批次的卷数 + startProgress = function(ids, total) + batch = { ids = ids or {}, total = total or #(ids or {}) } + -- 同一部书的这一批进「后台任务」:顶栏能看到、缓存期间不自动休眠、关掉页面后仍有完成提示。 + -- 页面自己的进度框还在时静音任务,避免收尾时两处同时提示(04 A5)。 + if ctx.queue_capable then + cache_task = CacheTask.track{ series = series, entries = batchEntries(batch.ids) } + if cache_task then cache_task.mute(true) end + end + local ProgressDialog = require("ui.themes.widgets.progress_dialog") + -- 缺 queue_control 时只留「后台运行」(02 A4)。 + local control = has(ctx.capabilities, "queue_control") + dialog = ProgressDialog:new{ + title = _("正在缓存"), + -- 缺 queue:没有百分比,只报「已排队」(02 A4)。 + text = ctx.queue_capable and T(_("正在缓存 %1/%2 卷"), 1, batch.total) or _("已排队"), + cancel_text = control and _("暂停") or nil, + on_cancel = control and function() + local ok, code, message = Cache.queuePause() + if not ok then toast(Cache.message(code, message)) end + refresh() + end or nil, + -- 关弹窗 ≠ 取消:队列继续跑,列表行继续按拍刷新(04 A5)。 + -- 此后由后台任务负责收尾提示,所以取消静音。 + on_background = function() + dialog = nil + if cache_task then cache_task.mute(false) end + end, + } + dialog:show() + refresh(true) + -- 没有 queue 就没有可轮询的进度;不排拍,也就不会从缺席的队列宣布完成。 + if not ctx.queue_capable then return end + startPolling() + end + + ---@param entries table[] + confirmRetry = function(entries) + local Confirm = require("ui.themes.widgets.confirm") + Confirm:new{ + title = _("重试缓存"), + text = retryText(entries, ctx), + ok_text = _("重试"), + ok_callback = function() + if retry(entries) then + startProgress(chapterIds(entries), #entries) + end + end, + }:show() + end + + --- 先 estimate 再画 04 A4 的确认框;空间不足就地换文案(07 A6)。 + ---@param to_enqueue table[] + ---@param to_retry table[] + confirmEnqueue = function(to_enqueue, to_retry) + local estimate, code, message = Cache.estimate(to_enqueue) + if type(estimate) ~= "table" then + toast(Cache.message(code, message)) + return + end + local reason = Cache.estimateMessage(estimate) + if reason then + if estimate.reason == "nothing_to_do" then toast(reason) else confirmSpace(reason) end + return + end + local count = tonumber(estimate.chapters) or #to_enqueue + local total = count + #to_retry + local Confirm = require("ui.themes.widgets.confirm") + Confirm:new{ + title = total == 1 and _("缓存这一卷") or T(_("缓存 %1 卷"), total), + text = enqueueText(to_enqueue, estimate, #to_retry, ctx.paused), + ok_text = _("开始缓存"), + ok_callback = function() + if not enqueue(to_enqueue) then return end + if #to_retry > 0 then retry(to_retry) end + local ids = chapterIds(to_enqueue) + for _idx, id in ipairs(chapterIds(to_retry)) do ids[#ids + 1] = id end + startProgress(ids, total) + end, + }:show() + end + + --- 恢复队列:低水位不给继续,连续失败先逐条重试失败项(07 A5)。 + resumeQueue = function() + local reason = type(ctx.queue) == "table" and ctx.queue.pause_reason or nil + if reason == "low_space" then + toast(_("空间不足,已暂停。清理后再下载")) + return + end + if reason == "network" then + local failed = {} + for _idx, entry in ipairs(toc) do + local queued = ctx.entries[tostring(entry.chapterId)] + if type(queued) == "table" and queued.state == "failed" then failed[#failed + 1] = entry end + end + if #failed > 0 then retry(failed) end + end + local ok, code, message = Cache.queueResume() + if not ok then + toast(Cache.message(code, message)) + else + -- 只恢复队列不会自己排拍:行尾点的继续也要开始刷新。 + startPolling() + end + refresh() + end + + --- 批量入口:三种范围共用 estimate 确认、进度框与失败重试;没有对象只 toast。 + ---@param entries table[] + local function runBatch(entries) + local to_enqueue, to_retry = batchTargets(ctx, entries) + if #to_enqueue == 0 and #to_retry == 0 then + toast(_("全部已缓存")) + return + end + if #to_enqueue == 0 then + confirmRetry(to_retry) + return + end + confirmEnqueue(to_enqueue, to_retry) + end + + --- 「缓存后 N 卷」:数值加减控件([+]/[-]),范围 1..剩余卷数,默认 3(不足 3 取剩余); + --- 越界由 volumeRange 截断兜底。 + local function promptNext() + local Spin = require("ui.themes.widgets.spin") + local first = resumeIndex(ctx, toc) + local max = math.max(1, #toc - first + 1) + Spin:new{ + title = _("缓存后 N 卷"), + fields = { + { value = math.min(3, max), min = 1, max = max, label = _("卷数") }, + }, + callback = function(count) + local n = math.floor(tonumber(count) or 0) + if n <= 0 then return end + runBatch(volumeRange(toc, first, n)) + end, + }:show() + end + + --- 清理本系列 / 本系列已读:同一份 chapters 快照出预览,确认后一次批量删除。 + ---@param filter "all"|"read" + ---@param title string + local function runCleanup(filter, title) + local plan = Cache.plan(ctx.plan or {}, filter) + if plan.chapters == 0 then + toast(filter == "read" and _("没有已读完的缓存") or _("没有可清理的缓存")) + return + end + local lines = { + filter == "read" + and T(_("将删除本系列 %1 卷已读完的缓存(约 %2)。"), plan.chapters, Cache.sizeText(plan.bytes)) + or T(_("将删除本系列 %1 卷缓存(约 %2)。"), plan.chapters, Cache.sizeText(plan.bytes)), + } + if plan.queued > 0 then + lines[#lines + 1] = T(_("会中止正在下载的 %1 卷,已下载的部分会被删除。"), plan.queued) + end + lines[#lines + 1] = _("阅读进度与 kamare journal 保留。") + require("ui.themes.widgets.confirm"):new{ + title = title, + text = table.concat(lines, "\n"), + ok_text = _("清理"), + cancel_text = _("取消"), + ok_callback = function() + local ok, code, message = deleteBusy(title, plan.ids) + if not ok then + toast(Cache.message(code, message)) + return + end + refresh() + local remaining = {} + for _idx, item in ipairs(ctx.plan or {}) do + remaining[tostring(item.chapterId)] = true + end + local left = 0 + for _idx, id in ipairs(plan.ids) do + if remaining[tostring(id)] then left = left + 1 end + end + if left > 0 then + toast(T(_("已清理 %1 卷,%2 卷未能删除"), plan.chapters - left, left), 3) + else + toast(T(_("已清理 %1 卷,释放约 %2"), plan.chapters, Cache.sizeText(plan.bytes)), 3) + end + end, + }:show() + end + + local can_clean = ctx.show_cache + and has(ctx.capabilities, "chapters") and has(ctx.capabilities, "delete") + + --- 标题栏左钮:批量操作菜单(缓存预设 + 系列清理,04 A9 的 C 变体)。 + local function openBatchMenu() + local Menu = require("ui.themes.widgets.list") + local items = { + { text = _("缓存整部"), value = "all" }, + { text = _("缓存未读"), value = "unread" }, + { text = _("缓存后 N 卷…"), value = "next" }, + } + if can_clean then + local read_plan = Cache.plan(ctx.plan or {}, "read") + local all_plan = Cache.plan(ctx.plan or {}, "all") + items[#items + 1] = { + text = _("清理本系列"), value = "clean_all", + mandatory = all_plan.chapters > 0 and T(_("%1 卷"), all_plan.chapters) or _("无"), + enabled = all_plan.chapters > 0, + } + items[#items + 1] = { + text = _("清理本系列已读"), value = "clean_read", + mandatory = read_plan.chapters > 0 and T(_("%1 卷"), read_plan.chapters) or _("无"), + enabled = read_plan.chapters > 0, + } + end + Menu:new{ + title = _("批量操作"), + items = items, + on_select = function(value) + if value == "all" then + runBatch(toc) + elseif value == "unread" then + local unread = unreadVolumes(ctx, toc) + -- 全部读完不是「全部已缓存」:文案要说得准确。 + if #unread == 0 then toast(_("没有未读的卷")) else runBatch(unread) end + elseif value == "next" then + promptNext() + elseif value == "clean_all" then + runCleanup("all", _("清理本系列")) + elseif value == "clean_read" then + runCleanup("read", _("清理本系列已读")) + end + end, + }:show() + end + + local can_batch = ctx.show_cache + and (has(ctx.capabilities, "enqueue") or has(ctx.capabilities, "queue_control") + or can_clean) + + --- 固定在标题栏下方的续读卡:点它直接开目标卷(跳过选卷)。 + local function continueCard(width) + local target = continue_target + if not target then return nil end + local title, subtitle = ContinuePoint.describe(target, series and series.title) + if target.kind == "done" then + subtitle = title + title = T(_("已读完 · 共 %1 卷"), #toc) + end + local url, headers = coverFor(target.entry) + return require("ui.themes.widgets.row").widget{ + width = width, + height = 112, + image = url, image_w = 62, image_h = 88, image_headers = headers, + title = title, + subtitle = subtitle, + callback = function() list:choose(item(target.entry)) end, + } + end + + list = require("ui.themes.widgets.list"):new{ + title = series.title or _("选择卷"), + items = items(), + header = continueCard, + row_height = 72, + left_icon = can_batch and "download" or nil, + left_callback = can_batch and openBatchMenu or nil, + on_select = function(entry) + chosen = true + cb(entry) + end, + -- 单选点按时先关窗、同一拍再 on_select:下一拍还没选中就是用户关掉了列表。 + close_callback = function() + -- 04 A8:关列表即停,不设常驻轮询。后台任务继续轮询并在收尾时提示。 + stopPolling() + if cache_task then cache_task.mute(false) end + require("ui/uimanager"):nextTick(function() + if not chosen then cb(nil) end + end) + end, + } + -- 打开列表时队列已经在跑(例如从书架 / 后台任务回来,不是本页发起的批次): + -- 不排拍的话行会永远停在打开那一瞬的「下载中 32%」。 + if queueRunning(ctx.queue) and not ctx.paused then startPolling() end + + --- 打开后刷新目录(点开系列时后台拉服务器最新进度):原地替换条目并重扫状态, + --- 列表停在原页;列表已关 / 回包为空则丢弃。 + ---@param fresh table[] 新目录(chapterId 与卷号顺序不变) + list.refreshToc = function(fresh) + if type(fresh) ~= "table" or fresh[1] == nil or list.closed then return end + for i = #toc, 1, -1 do toc[i] = nil end + for i, entry in ipairs(fresh) do toc[i] = entry end + local states, rows = localReadStates(series, toc) + ctx.local_reads, local_progress = states, rows + refresh(true) + end + return list +end + +return VolumeList diff --git a/tests/kavita/annotation_spec.lua b/tests/kavita/annotation_spec.lua new file mode 100644 index 0000000..ecf01a0 --- /dev/null +++ b/tests/kavita/annotation_spec.lua @@ -0,0 +1,211 @@ +--[[-- +extensions/moonsource-kavita.koplugin:注解线上形态(写入 / 读回)与同一性键。 + +备注在 Kavita 侧是 Quill Delta JSON(`comment`)+ Quill HTML(`commentHtml`), +纯文本 `commentPlainText` 由后端从 HTML 去标签算出来。拉取、推送、冲突判定必须 +共用这一套归一,否则同一段备注每次都会判「改过」→ 无限 update。 + +@module tests.moonsource_kavita.annotation_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local JsonStub = require("support.json_stub") + +-- 模块内部 require("json");这里给真实语义的往返桩(encode 出的串 decode 得回同一结构)。 +package.loaded["json"] = { encode = JsonStub.encode, decode = JsonStub.decode } + +local Annotation = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/annotation.lua") + +-- 读回:空值集合一律空串(漏判的后果不是显示花括号,而是 note 变成 "{}" → 无限 update)。 +Assert.eq(Annotation.noteText(nil), "") +Assert.eq(Annotation.noteText(""), "") +Assert.eq(Annotation.noteText(" "), "") +Assert.eq(Annotation.noteText("{}"), "") +Assert.eq(Annotation.noteText('{"ops":[]}'), "") +Assert.eq(Annotation.noteText('{"ops":[{"insert":"\\n"}]}'), "") +Assert.eq(Annotation.noteText('{"ops":[{"insert":" \\n"}]}'), "", "只含空白 insert 也是空") +Assert.eq(Annotation.noteText("null"), "") + +-- Delta:拼接字符串 insert,跳过 embed,忽略 attributes,剥掉末尾换行。 +Assert.eq(Annotation.noteText('{"ops":[{"insert":"一句话\\n"}]}'), "一句话") +Assert.eq( + Annotation.noteText('{"ops":[{"insert":"第一行\\n"},{"insert":"第二行","attributes":{"bold":true}},{"insert":"\\n"}]}'), + "第一行\n第二行" +) +Assert.eq( + Annotation.noteText('{"ops":[{"insert":"有图\\n"},{"insert":{"image":"x.png"}},{"insert":"\\n"}]}'), + "有图", + "非字符串 insert(图片等 embed)跳过" +) +Assert.eq(Annotation.noteText('{"ops":[{"insert":"a\\nb\\n"}]}'), "a\nb", "文内换行原样保留") + +-- 非 JSON 的 legacy 纯文本:原样返回(不能当空,也不能当 Delta 报错)。 +Assert.eq(Annotation.noteText("存量纯文本备注"), "存量纯文本备注") + +-- 优先级:commentHtml → commentPlainText → 解析 comment。 +Assert.eq(Annotation.noteText('{"ops":[{"insert":"delta\\n"}]}', "

html

", "plain"), "html") +Assert.eq(Annotation.noteText('{"ops":[{"insert":"delta\\n"}]}', "", "plain"), "plain") +Assert.eq(Annotation.noteText('{"ops":[{"insert":"delta\\n"}]}', " ", " "), "delta") + +-- commentHtml:块级边界转换行(后端 StripHtml 不插分隔,块之间会粘)。 +Assert.eq(Annotation.noteText(nil, "

第一段

第二段

", ""), "第一段\n第二段") +Assert.eq(Annotation.noteText(nil, "

a
b

", ""), "a\nb") +Assert.eq(Annotation.noteText(nil, "

a


b

", ""), "a\n\nb", "Quill 空行") +Assert.eq(Annotation.noteText(nil, "
a
b
", ""), "a\nb") +Assert.eq(Annotation.noteText(nil, "

a & b <c> "d"

", ""), 'a & b "d"', "实体解码") +Assert.eq(Annotation.noteText(nil, "


", ""), "", "全删后的空 HTML 也是空") + +-- 写入:空备注与 Web「新建未输入」字节一致("{}" + ""),不能写 {"ops":[...]}。 +for _idx, note in ipairs({ nil, "", " ", "\n\n", " \n \n" }) do + local remote = Annotation.toRemote(note) + Assert.eq(remote.comment, "{}", "空备注 comment") + Assert.eq(remote.commentHtml, "", "空备注 commentHtml") +end + +-- 写入:单个 insert op、末尾补 \n(Delta 文档必须以换行结尾);每行一个

。 +local one = Annotation.toRemote("第一行\n第二行") +local ops = JsonStub.decode(one.comment).ops +Assert.eq(#ops, 1, "只有一个 insert op") +Assert.eq(ops[1].insert, "第一行\n第二行\n") +Assert.eq(one.commentHtml, "

第一行

第二行

", "空行写


") +Assert.eq(Annotation.toRemote("a\n\nb").commentHtml, "

a


b

") + +-- 写入:转义 & < > ";先转 & 再转别的,避免二次转义。 +Assert.eq( + Annotation.toRemote('a & b < c > d "e"').commentHtml, + "

a & b < c > d "e"

" +) + +-- 写入:CRLF 归一、尾部换行去掉(否则每轮读回都多一行 → 判改过)。 +local crlf = Annotation.toRemote("a\r\nb\n\n") +Assert.eq(JsonStub.decode(crlf.comment).ops[1].insert, "a\nb\n") +Assert.eq(crlf.commentHtml, "

a

b

") + +-- 往返:自己写的备注读回后与归一后的 note 一致(push / pull 同一口径 → 零 update)。 +for _idx, note in ipairs({ + "一句话", + "第一行\n第二行", + "a\n\nb", + '引号 " 与反斜杠 \\ 都原样', + "小于 < 大于 > 和 & 号", + "好书📚 与 emoji 👍🏽", + " 行首缩进保留", +}) do + local remote = Annotation.toRemote(note) + Assert.eq(Annotation.noteText(remote.comment), note, "Delta 读回:" .. note) + Assert.eq( + Annotation.noteText(remote.comment, remote.commentHtml, ""), + note, + "完整 DTO 读回(commentHtml 优先):" .. note + ) +end + +-- 比较归一:trim + 内部连续空白压一个 + 零宽剔除;两边都空判等。 +Assert.is_true(Annotation.sameNote(nil, "")) +Assert.is_true(Annotation.sameNote("", " ")) +Assert.is_true(Annotation.sameNote("a b", " a b ")) +Assert.is_true(Annotation.sameNote("a\nb", "a b"), "换行也是空白") +Assert.is_true(Annotation.sameNote("a\226\128\139b", "ab"), "零宽空格剔除") +Assert.is_true(Annotation.sameNote("a\239\187\191b", "ab"), "BOM 剔除") +Assert.is_false(Annotation.sameNote("a", "b")) +Assert.is_false(Annotation.sameNote("", "a")) + +-- 幂等键:comment 不参与、selectedText 空白归一、xPath 精确。 +local base = { chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本" } +local function keyOf(over) + local ann = {} + for k, v in pairs(base) do ann[k] = v end + for k, v in pairs(over or {}) do ann[k] = v end + return Annotation.key(ann) +end +Assert.eq(keyOf({ comment = "甲" }), keyOf({ comment = "乙" }), "改备注不是新建") +Assert.eq(keyOf({ selectedText = " 选中\n文本 " }), keyOf({}), "选中文本的空白差异命中") +Assert.is_true(keyOf({ xPath = "//body/p[9]" }) ~= keyOf({})) +Assert.is_true(keyOf({ endingXPath = "//body/p[9]" }) ~= keyOf({})) +Assert.is_true(keyOf({ chapterId = 8 }) ~= keyOf({})) +Assert.eq(keyOf({}), "7" .. string.char(31) .. "//body/p[1]" .. string.char(31) .. "//body/p[2]" .. string.char(31) .. "选中 文本") +-- 分隔符对外导出:源侧拼「同坐标」判定键用的是同一个字符,不各写一份字面量。 +Assert.eq(Annotation.KEY_SEP, string.char(31)) +-- pull 落库后的本地条目把选中文本叫 text。 +Assert.eq( + Annotation.key({ chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", text = "选中 文本" }), + keyOf({}) +) +-- payload 形状(pull 落库后 / 阅读器快照里的条目)没有 DTO 字段名:xPath / endingXPath / selectedText +-- 的回退是 kavita_xpath / kavita_ending_xpath / text。源侧「远端同键去重」直接拿它当键。 +Assert.eq( + Annotation.key({ chapterId = 7, kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[2]", + text = "选中 文本" }), + keyOf({}), + "payload 字段与 DTO 字段算出同一个键" +) +Assert.eq( + Annotation.key({ kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[2]", text = "选中 文本" }), + Annotation.key({ xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本" }) +) +Assert.eq( + Annotation.key({ chapterId = 7, xPath = "//body/p[1]", kavita_xpath = "//body/p[9]", endingXPath = "//body/p[2]", + text = "选中 文本" }), + keyOf({}), + "DTO 字段优先,回退只在缺失时生效" +) + +-- 对账命中:同键多条取 id 最小;无命中 nil。 +local remote = { + { id = 9, chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本", comment = "{}" }, + { id = 3, chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = " 选中\n文本 ", comment = "{ops}" }, + { id = 1, chapterId = 7, xPath = "//body/p[5]", endingXPath = "//body/p[6]", selectedText = "别的划线" }, +} +Assert.eq(Annotation.match(remote, base).id, 3, "同键两条取 id 最小") +Assert.eq(Annotation.match({ { id = "12", chapterId = 7, xPath = "//body/p[1]", endingXPath = "//body/p[2]", selectedText = "选中 文本" } }, base).id, "12", "字符串 id 也能比") +Assert.is_nil(Annotation.match(remote, { chapterId = 7, xPath = "//body/p[7]", endingXPath = "//body/p[8]", selectedText = "x" })) +Assert.is_nil(Annotation.match(nil, base)) + +-- 列表:`GET /api/Annotation/all?chapterId=`,无分页;owner_id 非空才按 ownerUserId 过滤 +-- (owner_id 为空是 `/api/Users/me` 不可用时的降级:不过滤,宁可多看到自己的)。 +local chapter = { + { id = 1, ownerUserId = 5, comment = "{}" }, + { id = 2, ownerUserId = 9, comment = "别人的纯文本备注" }, + { id = 3, ownerUserId = 5, comment = "" }, +} +local calls = {} +local function clientReturning(data, err) + return { + json = function(_self, method, path, query, body, cb) + calls[#calls + 1] = { method = method, path = path, query = query, body = body } + cb(data, err) + return { cancel = function() end } + end, + } +end + +local got, got_err +Annotation.listByChapter(clientReturning(chapter), 12763, nil, function(list, err) got, got_err = list, err end) +Assert.eq(calls[1].method, "GET") +Assert.eq(calls[1].path, "/api/Annotation/all") +Assert.eq(calls[1].query.chapterId, 12763) +Assert.is_nil(calls[1].query.pageNumber, "该接口没有分页") +Assert.is_nil(calls[1].body) +Assert.eq(#got, 3, "owner_id 为空时不过滤") +Assert.is_nil(got_err) + +calls = {} +Annotation.listByChapter(clientReturning(chapter), 12763, 5, function(list) got = list end) +Assert.eq(#got, 2, "只留自己的注解") +Assert.eq(got[1].id, 1) +Assert.eq(got[2].id, 3) + +calls = {} +Annotation.listByChapter(clientReturning(chapter), 12763, "5", function(list) got = list end) +Assert.eq(#got, 2, "字符串 owner_id 也能对上数字 ownerUserId") + +Annotation.listByChapter(clientReturning(nil, "请求失败 (HTTP 400)"), 12763, 5, function(list, err) + got, got_err = list, err +end) +Assert.is_nil(got, "失败回 nil") +Assert.eq(got_err, "请求失败 (HTTP 400)") + +Annotation.listByChapter(clientReturning({}), 12763, 5, function(list) got = list end) +Assert.eq(#got, 0, "该章没有注解 = 空列表,不是 nil") diff --git a/tests/kavita/cache_spec.lua b/tests/kavita/cache_spec.lua new file mode 100644 index 0000000..4c35427 --- /dev/null +++ b/tests/kavita/cache_spec.lua @@ -0,0 +1,859 @@ +--[[-- +book.koplugin/source/kavita/cache.lua:kamare 缓存适配层。 + +kamare 的 `kamarecache` 是唯一的缓存执行者。这里只做探测、能力门面、配置镜像、 +错误文案、书架投影与删除保护,所有 kamare 模块都在函数内 pcall require、不持有 table。 + +@module tests.moonsource_kavita.cache_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") + +-- 源配置:每个用例自己改;cache 只读 base_url / api_key。 +local cfg = {} +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function() end, + } +end + +-- 日志:记录每一行,供「一次性 / 不刷屏」断言。 +local logs = {} +package.preload["utils.log"] = function() + local function push(level, ...) + local parts = {} + for index = 1, select("#", ...) do + parts[#parts + 1] = tostring(select(index, ...)) + end + logs[#logs + 1] = { level = level, text = table.concat(parts, " ") } + end + return { + dbg = function(...) push("dbg", ...) end, + info = function(...) push("info", ...) end, + warn = function(...) push("warn", ...) end, + error = function(...) push("error", ...) end, + } +end + +package.preload["moonsource_kavita.cache"] = function() + return dofile(PLUGIN .. "/cache.lua") +end +local Cache = require("moonsource_kavita.cache") + +--- 清空 kamare 模块,模拟未安装。 +local function uninstall() + package.loaded["kamarecache"] = nil + package.preload["kamarecache"] = nil + package.loaded["kamareimageviewer"] = nil + package.preload["kamareimageviewer"] = nil + package.loaded["kamareversion"] = nil + package.preload["kamareversion"] = nil +end + +--- 装一个 kamarecache 桩;status 用 loadstring 造出可预测的模块路径。 +---@param spec table { api_version, capabilities, version, path, viewer } +---@return table +local function installCache(spec) + package.loaded["kamareimageviewer"] = spec.viewer + local mod = { + api_version = spec.api_version, + capabilities = spec.capabilities or {}, + } + if spec.path then + mod.status = assert(loadstring("return function() end", "@" .. spec.path))() + end + package.loaded["kamarecache"] = mod + if spec.version then + package.loaded["kamareversion"] = spec.version + end + Cache.reset() + return mod +end + +local function resetLogs() + logs = {} +end + +local function logText() + local parts = {} + for _idx, line in ipairs(logs) do parts[#parts + 1] = line.text end + return table.concat(parts, "\n") +end + +--- 含某段文字的行数(一次性 / 不刷屏断言用)。 +---@param fragment string +---@return integer +local function countLines(fragment) + local count = 0 + for _idx, line in ipairs(logs) do + if line.text:find(fragment, 1, true) then count = count + 1 end + end + return count +end + +---------------------------------------------------------------------- +-- 探测:四安装态、版本、加载路径;成功记忆、失败不记忆。 +---------------------------------------------------------------------- +uninstall() +Cache.reset() +local probe = Cache.probe() +Assert.is_false(probe.ok, "没有 kamarecache 不可用") +Assert.eq(probe.state, "missing", "未安装 / 已安装但被禁用") +Assert.eq(probe.reason, "missing") +Assert.eq(Cache.available("open"), false, "未安装时没有任何缓存能力") + +uninstall() +package.loaded["kamareimageviewer"] = { new = function() end } +Cache.reset() +probe = Cache.probe() +Assert.is_false(probe.ok, "官方版没有缓存接口") +Assert.eq(probe.state, "official", "有查看器但无 kamarecache") + +installCache({ api_version = 2, capabilities = { status = true, open = true } }) +probe = Cache.probe() +Assert.is_false(probe.ok, "主版本不符整体禁用") +Assert.eq(probe.state, "incompatible") +Assert.eq(probe.api_version, 2) +Assert.eq(probe.reason, "major_mismatch") +Assert.eq(Cache.available("status"), false, "主版本不符整体禁用缓存") +Assert.eq(Cache.available("open"), false, "没有查看器可退回时 open 也不可用") + +local fake_path = "/fake/plugins/kamare.koplugin/src/kamarecache.lua" +installCache({ + api_version = 1, + capabilities = { status = true, open = true }, + version = "0.10.0-dev", + path = fake_path, +}) +probe = Cache.probe() +Assert.is_true(probe.ok) +Assert.eq(probe.state, "enhanced") +Assert.eq(probe.api_version, 1) +Assert.eq(probe.version, "0.10.0-dev", "kamareversion 返回字符串") +Assert.eq(probe.path, fake_path, "加载路径取自 debug.getinfo(module.status)") + +-- data 目录里的插件路径是 `plugins//x.koplugin`(KOReader 的 extra_plugin_paths 带尾斜杠): +-- 展示前归一,否则用户会以为路径坏了。 +installCache({ + api_version = 1, + capabilities = { status = true, open = true }, + version = "0.10.0-dev", + path = "/fake/plugins//kamare.koplugin/kamarecache.lua", +}) +Assert.eq(Cache.probe().path, "/fake/plugins/kamare.koplugin/kamarecache.lua", "重复斜杠归一") +Assert.eq(probe.capabilities.status, true) +Assert.eq(Cache.available("status"), true) +Assert.eq(Cache.available("index"), false, "能力逐项判断") + +-- 成功结果进程内记忆:模块从 package 里消失后仍按上次结果 +package.loaded["kamarecache"] = nil +Assert.eq(Cache.probe().state, "enhanced", "成功结果记住,不重复 require") +Assert.eq(Cache.reprobe().state, "missing", "「重新检测」清掉成功记忆") +Cache.reset() +Assert.eq(Cache.probe().state, "missing", "reset 后重新探测") + +-- 失败不记忆:装上模块后立刻能看到增强版 +Assert.eq(Cache.probe().state, "missing") +installCache({ api_version = 1, capabilities = {} }) +Assert.eq(Cache.probe().state, "enhanced", "失败结果不缓存") + +-- kamareversion 用表形状也认(老写法) +package.loaded["kamareversion"] = { version = "0.9.9" } +Cache.reset() +Assert.eq(Cache.probe().version, "0.9.9") + +---------------------------------------------------------------------- +-- 功能清单:kamarefeatures.lua 原样展示;缺文件 / 版本不符 / 结构不合法都不显示。 +---------------------------------------------------------------------- +local function withManifest(value) + package.loaded["kamarefeatures"] = value + Cache.reset() + return Cache.featureText() +end + +uninstall() +installCache({ api_version = 1, capabilities = { open = true }, path = fake_path }) +Assert.eq(withManifest({ api_version = 1, features = { "缓存", "双页", "裁切" } }), + "缓存 · 双页 · 裁切", "按清单顺序拼接") +Assert.eq(withManifest({ api_version = 1, features = { "缓存", "缓存", "", 42, "裁切" } }), + "缓存 · 裁切", "去重并忽略空串 / 非字符串") +Assert.is_nil(withManifest({ api_version = 2, features = { "缓存" } }), "api_version 不符") +Assert.is_nil(withManifest({ api_version = 1, features = {} }), "空清单") +Assert.is_nil(withManifest({ api_version = 1, features = "缓存" }), "不是数组") +Assert.is_nil(withManifest({ api_version = 1 }), "没有 features") +Assert.is_nil(withManifest("not a table"), "不是表") +package.loaded["kamarefeatures"] = nil +Cache.reset() +Assert.is_nil(Cache.featureText(), "没有清单不显示") + +-- 最多 8 项 +local many = {} +for i = 1, 10 do many[i] = "功能" .. i end +local text = withManifest({ api_version = 1, features = many }) +Assert.not_nil(text:find("功能8", 1, true), "保留前 8 项") +Assert.is_nil(text:find("功能9", 1, true), "超出 8 项截断") + +-- 未安装 kamare 时,即使有清单也不显示。 +package.loaded["kamarefeatures"] = { api_version = 1, features = { "缓存" } } +uninstall() +Cache.reset() +Assert.is_nil(Cache.featureText(), "非增强版不显示") + +---------------------------------------------------------------------- +-- 门面:每个能力一个显式包装,参数只从配置补 base_url;缺能力则 unsupported。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = " k " } + +local calls = {} +local function record(name, impl) + return function(...) + calls[#calls + 1] = { name = name, args = { ... } } + if impl then return impl(...) end + return true + end +end + +local function lastCall(name) + for index = #calls, 1, -1 do + if calls[index].name == name then return calls[index] end + end +end + +local index_result = { used = 1, available = 2, series = { ["60"] = { seriesId = 60 } } } +local mod = installCache({ + api_version = 1, + capabilities = { + status = true, summary = true, resume = true, queue = true, + index = true, enqueue = true, delete = true, estimate = true, + queue_control = true, + }, +}) +mod.index = record("index", function() return index_result end) +mod.status = record("status", function() return { state = "complete" } end) +mod.resume_page = record("resume_page", function() return { page = 7 } end) +mod.summary = record("summary", function() return { used = 10, available = 20, chapters = 3 } end) +mod.queue_state = record("queue_state", function() return { state = "idle" } end) +mod.enqueue = record("enqueue", function() return true, nil, { chapters = 1 } end) +mod.delete = record("delete", function() return true, nil, 1 end) +mod.estimate = record("estimate", function() return { ok = true, chapters = 1, bytes = 1, available = 2 } end) + +Assert.eq(Cache.index(), index_result) +Assert.eq(lastCall("index").args[1], "http://kav", "base_url 去尾斜杠;不传 api_key") + +Assert.eq(Cache.status(6001).state, "complete") +Assert.eq(lastCall("status").args[1], "http://kav") +Assert.eq(lastCall("status").args[2], 6001) + +Assert.eq(Cache.resumePage(6001, 60).page, 7) +Assert.eq(lastCall("resume_page").args[1], "http://kav") +Assert.eq(lastCall("resume_page").args[2], 6001) +Assert.eq(lastCall("resume_page").args[3], 60) + +Assert.eq(Cache.summary().chapters, 3) +Assert.eq(lastCall("summary").args[1], "http://kav") + +Assert.eq(Cache.queueState().state, "idle") +Assert.eq(lastCall("queue_state").args[1], "http://kav") + +local ok, code, info = Cache.enqueue({ { chapterId = 6001 } }) +Assert.is_true(ok) +Assert.is_nil(code) +Assert.eq(info.chapters, 1, "成功时第三个返回值原样透出") +Assert.eq(lastCall("enqueue").args[1], "http://kav") +Assert.eq(lastCall("enqueue").args[2][1].chapterId, 6001) + +local deleted_ok, deleted_code, deleted = Cache.delete({ 6001 }) +Assert.is_true(deleted_ok) +Assert.is_nil(deleted_code) +Assert.eq(deleted, 1) +Assert.eq(lastCall("delete").args[1], "http://kav") +Assert.eq(lastCall("delete").args[2][1], 6001) + +Assert.is_true(Cache.estimate({ { chapterId = 6001 } }).ok) +Assert.eq(lastCall("estimate").args[1], "http://kav") +Assert.eq(lastCall("estimate").args[2][1].chapterId, 6001) + +-- 队列控制:三个显式包装,全部作用在全局队列上。 +mod.queue_pause = record("queue_pause") +mod.queue_resume = record("queue_resume") +mod.queue_retry = record("queue_retry") +Assert.is_true(Cache.queuePause()) +Assert.is_true(Cache.queueResume()) +Assert.is_true(Cache.queueRetry({ 6001, 6002 })) +Assert.eq(lastCall("queue_pause").args[1], "http://kav") +Assert.eq(lastCall("queue_resume").args[1], "http://kav") +Assert.eq(lastCall("queue_retry").args[1], "http://kav") +Assert.eq(lastCall("queue_retry").args[2][2], 6002) + +-- 缺能力:对应功能单独降级,kamare 的函数不会被调用。 +calls = {} +installCache({ api_version = 1, capabilities = { status = true } }) +local value, code = Cache.status(1) +Assert.eq(code, "unsupported", "能力声明了但没有函数也按缺失处理") +value, code = Cache.index() +Assert.is_nil(value, "缺 index 返回 nil") +Assert.eq(code, "unsupported") +value, code = Cache.summary() +Assert.is_nil(value) +Assert.eq(code, "unsupported") +Assert.eq(select(2, Cache.queueState()), "unsupported") +Assert.eq(select(2, Cache.queueState()), "unsupported") +Assert.eq(select(2, Cache.queuePause()), "unsupported") +Assert.eq(select(2, Cache.enqueue({ { chapterId = 1 } })), "unsupported") +Assert.eq(select(2, Cache.delete({ 1 })), "unsupported") +Assert.eq(select(2, Cache.estimate({ { chapterId = 1 } })), "unsupported") + +-- 未配置服务器:静默 unknown_server,不碰 kamare。 +cfg = { base_url = "", api_key = "" } +calls = {} +Assert.eq(select(2, Cache.index()), "unknown_server") +Assert.eq(select(2, Cache.enqueue({ { chapterId = 1 } })), "unknown_server") +Assert.len(calls, 0, "未配置时不发任何调用") + +-- kamare 的错误码原样透出,文案交给 message 表。 +cfg = { base_url = "http://kav/", api_key = "k" } +installCache({ + api_version = 1, + capabilities = { index = true, enqueue = true }, +}) +mod = package.loaded["kamarecache"] +mod.index = function() return nil, "unknown_server" end +mod.enqueue = function() return nil, "not_enough_space", "空间不足", { needed = 3, available = 1 } end +local read, read_code = Cache.index() +Assert.is_nil(read) +Assert.eq(read_code, "unknown_server") +local written, write_code, write_message, write_detail = Cache.enqueue({ { chapterId = 1 } }) +Assert.is_nil(written) +Assert.eq(write_code, "not_enough_space") +Assert.eq(write_message, "空间不足") +Assert.eq(write_detail.available, 1) + +---------------------------------------------------------------------- +-- 配置镜像:首次缓存操作前 + 每次写操作前;只传 base_url + api_key,不传 name。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = " k " } +calls = {} +resetLogs() +local mirror_mod = installCache({ + api_version = 1, + capabilities = { server = true, index = true, status = true, enqueue = true, + delete = true, queue_control = true, estimate = true }, +}) +mirror_mod.register_server = record("register_server", function() return "srv-1" end) +mirror_mod.index = record("index", function() return { series = {} } end) +mirror_mod.status = record("status") +mirror_mod.enqueue = record("enqueue", function() return true end) +mirror_mod.delete = record("delete", function() return true, nil, 1 end) +mirror_mod.queue_pause = record("queue_pause") +mirror_mod.queue_resume = record("queue_resume") +mirror_mod.queue_retry = record("queue_retry") +mirror_mod.estimate = record("estimate", function() return { ok = true } end) + +local function callCount(name) + local n = 0 + for _idx, call in ipairs(calls) do + if call.name == name then n = n + 1 end + end + return n +end + +--- 某次调用在 calls 里的位置(从 1 起;没有为 0) +local function callIndex(name) + for index, call in ipairs(calls) do + if call.name == name then return index end + end + return 0 +end + +Cache.index() +Assert.eq(callCount("register_server"), 1, "首次缓存操作前镜像一次") +local registered = lastCall("register_server").args[1] +Assert.eq(registered.base_url, "http://kav", "URL 规范化:去尾斜杠") +Assert.eq(registered.api_key, "k", "API Key 去空白") +Assert.is_nil(registered.name, "不传固定显示名(否则两台服务器会共用一个缓存目录)") + +Cache.status(1) +Assert.eq(callCount("register_server"), 1, "读操作不重复镜像") + +Cache.enqueue({ { chapterId = 1 } }) +Assert.eq(callCount("register_server"), 2, "每次写操作前幂等兜底") +Assert.is_true(callIndex("register_server") < callIndex("enqueue"), "镜像先于写入") + +Cache.delete({ 1 }) +Cache.queuePause() +Cache.queueResume() +Cache.queueRetry({ 1 }) +Cache.estimate({ { chapterId = 1 } }) +Assert.eq(callCount("register_server"), 6, "delete / queue_* / 估计写盘前路径都镜像") + +-- 显式调用:设置页保存后走这一个入口。 +local server_key, mirror_code = Cache.registerServer("http://kav/", " k ") +Assert.eq(server_key, "srv-1") +Assert.is_nil(mirror_code) +Assert.eq(callCount("register_server"), 7) + +-- 失败:后台只记一次日志,功能照常交给 kamare(按 unknown_server 静默降级)。 +mirror_mod.register_server = record("register_server", function() return nil, "settings_write_failed" end) +local before = callCount("register_server") +Cache.enqueue({ { chapterId = 2 } }) +Assert.eq(callCount("register_server"), before + 1) +Assert.eq(callCount("enqueue"), 2, "镜像失败不阻断写操作,最终以 kamare 为准") +Assert.is_true(Cache.mirrorFailed(), "本次会话镜像失败") +Assert.matches(logText(), "settings_write_failed", "失败记一行") +local mirror_lines = 0 +for _idx, line in ipairs(logs) do + if line.text:find("mirror", 1, true) then mirror_lines = mirror_lines + 1 end +end +Assert.eq(mirror_lines, 1, "同一原因只记一次") +Cache.enqueue({ { chapterId = 3 } }) +mirror_lines = 0 +for _idx, line in ipairs(logs) do + if line.text:find("mirror", 1, true) then mirror_lines = mirror_lines + 1 end +end +Assert.eq(mirror_lines, 1, "重复失败不刷屏") + +mirror_mod.register_server = record("register_server", function() return "srv-1" end) +Cache.enqueue({ { chapterId = 4 } }) +Assert.is_false(Cache.mirrorFailed(), "成功后清除失败态") + +-- 未配置 / 未安装时不假装镜像。 +cfg = { base_url = "", api_key = "" } +calls = {} +Cache.index() +Assert.len(calls, 0, "未配置不发镜像") + +cfg = { base_url = "http://kav/", api_key = "k" } +uninstall() +Cache.reset() +calls = {} +Cache.available("index") +Assert.len(calls, 0, "未安装不发镜像") + +---------------------------------------------------------------------- +-- 文案:02 A9 的 code 表 + 07 A7 的 lastError 特征。 +---------------------------------------------------------------------- +local CODE_CASES = { + { "offline_not_cached", "这一卷还没缓存,联网后可下载" }, + { "viewer_running", "漫画阅读器已在运行" }, + { "no_pages", "这一卷没有可显示的页面" }, + { "settings_write_failed", "无法写入 kamare 配置" }, + { "retry_no_entry", "没有可重试的任务" }, + { "chapter_open", "正在阅读这一卷,关闭后可以删除" }, +} +for _idx, case in ipairs(CODE_CASES) do + Assert.eq(Cache.message(case[1]), case[2], "code → 文案: " .. case[1]) +end +-- 静默:已是目标状态 / 未知服务器都当无缓存,不打扰用户。 +Assert.is_nil(Cache.message("unknown_server"), "unknown_server 静默") +Assert.is_nil(Cache.message("already_cached"), "已缓存静默") +Assert.is_nil(Cache.message("already_queued"), "已排队静默") +Assert.is_nil(Cache.message(nil), "没有 code 没有说话") +-- 未知 code:kamare 的 message 优先,再退通用文案。 +Assert.eq(Cache.message("weird_code", "kamare 的原话"), "kamare 的原话") +Assert.eq(Cache.message("weird_code"), "缓存操作失败") + +local MB = 1024 * 1024 +Assert.eq(Cache.sizeText(3 * MB), "3.0 MB") +Assert.eq(Cache.message("not_enough_space", nil, { needed = 3 * MB, available = MB }), + "空间不足:需要 3.0 MB,可用 1.0 MB") +Assert.eq(Cache.message("cache_limit_reached", nil, { needed = 2 * MB, limit = 9 * MB }), + "缓存空间已满:需要 2.0 MB,上限 9.0 MB") +Assert.eq(Cache.message("low_space", nil, { available = MB, low_water = 500 * MB }), + "可用空间低于 500.0 MB,清理后再下载") + +-- estimate 的三种裁决:确认框就地换文案,不复制 kamare 的 2.05 / 500MB 常量。 +Assert.eq(Cache.estimateMessage({ reason = "nothing_to_do" }), "全部已缓存或正在下载") +Assert.eq(Cache.estimateMessage({ reason = "space", bytes = 3 * MB, available = MB }), + "空间不足:需要 3.0 MB,可用 1.0 MB") +Assert.eq(Cache.estimateMessage({ reason = "low_water", available = MB }), + "可用空间不足(剩余 1.0 MB),清理后再下载") +Assert.is_nil(Cache.estimateMessage({ ok = true, reason = nil }), "可下载时没有额外文案") +Assert.is_nil(Cache.estimateMessage(nil)) + +-- 失败原因(07 A7):按 kamare 的 lastError 特征归并成可读文案。 +local FAILED = { + { "http 403 while fetching page 3", "服务器拒绝下载(403),检查 API Key / 权限" }, + { "not an archive: text/html", "下载内容不完整或不是有效压缩包" }, + { "size 120/900", "下载内容不完整或不是有效压缩包" }, + { "extracted 3 of 5 pages", "下载内容不完整或不是有效压缩包" }, + { "sink write failed: no space left on device", "存储空间不足或写入失败" }, + { "socket closed", "网络中断或服务器不可达" }, + { "connect timeout", "网络中断或服务器不可达" }, + { "connection truncated", "网络中断或服务器不可达" }, +} +for _idx, case in ipairs(FAILED) do + Assert.eq(Cache.failureText(case[1]), case[2], "lastError → 文案: " .. case[1]) +end +Assert.eq(Cache.failureText("weird failure"), "缓存失败:weird failure", "未知错误前缀保留原话") +Assert.is_nil(Cache.failureText(nil)) + +---------------------------------------------------------------------- +-- 打开:enhanced 有 open 走 kamare;官方 / 缺 open 退回 legacy;记录当前打开的章。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = "k" } +calls = {} +local opened = installCache({ + api_version = 1, + capabilities = { open = true, delete = true, server = true }, +}) +opened.register_server = record("register_server", function() return "srv-1" end) +local closed = {} +local nexts = {} +local fake_viewer = { kind = "viewer" } +opened.open = record("open", function() return fake_viewer end) +Assert.is_true(Cache.enhancedOpen(), "增强版有 open:由 kamare 决定起始页 / 离线") +local open_result, open_code = Cache.open({ + base_url = "http://kav/", api_key = "k", + entry = { chapterId = 6001, pages = 20 }, title = "漫画", + on_close = function(page, total) closed[#closed + 1] = { page, total } end, + on_next = function(id) nexts[#nexts + 1] = id end, +}) +Assert.eq(open_result, fake_viewer) +Assert.is_nil(open_code) +local open_opts = lastCall("open").args[1] +Assert.eq(open_opts.entry.chapterId, 6001, "目录条目原样交给 kamare") +Assert.eq(open_opts.title, "漫画") +Assert.not_nil(open_opts.on_next) +Assert.is_true(Cache.isChapterOpen(6001), "打开成功记下当前章") +Assert.is_false(Cache.isChapterOpen(6002)) + +open_opts.on_close(7, 20) +Assert.eq(closed[1][1], 7, "关闭回调原样透出") +Assert.eq(closed[1][2], 20) +Assert.is_false(Cache.isChapterOpen(6001), "关闭后清除当前章") + +-- 打开失败不留 active。 +opened.open = function() return nil, "viewer_running", "漫画阅读器已在运行" end +local failed, failed_code, failed_message = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6003, pages = 4 }, +}) +Assert.is_nil(failed) +Assert.eq(failed_code, "viewer_running") +Assert.eq(failed_message, "漫画阅读器已在运行") +Assert.is_false(Cache.isChapterOpen(6003)) + +-- 删除保护:本地先拦,kamare 的 delete 根本不会被调用。 +calls = {} +local deleted_viewer = installCache({ + api_version = 1, + capabilities = { open = true, delete = true }, +}) +deleted_viewer.open = record("open", function() return { kind = "viewer" } end) +deleted_viewer.delete = record("delete", function() return true, nil, 1 end) +Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 20 } }) +local del_ok, del_code = Cache.delete({ 6001 }) +Assert.is_nil(del_ok) +Assert.eq(del_code, "chapter_open", "正在读的章拒绝删除") +Assert.eq(Cache.message(del_code), "正在阅读这一卷,关闭后可以删除") +Assert.eq(callCount("delete"), 0, "kamare 的 delete 不被调用") + +Assert.is_true(Cache.delete({ 6002 }), "别的章照删") +Assert.eq(lastCall("delete").args[2][1], 6002) + +-- 关掉查看器后可以删。 +lastCall("open").args[1].on_close(1, 20) +Assert.is_true(Cache.delete({ 6001 })) + +-- 官方版 / enhanced 缺 open:退回 legacy 通道(今天的在线看图能力不能丢)。 +uninstall() +package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } +local streamed = {} +package.loaded["kavitaclient"] = { + streamChapter = function(_self, id) streamed[#streamed + 1] = id; return { { pageNumber = 1 } } end, +} +local shown = {} +package.loaded["ui/uimanager"] = { show = function(_, widget) shown[#shown + 1] = widget end } +Cache.reset() +Assert.is_true(Cache.available("open"), "官方版仍能在线看图") +Assert.is_false(Cache.enhancedOpen(), "官方版不接管 open:起始页由 moon 补") +local legacy_viewer, legacy_code = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 20 }, title = "漫画", + start_page = 3, on_close = function() end, on_next = function() end, +}) +Assert.is_nil(legacy_code) +Assert.eq(legacy_viewer.metadata.chapterId, 6001) +Assert.eq(legacy_viewer.metadata.startPage, 3) +Assert.eq(legacy_viewer.images_list_nb, 20) +Assert.eq(legacy_viewer.title, "漫画") +Assert.eq(require("kavitaclient").api_key, "k") +Assert.eq(require("kavitaclient").device_id, "moon-kavita") +Assert.eq(streamed[1], 6001) +Assert.eq(shown[1], legacy_viewer, "交给 UIManager 显示") +Assert.is_true(Cache.isChapterOpen(6001), "legacy 也记当前章") + +-- enhanced 但缺 open 能力:同样退回 legacy。 +installCache({ api_version = 1, capabilities = { status = true } }) +Assert.is_false(Cache.enhancedOpen(), "增强版缺 open:退回 legacy,由 moon 给起始页") +package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } +package.loaded["kavitaclient"] = { streamChapter = function() return { { pageNumber = 1 } } end } +Cache.reset() +local fallback = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6004, pages = 4 }, +}) +Assert.not_nil(fallback, "增强版缺 open 时退回查看器") +Assert.eq(fallback.metadata.chapterId, 6004) + +-- legacy 没有页面 / 查看器已被占用 / 串流失败:稳定 code。 +Cache.reset() +local no_pages, no_pages_code = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6005, pages = 0 }, +}) +Assert.is_nil(no_pages) +Assert.eq(no_pages_code, "no_pages") + +package.loaded["kamareimageviewer"] = { new = function(_self, spec) spec._aborted = true; return spec end } +local running, running_code = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6006, pages = 3 }, +}) +Assert.is_nil(running) +Assert.eq(running_code, "viewer_running") + +package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } +package.loaded["kavitaclient"] = { streamChapter = function() return nil end } +local broken, broken_code, broken_message = Cache.open({ + base_url = "http://kav/", api_key = "k", entry = { chapterId = 6007, pages = 3 }, +}) +Assert.is_nil(broken) +Assert.eq(broken_code, "open_failed") +Assert.eq(broken_message, "打开漫画阅读器失败") + +-- 完全没有 kamare:不能假装能打开。 +uninstall() +Cache.reset() +Assert.is_false(Cache.available("open")) +local none, none_code = Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 1, pages = 1 } }) +Assert.is_nil(none) +Assert.eq(none_code, "unsupported") + +---------------------------------------------------------------------- +-- 书架投影:complete / stale 才算已缓存;三张表按服务器记忆,无 TTL。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = "k" } +local work = Config.dir() .. "/cache_spec" +os.execute("mkdir -p '" .. work .. "'") +local cover = work .. "/cover-60.jpg" +local cover_file = assert(io.open(cover, "wb")) +cover_file:write("jpeg") +cover_file:close() + +calls = {} +local shelf_mod = installCache({ + api_version = 1, + capabilities = { index = true, server = true, enqueue = true, delete = true, queue_control = true }, +}) +shelf_mod.register_server = record("register_server", function() return "srv" end) +local shelf_index = { + series = { + ["60"] = { seriesId = 60, chapters = 2, complete = true, coverPath = cover }, + ["61"] = { seriesId = 61, chapters = 0, complete = true, coverPath = work .. "/missing.jpg" }, + ["62"] = { seriesId = 62, chapters = 1, stale = true }, + ["63"] = { seriesId = 63, chapters = 1 }, + ["64"] = { seriesId = 64, chapters = 3, stale = true, complete = false }, + }, +} +shelf_mod.index = record("index", function() return shelf_index end) +shelf_mod.enqueue = record("enqueue", function() return true end) +shelf_mod.delete = record("delete", function() return true, nil, 1 end) +shelf_mod.queue_pause = record("queue_pause", function() return true end) + +local shelf = Cache.shelf() +Assert.is_true(shelf.series_ids["60"], "complete 算已缓存") +Assert.is_true(shelf.mark["60"]) +Assert.is_true(shelf.series_ids["62"], "stale 与 complete 等价") +Assert.is_true(shelf.series_ids["64"]) +Assert.is_nil(shelf.series_ids["61"], "没有章不算(chapters = 0)") +Assert.is_nil(shelf.series_ids["63"], "queued / downloading 不算") +Assert.eq(shelf.cover["60"], cover, "封面路径存在才给") +Assert.is_nil(shelf.cover["61"], "文件不存在不给") +Assert.eq(callCount("index"), 1) + +Cache.shelf() +Assert.eq(callCount("index"), 1, "进程内记忆,无 TTL、翻页不重拉") + +-- 三类失效:写操作成功、手动刷新、Registry.reload(源实例重建时调 resetShelf)。 +Cache.enqueue({ { chapterId = 6001 } }) +Cache.shelf() +Assert.eq(callCount("index"), 2, "enqueue 成功后失效") +Cache.delete({ 6001 }) +Cache.shelf() +Assert.eq(callCount("index"), 3, "delete 成功后失效") +Cache.queuePause() +Cache.shelf() +Assert.eq(callCount("index"), 4, "queue_* 成功后失效") +Cache.resetShelf() +Cache.shelf() +Assert.eq(callCount("index"), 5, "手动刷新 / Registry.reload") + +-- 写失败不能误伤投影(失败时缓存没变)。 +shelf_mod.enqueue = record("enqueue", function() return nil, "not_enough_space" end) +Cache.enqueue({ { chapterId = 6002 } }) +Cache.shelf() +Assert.eq(callCount("index"), 5, "失败的写操作不失效") + +-- 按服务器分开记忆:切回旧服务器不重拉。 +cfg.base_url = "http://other/" +Cache.shelf() +Assert.eq(callCount("index"), 6) +Assert.eq(lastCall("index").args[1], "http://other") +cfg.base_url = "http://kav/" +Cache.shelf() +Assert.eq(callCount("index"), 6, "旧服务器的投影还在") + +-- unknown_server 不记忆:下次进书架再试(可能刚镜像完)。 +shelf_mod.index = record("index", function() return nil, "unknown_server" end) +cfg.base_url = "http://third/" +Assert.is_nil(Cache.shelf()) +Assert.is_nil(Cache.shelf()) +Assert.eq(callCount("index"), 8, "无缓存不写空投影") + +-- 缺 index 能力:整块降级为无标记。 +installCache({ api_version = 1, capabilities = { status = true } }) +Assert.is_nil(Cache.shelf(), "缺 index 无书架标记") + +-- 「已缓存」口径只在一处:章状态与 index 摘要两种形状都认(03 A3)。 +Assert.is_true(Cache.isCached({ state = "complete" })) +Assert.is_true(Cache.isCached({ state = "stale" })) +Assert.is_false(Cache.isCached({ state = "partial" })) +Assert.is_false(Cache.isCached(nil)) +Assert.is_true(Cache.isCached({ chapters = 1, complete = true })) +Assert.is_false(Cache.isCached({ chapters = 1 })) + +-- 能力名单排序与拼接:设置页与日志共用同一份(08)。 +Assert.eq(Cache.capabilityNames({ open = true, index = true }), "index,open") +Assert.eq(Cache.capabilityNames({ open = true, index = true }, "、"), "index、open") +Assert.eq(Cache.capabilityNames(nil), "none") + +---------------------------------------------------------------------- +-- 日志:探测每进程一次、写操作一行、open 失败去重、暂停原因只在变化时记。 +---------------------------------------------------------------------- +cfg = { base_url = "http://kav/", api_key = "secret-key" } +uninstall() +resetLogs() +Cache.reset() +Cache.probe() +Cache.probe() +Assert.eq(countLines("kamare probe"), 1, "探测结果每进程只记一次") +Assert.matches(logText(), "kamare probe ok=false state=missing") +Assert.is_nil(logText():find("secret-key", 1, true), "日志里绝不出现 API Key") + +installCache({ + api_version = 1, + capabilities = { status = true, index = true, enqueue = true, delete = true, + queue = true, queue_control = true, open = true }, + version = "0.10.0", + path = "/fake/plugins/kamare.koplugin/kamarecache.lua", +}) +resetLogs() +Cache.probe() +Cache.probe() +Assert.eq(countLines("kamare probe ok=true"), 1) +Assert.matches(logText(), "state=enhanced") +Assert.matches(logText(), "version=0.10.0") +Assert.matches(logText(), "caps=.*index") +Assert.is_nil(logText():find("secret-key", 1, true)) + +local log_mod = package.loaded["kamarecache"] +log_mod.status = function() return { state = "complete" } end +log_mod.index = function() return { series = {} } end +log_mod.enqueue = function() return nil, "not_enough_space", "空间不足", { needed = 9, available = 1 } end +resetLogs() +Cache.enqueue({ { chapterId = 6001 }, { chapterId = 6002 } }) +Cache.enqueue({ { chapterId = 6003 } }) +Assert.eq(countLines("cache enqueue cid=6001,6002 code=not_enough_space"), 1, "每次写操作一行,带 code 与章 id") +Assert.eq(countLines("cache enqueue cid=6003 code=not_enough_space"), 1, "另一次失败另记一行") + +log_mod.delete = function() return true, nil, 1 end +resetLogs() +Cache.delete({ 6004 }) +Assert.eq(countLines("cache delete cid=6004 code=ok"), 1) + +log_mod.queue_pause = function() return true end +resetLogs() +Cache.queuePause() +Assert.eq(countLines("cache queue_pause cid=- code=ok"), 1, "队列动作没有章 id,记 -") + +-- 轮询路径不刷日志,只在暂停原因变化时记一行。 +log_mod.queue_state = function() return { state = "paused", pause_reason = "offline" } end +resetLogs() +Cache.queueState() +Cache.queueState() +Assert.eq(countLines("queue paused reason=offline"), 1, "1 秒轮询不重复记") +log_mod.queue_state = function() return { state = "idle" } end +Cache.queueState() +log_mod.queue_state = function() return { state = "paused", pause_reason = "offline" } end +Cache.queueState() +Assert.eq(countLines("queue paused reason=offline"), 2, "恢复后再次暂停要再记") +log_mod.queue_state = function() return { state = "paused", pause_reason = "network" } end +Cache.queueState() +Assert.eq(countLines("queue paused reason=network"), 1) + +-- 读操作不写日志。 +resetLogs() +Cache.status(6001) +Cache.index() +Assert.len(logs, 0, "读路径零日志") + +-- open 失败同一原因只记一次。 +log_mod.open = function() return nil, "viewer_running" end +resetLogs() +Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 4 } }) +Cache.open({ base_url = "http://kav/", api_key = "k", entry = { chapterId = 6001, pages = 4 } }) +Assert.eq(countLines("cache open cid=6001 code=viewer_running"), 1, "open 失败去重") + +-- chapters / delete_all / plan / summaryAll:清理门面 +cfg.base_url, cfg.api_key = "http://kav", "k" +local cleanup_calls = {} +local cleanup_mod = installCache({ + api_version = 1, + capabilities = { status = true, summary = true, chapters = true, delete = true, + delete_all = true, server = true }, + version = "0.10.0", +}) +function cleanup_mod.chapters(base_url, series_id) + cleanup_calls.chapters = { base_url, series_id } + return { { chapterId = 1, pages = 10, bytes = 100, read = true } } +end +function cleanup_mod.delete_all() + cleanup_calls.delete_all = (cleanup_calls.delete_all or 0) + 1 + return true, nil, { chapters = 3, bytes = 300 } +end +function cleanup_mod.summary(base_url) + cleanup_calls.summary = (cleanup_calls.summary or 0) + 1 + cleanup_calls.summary_base = base_url + return { used = 300, available = 1000, chapters = 3 } +end +function cleanup_mod.register_server() return "srv" end +Cache.reset() + +local plan_rows = Cache.chapters(42) +Assert.eq(cleanup_calls.chapters[1], "http://kav", "chapters 用当前服务器") +Assert.eq(cleanup_calls.chapters[2], 42, "chapters 透传 series_id") +Assert.len(plan_rows, 1, "chapters 返回数组") + +local ok, _code, _message, detail = Cache.deleteAll() +Assert.is_true(ok, "deleteAll 成功") +Assert.eq(detail and detail.chapters, 3, "deleteAll 透传估算") +Assert.eq(cleanup_calls.delete_all, 1, "deleteAll 调 kamare 一次") + +Assert.eq(Cache.summaryAll().chapters, 3, "summaryAll 返回合计") +Assert.eq(cleanup_calls.summary_base, nil, "summaryAll 不传 base_url") + +local plan = Cache.plan(plan_rows, "read", nil) +Assert.eq(plan.chapters, 1, "read 过滤保留已读") +Assert.eq(plan.bytes, 100, "字节合计") +Assert.eq(plan.ids[1], 1, "ids 供批量删除") +local not_read = Cache.plan({ { chapterId = 2, pages = 10, bytes = 50, read = false } }, "read", nil) +Assert.eq(not_read.chapters, 0, "未读不入选") +local via_toc = Cache.plan({ { chapterId = 3, pages = 10, bytes = 50, read = false } }, "read", + { ["3"] = 10 }) +Assert.eq(via_toc.chapters, 1, "toc 的 pagesRead 补第三源") +local queued = Cache.plan({ { chapterId = 4, pages = 10, bytes = 1, read = true, queued = true } }, "all", nil) +Assert.eq(queued.queued, 1, "排队数进计划") + + +return true diff --git a/tests/kavita/cache_task_spec.lua b/tests/kavita/cache_task_spec.lua new file mode 100644 index 0000000..27da0a5 --- /dev/null +++ b/tests/kavita/cache_task_spec.lua @@ -0,0 +1,256 @@ +--[[-- +漫画缓存的后台任务:登记 passive 任务、按本批卷轮询、暂停时放行自动休眠、收尾只提示一次。 + +kamare 仍是执行者,这里只观察 queue_state / status;队列全局共享,所以进度只数本批的卷。 + +@module tests.moonsource_kavita.cache_task_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field, redundant-parameter + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") + +local Themed = require("support.theme_stubs") +Themed.install() + +package.preload["ui/network/manager"] = function() + return { isConnected = function() return true end } +end +package.preload["ui.guard"] = function() + return { + call = function(_label, fn, ...) return fn(...) end, + wrap = function(_label, fn) return fn end, + } +end +package.preload["utils.log"] = function() + return { info = function() end, warn = function() end, err = function() end, dbg = function() end } +end + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") + +-- 缓存适配层:只提供 cache_task 用到的读接口;写操作不经过这里。 +local st = { queue = { state = "idle", entries = {} }, statuses = {}, queue_ok = true } +package.preload["moonsource_kavita.cache"] = function() + return { + available = function(cap) return st.queue_ok and cap == "queue" end, + queueState = function() return st.queue end, + status = function(id) return st.statuses[tostring(id)] end, + isCached = function(status) + return type(status) == "table" and (status.state == "complete" or status.state == "stale") + end, + } +end + +local Tasks = require("workers.tasks") +local CacheTask = dofile(PLUGIN .. "/cache_task.lua") + +local series = { stable_id = "900", title = "测试系列" } +local entries = { + { chapterId = 1, title = "第 1 卷" }, + { chapterId = 2, title = "第 2 卷" }, + { chapterId = 3, title = "第 3 卷" }, +} + +--- 跑一条指定延迟的定时器:<1 是队列的变更拍,>=1 且 <60 是轮询拍(60 秒是防休眠的 InputEvent 补拍)。 +---@param match fun(delay: number): boolean +---@return boolean +local function runTimer(match) + for index, item in ipairs(Kit.scheduled) do + if match(item.delay) then + table.remove(Kit.scheduled, index) + item.fn() + return true + end + end + return false +end + +--- 结清队列的变更拍(pause_auto_suspend 之类)。 +local function changes() + while runTimer(function(delay) return delay < 1 end) do end +end + +--- 跑一拍轮询。 +local function tick() + Assert.is_true(runTimer(function(delay) return delay >= 1 and delay < 60 end), "排了下一拍轮询") +end + +local function reset() + for _idx, item in ipairs(Tasks.tasks()) do + local live = Tasks.get(item.key) + if live then live.cancel() end + end + changes() + st.queue = { state = "idle", entries = {} } + st.statuses = {} + st.queue_ok = true + Themed.made = {} + Kit.scheduled, Kit.unscheduled = {}, {} +end + +-- 缺 queue 能力:没有可轮询的队列,不登记(免得后台任务永远挂着)。 +do + reset() + st.queue_ok = false + Assert.is_nil(CacheTask.track{ series = series, entries = entries }) + Assert.len(Tasks.tasks(), 0) + st.queue_ok = true +end + +-- 登记:一条 passive 的 cache 任务,顶栏读到「执行中 1/1」;缓存期间不自动休眠。 +do + reset() + local handle = CacheTask.track{ series = series, entries = entries } + Assert.not_nil(handle) + local list = Tasks.tasks() + Assert.len(list, 1, "只登记一条") + Assert.eq(list[1].kind, "cache") + Assert.eq(list[1].title, "测试系列") + Assert.eq(list[1].state, "running", "passive 任务立刻启动,不排队") + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "缓存期间压住自动休眠") +end + +-- 进度:只数本批的卷,当前卷名来自 queue.current_chapter_id。 +do + reset() + CacheTask.track{ series = series, entries = entries } + st.statuses["1"] = { state = "complete" } + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" } }, + current_chapter_id = 2 } + tick() + local task = Tasks.tasks()[1] + Assert.eq(task.count, 1, "已落地 1 卷") + Assert.eq(task.total, 3, "总数是本批卷数") + Assert.eq(task.text, "第 2 卷", "说明行写当前卷") + + -- 不在本批的卷(别的系列)不计数。 + st.queue.entries[99] = { state = "downloading" } + tick() + Assert.eq(Tasks.tasks()[1].count, 1, "别的系列不算进度") +end + +-- 全部落地:任务结束、toast 一次、不再排下一拍。 +do + reset() + CacheTask.track{ series = series, entries = entries } + for index = 1, 3 do st.statuses[tostring(index)] = { state = "complete" } end + st.queue = { state = "idle", entries = {} } + local toasts = #Themed.all("toast") + tick() + Assert.len(Tasks.tasks(), 0, "结束后离开未结束列表") + local finished = Tasks.finished()[1] + Assert.is_true(finished.ok, "全成算成功") + Assert.eq(finished.total, 3) + Assert.eq(finished.count, 3, "收尾补报最终计数(不是上一拍的 2/3)") + Assert.is_nil(finished.text, "收尾后不再挂着上一卷的名字") + Assert.eq(#Themed.all("toast"), toasts + 1, "只 toast 一次") + Assert.eq(Themed.last("toast").text, "已缓存 3 卷") + Assert.is_false(runTimer(function(delay) return delay >= 1 end), "收尾后不再轮询") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "结束放行自动休眠") +end + +-- 部分失败:失败项是终态(kamare 留在队列里等重试),收尾报成功 / 失败数。 +do + reset() + CacheTask.track{ series = series, entries = entries } + st.statuses["1"] = { state = "complete" } + st.statuses["2"] = { state = "complete" } + st.queue = { state = "idle", entries = { [3] = { state = "failed", last_error = "http 403" } } } + tick() + local finished = Tasks.finished()[1] + Assert.is_false(finished.ok) + Assert.eq(finished.total, 3) + Assert.eq(finished.count, 2, "失败的那卷不算成功") + Assert.eq(Themed.last("toast").text, "2 卷成功,1 卷失败") +end + +-- 静音:页面自己的进度框负责提示时不出 toast。 +do + reset() + local handle = CacheTask.track{ series = series, entries = entries } + handle.mute(true) + for index = 1, 3 do st.statuses[tostring(index)] = { state = "complete" } end + st.queue = { state = "idle", entries = {} } + local toasts = #Themed.all("toast") + tick() + Assert.eq(#Themed.all("toast"), toasts, "静音时不提示") + Assert.is_true(Tasks.finished()[1].ok, "任务照常收尾") +end + +-- 暂停:说明行给暂停原因,放行自动休眠,轮询放慢到 5 秒;恢复后继续。 +do + reset() + CacheTask.track{ series = series, entries = entries } + st.statuses["1"] = { state = "complete" } + st.queue = { state = "paused", pause_reason = "low_space", + entries = { [2] = { state = "queued" } } } + changes() + tick() + local task = Tasks.tasks()[1] + Assert.eq(task.state, "running", "暂停只是报状态,不结束任务") + Assert.eq(task.text, "空间不足,已暂停") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "暂停时不再撑着不睡") + Assert.is_true(runTimer(function(delay) return delay == 5 end), "暂停时 5 秒一拍") + + -- 恢复:下一拍回到下载说明行,重新压住休眠。 + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" } }, + current_chapter_id = 2 } + tick() + Assert.eq(Tasks.tasks()[1].text, "第 2 卷") + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "恢复后继续撑住") +end + +-- 队列丢了(kamare 重启 / 队列被清):连续几拍看不到本批的项就按中断收尾。 +do + reset() + CacheTask.track{ series = series, entries = entries } + local toasts = #Themed.all("toast") + for _idx = 1, 4 do + tick() + Assert.len(Tasks.tasks(), 1, "还没到上限,继续等") + end + tick() + Assert.len(Tasks.tasks(), 0, "超时后收尾") + local finished = Tasks.finished()[1] + Assert.is_false(finished.ok) + Assert.eq(#Themed.all("toast"), toasts + 1) + Assert.eq(Themed.last("toast").text, "缓存已中断") +end + +-- 同一部再有卷入队 / 重试:并进同一条任务,失败项清掉终态重新观察。 +do + reset() + local first = CacheTask.track{ series = series, entries = { entries[1] } } + Assert.eq(Tasks.tasks()[1].total, 1) + st.queue = { state = "downloading", entries = { [1] = { state = "downloading" } } } + tick() + Assert.eq(Tasks.tasks()[1].total, 1) + + local merged = CacheTask.track{ series = series, entries = { entries[2], entries[3] } } + Assert.eq(merged, first, "同一部书复用同一条任务") + Assert.len(Tasks.tasks(), 1, "不新增任务") + Assert.eq(Tasks.tasks()[1].total, 3, "总数并进去") + + -- 失败项重试:终态清掉,重新计入进度。 + st.statuses["1"] = { state = "complete" } + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" }, + [3] = { state = "failed" } } } + tick() + Assert.eq(Tasks.tasks()[1].count, 1, "失败项不算成功") + merged.add({ entries[3] }) + st.queue = { state = "downloading", entries = { [2] = { state = "downloading" }, + [3] = { state = "downloading" } } } + tick() + Assert.eq(Tasks.tasks()[1].count, 1, "重试的卷回到未完成") + st.statuses["2"] = { state = "complete" } + st.statuses["3"] = { state = "complete" } + st.queue = { state = "idle", entries = {} } + tick() + Assert.is_true(Tasks.finished()[1].ok, "重试成功后收尾") +end diff --git a/tests/kavita/client_spec.lua b/tests/kavita/client_spec.lua new file mode 100644 index 0000000..6f0083a --- /dev/null +++ b/tests/kavita/client_spec.lua @@ -0,0 +1,69 @@ +--[[-- +book.koplugin/source/kavita/client.lua:请求超时可配置, +统计分页的 URL 形态与 `Pagination` 头解析。 + +慢设备 / 慢服务器上全量书架(all-v2)一次要几十秒,固定的 30s 上限会让整轮同步中断、 +书架永远加载不出来;这里锁住「默认足够宽 + 可在设置里调大 + 透传到 HTTP 层」。 + +@module tests.moonsource_kavita.client_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local JsonStub = require("support.json_stub") + +package.loaded["json"] = { encode = JsonStub.encode, decode = JsonStub.decode } + +local captured +package.loaded["http.request"] = { + ok = function(code) return tonumber(code) == 200 end, + request = function(opts, cb) + captured = opts + cb({ code = 200, body = "{}" }) + return { cancel = function() end } + end, +} +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +package.preload["moonsource_kavita.client"] = function() + return dofile(PLUGIN .. "/client.lua") +end +local Client = require("moonsource_kavita.client") + +local function make(timeout) + return Client.new({ base_url = "http://kav/", api_key = "k", timeout = timeout }) +end + +Assert.eq(Client.DEFAULT_TIMEOUT, 60, "默认不再是 30s") +Assert.eq(Client.new({ base_url = "http://kav/", api_key = "k" }).timeout, 60, "未配置用默认超时") +Assert.eq(make("120").timeout, 120, "设置里的字符串数值也认") +Assert.eq(make(1).timeout, 5, "过小收敛到下限") +Assert.eq(make(0).timeout, 5, "0 收敛到下限") +Assert.eq(make(100000).timeout, 600, "过大收敛到上限") + +local client = make(180) +Assert.eq(client:configured(), true) +client:request("GET", "/api/Series/all-v2", { pageNumber = 1 }, nil, function() end) +Assert.eq(captured.timeout, 180, "超时透传到 HTTP 请求,长拉书架不再被 30s 掐断") +Assert.matches(captured.url, "^http://kav/api/Series/all%-v2%?") +Assert.eq(captured.headers["x-api-key"], "k") + +-- 统计拉取:`Libraries` 是重复键(逗号串会被服务端当成一个库,恒返回 0 条), +-- 其余参数按名排序,PageSize 用服务端接受的上限 200。 +Assert.eq( + client:url("/api/Stats/reading-history", { + TimeZoneId = "Asia/Shanghai", Libraries = { 2, 1 }, PageNumber = 1, PageSize = 200, + }), + "http://kav/api/Stats/reading-history?Libraries=2&Libraries=1&PageNumber=1&PageSize=200&TimeZoneId=Asia%2FShanghai" +) +Assert.eq(client:url("/api/Image/series-cover", { seriesId = "10" }), + "http://kav/api/Image/series-cover?seriesId=10", "单值参数与 formEncode 同形") + +-- 分页头(挂在响应上,不在 body 里):只认 totalPages。 +Assert.eq(Client.totalPages('{"currentPage":1,"itemsPerPage":200,"totalItems":316,"totalPages":2}'), 2) +Assert.eq(Client.totalPages('{"totalPages":0}'), 0, "0 页 = 没有数据,读成 nil 会让调用方按「本页拉满」再拉一页") +Assert.is_nil(Client.totalPages('{"currentPage":1}'), "没有 totalPages 就当不可信,调用方走兜底") +Assert.is_nil(Client.totalPages('{"totalPages":-1}'), "负数不可信") +Assert.is_nil(Client.totalPages(nil)) +Assert.is_nil(Client.totalPages("")) +Assert.is_nil(Client.totalPages("oops"), "反代错误页不能当分页头") diff --git a/tests/kavita/continue_point_spec.lua b/tests/kavita/continue_point_spec.lua new file mode 100644 index 0000000..83ee8f3 --- /dev/null +++ b/tests/kavita/continue_point_spec.lua @@ -0,0 +1,133 @@ +--[[-- +卷列表 / 系列页共用的续读目标:主线 = 最远有进度的卷,回顾旧卷只标「上次翻阅」。 + +@module tests.moonsource_kavita.continue_point_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") + +local CP = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/continue_point.lua") + +local function vol(chapter_id, title, pages, pages_read) + return { + idx = chapter_id, chapterId = chapter_id, title = title, + pages = pages, pagesRead = pages_read or 0, + } +end + +local toc = { + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 40), + vol(103, "第 3 卷", 100, 0), + vol(104, "第 4 卷", 100, 0), +} + +-- 未开始 +local fresh = CP.pick({ + vol(101, "第 1 卷", 100, 0), + vol(102, "第 2 卷", 100, 0), +}, {}) +Assert.eq(fresh.kind, "fresh") +Assert.eq(fresh.entry.chapterId, 101) +Assert.eq(fresh.page, 0) +local fresh_text, fresh_caption = CP.describe(fresh, "系列") +Assert.eq(fresh_text, "开始阅读 · 第 1 卷") +Assert.eq(fresh_caption, "共 100 页") + +-- 读到第 2 卷一半:主线是第 2 卷 +local mid = CP.pick(toc, {}) +Assert.eq(mid.kind, "continue") +Assert.eq(mid.entry.chapterId, 102) +Assert.eq(mid.fraction, 0.4) +Assert.eq(mid.page, 40) +Assert.eq(mid.total_pages, 100) +local mid_text, mid_caption = CP.describe(mid, "系列") +Assert.eq(mid_text, "继续阅读 · 第 2 卷") +Assert.eq(mid_caption, "第 40/100 页 · 40%") +Assert.is_nil(mid.browsed) + +-- 第 2 卷读完:顺延第 3 卷 +local rolled = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), + vol(103, "第 3 卷", 100, 0), +}, {}) +Assert.eq(rolled.entry.chapterId, 103) +Assert.eq(rolled.kind, "continue") +Assert.eq(rolled.page, 0) + +-- 全部读完:回到第 1 卷,kind = done +local done = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), +}, {}) +Assert.eq(done.kind, "done") +Assert.eq(done.entry.chapterId, 101) + +-- 读到第 4 卷、回头翻第 1 卷:主线不动,第 1 卷只作「上次翻阅」 +local updated = { [101] = 300, [104] = 200 } +local review = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), + vol(103, "第 3 卷", 100, 100), + vol(104, "第 4 卷", 100, 50), +}, { + updated_at = function(e) return updated[e.chapterId] end, +}) +Assert.eq(review.entry.chapterId, 104, "主线仍是最远的第 4 卷") +Assert.eq(review.browsed.chapterId, 101, "上次翻阅单独返回") + +-- 上次翻阅 == 主线:不返回标记 +local same = CP.pick(toc, { updated_at = function(e) return e.chapterId == 102 and 500 or 0 end }) +Assert.is_nil(same.browsed) + +-- 注入 fraction / page(本地 ProgressDB 比 toc 快照新) +local local_better = CP.pick(toc, { + fraction = function(e) return e.chapterId == 102 and 0.9 or nil end, + page = function(e) + if e.chapterId == 102 then return { page = 90, total = 100 } end + end, +}) +Assert.eq(local_better.fraction, 0.9) +Assert.eq(local_better.page, 90) + +-- pages == 0 的卷不参与 +local zero = CP.pick({ + vol(101, "第 1 卷", 0, 0), + vol(102, "第 2 卷", 100, 10), +}, {}) +Assert.eq(zero.entry.chapterId, 102) + +-- 空目录 +Assert.is_nil(CP.pick({}, {})) +Assert.is_nil(CP.pick(nil, nil)) + +-- 服务端已读完、本机重新打开留下 1%:仍按已读完处理,主线顺延下一卷。 +local reread = CP.pick({ + vol(101, "第 1 卷", 100, 100), + vol(102, "第 2 卷", 100, 100), + vol(103, "第 3 卷", 100, 0), +}, { fraction = function(e) return e.chapterId == 102 and 0.01 or nil end }) +Assert.eq(reread.entry.chapterId, 103, "已读完的卷不会被本机低进度拖回主线") +Assert.eq(reread.kind, "continue") + + +-- 调用方说已读完(kamare 三源)时同样按 fraction 1,不再被本机低进度拖回。 +local by_caller = CP.pick({ + vol(101, "第 1 卷", 100, 0), + vol(102, "第 2 卷", 100, 0), +}, { + fraction = function(e) return e.chapterId == 101 and 0.01 or nil end, + complete = function(e) return e.chapterId == 101 end, +}) +Assert.eq(by_caller.entry.chapterId, 102, "调用方标记已读完的卷不会成为主线") + + +-- 卷名:优先标题;空 / 退化成系列名时兜底第 N 卷 +Assert.eq(CP.label({ idx = 3, title = "ONE PIECE (3)" }, "航海王"), "ONE PIECE (3)") +Assert.eq(CP.label({ idx = 3, title = "" }, "航海王"), "第 3 卷") +Assert.eq(CP.label({ idx = 3, title = "航海王" }, "航海王"), "第 3 卷") +Assert.eq(CP.label({ idx = 3 }, "航海王"), "第 3 卷") +Assert.eq(CP.label(nil, "航海王"), "?") diff --git a/tests/kavita/fixtures/history_7453.lua b/tests/kavita/fixtures/history_7453.lua new file mode 100644 index 0000000..9949e8f --- /dev/null +++ b/tests/kavita/fixtures/history_7453.lua @@ -0,0 +1,140 @@ +--[[-- +样本 fixture:`GET /api/Stats/reading-history/series/7453` 实测响应(2026-10-16,Kavita 0.9.1.4) +的精简版,只留聚合用到的字段(seriesId / localDate / startTimeUtc / chapters[])。 + +对账基线(research-kavita-stats-pull.md §3):64 条会话 / 14,237s;逐日见 stats_spec 用例。 +来源完整响应:/tmp/opencode/kavita/live/history-7453-all.json(提交时精简,数值逐条未改)。 + +@module tests.extensions.kavita.fixtures.history_7453 +--]] +return { + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T13:49:02.6722926", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T13:49:02.6722926", durationSeconds = 845, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:51:10.7006183", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:51:10.7006183", durationSeconds = 638, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:14:33.5066159", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:14:33.5066159", durationSeconds = 436, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T08:01:09.6078347", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T08:01:09.6078347", durationSeconds = 33, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T07:20:02.0863122", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T07:20:02.0863122", durationSeconds = 156, pagesRead = 15 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T04:38:27.7268649", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T04:38:27.7268649", durationSeconds = 462, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T03:25:22.1307379", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T03:25:22.1307379", durationSeconds = 266, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T02:59:07.9600274", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T02:59:07.9600274", durationSeconds = 126, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:50:29.2326588", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T14:50:29.2326588", durationSeconds = 329, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:55:48.5704762", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T13:55:48.5704762", durationSeconds = 716, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:59:54.4012612", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:59:54.4012612", durationSeconds = 210, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:32:09.2873459", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:32:09.2873459", durationSeconds = 354, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T10:50:12.8325335", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T10:50:12.8325335", durationSeconds = 427, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:55:45.2531997", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T09:55:45.2531997", durationSeconds = 229, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T08:18:25.5482677", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T08:18:25.5482677", durationSeconds = 631, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:35:44.8950968", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:56:37.9521487", durationSeconds = 597, pagesRead = 5 }, + { chapterId = 11273, startTimeUtc = "2026-10-14T06:35:44.8950968", durationSeconds = 529, pagesRead = -6 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:12:27.3026502", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:12:27.3026502", durationSeconds = 686, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:35:38.8926445", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T05:35:38.8926445", durationSeconds = 674, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:36:59.7411875", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T03:36:59.7411875", durationSeconds = 1352, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:39:31.4453653", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T01:39:31.4453653", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:56:50.7578846", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T14:56:50.7578846", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T12:50:13.6195947", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T12:50:13.6195947", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T10:49:24.2700176", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T10:49:24.2700176", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T09:19:44.4142404", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T09:19:44.4142404", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T07:17:51.0855549", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T07:17:51.0855549", durationSeconds = 31, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T06:23:56.2429684", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T06:23:56.2429684", durationSeconds = 948, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:44:11.1456271", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:44:11.1456271", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:04:52.1419963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:04:52.1419963", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T03:52:47.3926019", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-12T03:52:47.3926019", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T15:16:45.9848037", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T15:16:45.9848037", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:54:13.613368", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:54:13.613368", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:35:43.0809755", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:35:43.0809755", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T12:58:29.291105", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T12:58:29.291105", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T11:00:42.6215043", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T11:00:42.6215043", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T04:17:28.3592015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T04:17:28.3592015", durationSeconds = 512, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T04:44:42.7023417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T04:44:42.7023417", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:55:35.74839", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:55:35.74839", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:39:55.2030981", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:39:55.2030981", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T14:45:39.0731175", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T14:45:39.0731175", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:44:06.636679", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:44:06.636679", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:13:20.7857153", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:13:20.7857153", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:40:28.7189645", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:40:28.7189645", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:05:17.6951039", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:05:17.6951039", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T14:34:05.7981443", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T14:34:05.7981443", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T13:12:53.6969824", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T13:12:53.6969824", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:48:06.6315963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:48:06.6315963", durationSeconds = 544, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:02:33.6484158", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:02:33.6484158", durationSeconds = 611, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T10:31:08.475182", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T10:31:08.475182", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T09:03:45.5309711", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T09:03:45.5309711", durationSeconds = 86, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:59:09.2881628", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:59:09.2881628", durationSeconds = 263, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:20:18.0105615", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:20:18.0105615", durationSeconds = 233, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T06:48:51.312417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T06:48:51.312417", durationSeconds = 296, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T04:05:45.0300961", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T04:05:45.0300961", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T13:44:15.125016", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T13:44:15.125016", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T09:45:01.0814021", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T09:45:01.0814021", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T05:19:38.9892914", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T05:19:38.9892914", durationSeconds = 503, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:01:31.4949015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T12:01:31.4949015", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T11:37:48.0185472", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T11:37:48.0185472", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T03:21:10.9150125", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T03:21:10.9150125", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T02:50:29.5547188", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T02:50:29.5547188", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T14:10:59.8916334", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T14:10:59.8916334", durationSeconds = 195, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T12:18:33.1689018", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T12:18:33.1689018", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:25:25.4088288", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:25:25.4088288", durationSeconds = 86, pagesRead = 2 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:01:44.7835505", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:01:44.7835505", durationSeconds = 230, pagesRead = 0 } } }, +} diff --git a/tests/kavita/fixtures/history_all.lua b/tests/kavita/fixtures/history_all.lua new file mode 100644 index 0000000..dbfd97b --- /dev/null +++ b/tests/kavita/fixtures/history_all.lua @@ -0,0 +1,657 @@ +--[[-- +样本 fixture:`GET /api/Stats/reading-history` 全量实测响应(2026-10-16,Kavita 0.9.1.4)的 +精简版,只留聚合用到的字段(seriesId / localDate / startTimeUtc / chapters[]),共 316 条会话 / +60 个系列 / 2 页。 + +数值逐条未改;对账基线 = research-kavita-stats-pull.md §2(逐日时长 / 页数)与 §4(Σ=60,238s / +1,406 页 / 起点 2026-09-18)。来源完整响应:/tmp/opencode/kavita/live/history-all-sep-oct.json。 + +@module tests.extensions.kavita.fixtures.history_all +--]] +return { + { seriesId = 7606, localDate = "2026-10-16T00:00:00", startTimeUtc = "2026-10-15T23:51:47.4527045", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-15T23:51:47.4527045", durationSeconds = 220, pagesRead = 6 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T13:49:02.6722926", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T13:49:02.6722926", durationSeconds = 845, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T13:41:03.9585123", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-15T13:41:03.9585123", durationSeconds = 469, pagesRead = 6 } } }, + { seriesId = 7606, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T12:18:53.1535569", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-15T12:18:53.1535569", durationSeconds = 163, pagesRead = 7 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:51:10.7006183", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:51:10.7006183", durationSeconds = 638, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:40:49.4449693", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-15T11:40:49.4449693", durationSeconds = 335, pagesRead = 1 } } }, + { seriesId = 10634, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:35:04.1639136", chapters = { + { chapterId = 17863, startTimeUtc = "2026-10-15T11:38:58.0370869", durationSeconds = 81, pagesRead = 15 }, + { chapterId = 17868, startTimeUtc = "2026-10-15T11:35:04.1639136", durationSeconds = 210, pagesRead = 29 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:14:33.5066159", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T11:14:33.5066159", durationSeconds = 436, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T11:04:40.7474367", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-15T11:04:40.7474367", durationSeconds = 321, pagesRead = 44 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T08:01:09.6078347", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T08:01:09.6078347", durationSeconds = 33, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T07:20:02.0863122", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T07:20:02.0863122", durationSeconds = 156, pagesRead = 15 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T04:38:27.7268649", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T04:38:27.7268649", durationSeconds = 462, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T03:25:22.1307379", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T03:25:22.1307379", durationSeconds = 266, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-15T00:00:00", startTimeUtc = "2026-10-15T02:59:07.9600274", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-15T02:59:07.9600274", durationSeconds = 126, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:50:29.2326588", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T14:50:29.2326588", durationSeconds = 329, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:38:39.3797696", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-14T14:38:39.3797696", durationSeconds = 481, pagesRead = 32 } } }, + { seriesId = 10634, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T14:08:54.1661113", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-14T14:08:54.1661113", durationSeconds = 309, pagesRead = 27 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:55:48.5704762", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T13:55:48.5704762", durationSeconds = 716, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:49:23.172248", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-14T13:49:23.172248", durationSeconds = 305, pagesRead = 6 } } }, + { seriesId = 10634, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T13:03:43.5815681", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-14T13:03:43.5815681", durationSeconds = 22, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:59:54.4012612", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:59:54.4012612", durationSeconds = 210, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T12:32:09.2873459", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T12:32:09.2873459", durationSeconds = 354, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T10:50:12.8325335", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T10:50:12.8325335", durationSeconds = 427, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:55:45.2531997", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T09:55:45.2531997", durationSeconds = 229, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:17:05.53145", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T09:17:05.53145", durationSeconds = 433, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T09:13:54.1770611", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T09:13:54.1770611", durationSeconds = 141, pagesRead = 3 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T08:31:01.497007", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T08:31:01.497007", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T08:18:25.5482677", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T08:18:25.5482677", durationSeconds = 631, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:55:05.3240629", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-14T07:55:05.3240629", durationSeconds = 82, pagesRead = 0 } } }, + { seriesId = 10705, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:38:45.2095335", chapters = { + { chapterId = 18930, startTimeUtc = "2026-10-14T07:38:45.2095335", durationSeconds = 206, pagesRead = 3 } } }, + { seriesId = 7540, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:34:26.9247375", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-14T07:34:26.9247375", durationSeconds = 83, pagesRead = 5 } } }, + { seriesId = 10720, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:16:16.0691328", chapters = { + { chapterId = 18951, startTimeUtc = "2026-10-14T07:16:16.0691328", durationSeconds = 72, pagesRead = 10 } } }, + { seriesId = 8661, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:14:59.4980606", chapters = { + { chapterId = 12763, startTimeUtc = "2026-10-14T07:14:59.4980606", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7805, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:14:45.0436933", chapters = { + { chapterId = 11791, startTimeUtc = "2026-10-14T07:14:45.0436933", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T07:14:08.0963104", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-14T07:14:08.0963104", durationSeconds = 71, pagesRead = 2 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:46:46.3439122", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T07:07:38.102712", durationSeconds = 0, pagesRead = 0 }, + { chapterId = 11501, startTimeUtc = "2026-10-14T06:46:46.3439122", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:54:53.1919748", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T07:06:44.0374852", durationSeconds = 21, pagesRead = 24 }, + { chapterId = 11285, startTimeUtc = "2026-10-14T06:54:53.1919748", durationSeconds = 48, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:35:44.8950968", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:56:37.9521487", durationSeconds = 597, pagesRead = 5 }, + { chapterId = 11273, startTimeUtc = "2026-10-14T06:35:44.8950968", durationSeconds = 529, pagesRead = -6 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:12:27.3026502", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T06:12:27.3026502", durationSeconds = 686, pagesRead = 1 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T06:02:06.7713486", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T06:02:06.7713486", durationSeconds = 647, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:48:30.213286", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T05:48:30.213286", durationSeconds = 113, pagesRead = 1 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:47:30.9663527", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T05:47:30.9663527", durationSeconds = 40, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T05:35:38.8926445", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T05:35:38.8926445", durationSeconds = 674, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:36:59.7411875", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T03:36:59.7411875", durationSeconds = 1352, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:28:46.1491425", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-14T03:28:46.1491425", durationSeconds = 794, pagesRead = -1 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T03:16:21.8058422", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T03:16:21.8058422", durationSeconds = 1063, pagesRead = 1 } } }, + { seriesId = 7606, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:55:37.5163534", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-14T01:55:37.5163534", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:49:18.2803981", chapters = { + { chapterId = 14594, startTimeUtc = "2026-10-14T01:49:18.2803981", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-14T00:00:00", startTimeUtc = "2026-10-14T01:39:31.4453653", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-14T01:39:31.4453653", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:57:39.6850524", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-13T14:57:39.6850524", durationSeconds = 296, pagesRead = 43 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:56:50.7578846", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T14:56:50.7578846", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T14:36:12.2101045", chapters = { + { chapterId = 17868, startTimeUtc = "2026-10-13T14:42:41.461277", durationSeconds = 73, pagesRead = 17 }, + { chapterId = 17861, startTimeUtc = "2026-10-13T14:36:12.2101045", durationSeconds = 382, pagesRead = 50 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T13:30:56.9584871", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-13T13:30:56.9584871", durationSeconds = 965, pagesRead = 35 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T12:50:13.6195947", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T12:50:13.6195947", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T11:07:48.1054905", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-13T11:07:48.1054905", durationSeconds = 1557, pagesRead = 87 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T10:49:24.2700176", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T10:49:24.2700176", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T10:33:26.9620773", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-13T10:33:26.9620773", durationSeconds = 85, pagesRead = 9 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T09:19:44.4142404", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T09:19:44.4142404", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T08:41:22.7503239", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-13T08:41:22.7503239", durationSeconds = 177, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T07:17:51.0855549", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T07:17:51.0855549", durationSeconds = 31, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T06:23:56.2429684", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T06:23:56.2429684", durationSeconds = 948, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:44:11.1456271", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:44:11.1456271", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-13T00:00:00", startTimeUtc = "2026-10-13T04:04:52.1419963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-13T04:04:52.1419963", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T13:41:25.4902953", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-12T13:41:25.4902953", durationSeconds = 77, pagesRead = 5 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T04:30:51.522376", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-12T04:30:51.522376", durationSeconds = 26, pagesRead = 4 } } }, + { seriesId = 7453, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T03:52:47.3926019", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-12T03:52:47.3926019", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T02:50:17.2681685", chapters = { + { chapterId = 17861, startTimeUtc = "2026-10-12T02:59:07.2940778", durationSeconds = 505, pagesRead = 5 }, + { chapterId = 17855, startTimeUtc = "2026-10-12T02:50:17.2681685", durationSeconds = 518, pagesRead = 12 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-12T02:26:17.4191481", chapters = { + { chapterId = 17855, startTimeUtc = "2026-10-12T02:26:17.4191481", durationSeconds = 332, pagesRead = 27 } } }, + { seriesId = 10600, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-11T16:06:22.9336343", chapters = { + { chapterId = 17139, startTimeUtc = "2026-10-11T16:06:22.9336343", durationSeconds = 34, pagesRead = 11 } } }, + { seriesId = 10634, localDate = "2026-10-12T00:00:00", startTimeUtc = "2026-10-11T16:00:00.7226412", chapters = { + { chapterId = 17855, startTimeUtc = "2026-10-11T16:00:00.7226412", durationSeconds = 311, pagesRead = 39 } } }, + { seriesId = 10634, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T15:54:42.9913657", chapters = { + { chapterId = 17855, startTimeUtc = "2026-10-11T15:54:42.9913657", durationSeconds = 137, pagesRead = 26 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T15:16:45.9848037", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T15:16:45.9848037", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:54:13.613368", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:54:13.613368", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T14:35:43.0809755", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T14:35:43.0809755", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T12:58:29.291105", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T12:58:29.291105", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T11:00:42.6215043", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T11:00:42.6215043", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T04:17:28.3592015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-11T04:17:28.3592015", durationSeconds = 512, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-11T00:00:00", startTimeUtc = "2026-10-11T02:53:45.4676925", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-11T02:53:45.4676925", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T15:00:59.375396", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T15:00:59.375396", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T09:37:25.4148239", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T09:37:25.4148239", durationSeconds = 2, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T08:58:13.142957", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T08:58:13.142957", durationSeconds = 9, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T08:15:36.7468877", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T08:15:36.7468877", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T07:52:18.8289612", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T07:52:18.8289612", durationSeconds = 164, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T07:10:45.3655221", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-10T07:10:45.3655221", durationSeconds = 33, pagesRead = 1 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T04:44:42.7023417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T04:44:42.7023417", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:55:35.74839", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:55:35.74839", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:41:12.3904529", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T03:41:12.3904529", durationSeconds = 12, pagesRead = 2 } } }, + { seriesId = 7453, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T03:39:55.2030981", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-10T03:39:55.2030981", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T02:29:21.0392738", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T02:29:21.0392738", durationSeconds = 40, pagesRead = 2 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T02:12:18.2048535", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T02:12:18.2048535", durationSeconds = 53, pagesRead = 3 } } }, + { seriesId = 7606, localDate = "2026-10-10T00:00:00", startTimeUtc = "2026-10-10T01:55:30.4051153", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-10T01:55:30.4051153", durationSeconds = 50, pagesRead = 2 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T14:45:39.0731175", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T14:45:39.0731175", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:43:07.3149178", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T13:43:07.3149178", durationSeconds = 5, pagesRead = 0 } } }, + { seriesId = 10735, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:32:16.6705302", chapters = { + { chapterId = 18969, startTimeUtc = "2026-10-09T13:32:16.6705302", durationSeconds = 163, pagesRead = 5 } } }, + { seriesId = 10698, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:30:11.0145349", chapters = { + { chapterId = 18923, startTimeUtc = "2026-10-09T13:30:11.0145349", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T13:17:56.7622935", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T13:17:56.7622935", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:51:14.1858092", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T11:51:14.1858092", durationSeconds = 7, pagesRead = 0 } } }, + { seriesId = 10732, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:20:33.6944863", chapters = { + { chapterId = 18966, startTimeUtc = "2026-10-09T11:20:33.6944863", durationSeconds = 29, pagesRead = 21 } } }, + { seriesId = 10735, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:15:31.2028337", chapters = { + { chapterId = 18969, startTimeUtc = "2026-10-09T11:15:31.2028337", durationSeconds = 80, pagesRead = 33 } } }, + { seriesId = 10724, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:12:30.4622536", chapters = { + { chapterId = 18957, startTimeUtc = "2026-10-09T11:12:30.4622536", durationSeconds = 4, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T11:04:22.6125371", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T11:04:22.6125371", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10724, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T10:29:16.8959018", chapters = { + { chapterId = 18957, startTimeUtc = "2026-10-09T10:29:16.8959018", durationSeconds = 7, pagesRead = 16 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:51:43.6940126", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T09:51:43.6940126", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:34:29.5406473", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-09T09:34:29.5406473", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:34:17.5161863", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T09:34:17.5161863", durationSeconds = 5, pagesRead = 1 } } }, + { seriesId = 7606, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T09:10:02.1865718", chapters = { + { chapterId = 11501, startTimeUtc = "2026-10-09T09:10:02.1865718", durationSeconds = 759, pagesRead = 11 } } }, + { seriesId = 10708, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T08:18:07.1620583", chapters = { + { chapterId = 18933, startTimeUtc = "2026-10-09T08:18:07.1620583", durationSeconds = 15, pagesRead = 2 } } }, + { seriesId = 10707, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:55:45.2365064", chapters = { + { chapterId = 18932, startTimeUtc = "2026-10-09T07:55:45.2365064", durationSeconds = 7, pagesRead = 4 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:44:06.636679", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:44:06.636679", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T07:13:20.7857153", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T07:13:20.7857153", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:40:28.7189645", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:40:28.7189645", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T04:05:17.6951039", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-09T04:05:17.6951039", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T03:03:56.2211648", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-09T03:03:56.2211648", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9292, localDate = "2026-10-09T00:00:00", startTimeUtc = "2026-10-09T01:10:42.7539032", chapters = { + { chapterId = 13569, startTimeUtc = "2026-10-09T01:10:42.7539032", durationSeconds = 8, pagesRead = 0 } } }, + { seriesId = 9292, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T15:26:10.3634693", chapters = { + { chapterId = 13569, startTimeUtc = "2026-10-08T15:26:10.3634693", durationSeconds = 15, pagesRead = 10 } } }, + { seriesId = 9249, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T15:12:20.8270779", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-08T15:12:20.8270779", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T14:34:05.7981443", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T14:34:05.7981443", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T13:12:53.6969824", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T13:12:53.6969824", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:49:28.3986198", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-08T11:49:28.3986198", durationSeconds = 95, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:48:06.6315963", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:48:06.6315963", durationSeconds = 544, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T10:57:20.8373954", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-08T11:15:47.102", durationSeconds = 1111, pagesRead = 0 }, + { chapterId = 11285, startTimeUtc = "2026-10-08T10:57:20.8373954", durationSeconds = 406, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T11:02:33.6484158", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T11:02:33.6484158", durationSeconds = 611, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T10:31:08.475182", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T10:31:08.475182", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T09:03:45.5309711", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T09:03:45.5309711", durationSeconds = 86, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:59:09.2881628", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:59:09.2881628", durationSeconds = 263, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T07:20:18.0105615", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T07:20:18.0105615", durationSeconds = 233, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T06:48:51.312417", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T06:48:51.312417", durationSeconds = 296, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T04:42:54.7579483", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-08T04:42:54.7579483", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T04:05:45.0300961", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-08T04:05:45.0300961", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T02:52:33.5236184", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-08T02:52:33.5236184", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-08T00:00:00", startTimeUtc = "2026-10-08T02:20:36.4169563", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-08T02:20:36.4169563", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T13:44:15.125016", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T13:44:15.125016", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T09:45:01.0814021", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T09:45:01.0814021", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-07T00:00:00", startTimeUtc = "2026-10-07T05:19:38.9892914", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-07T05:19:38.9892914", durationSeconds = 503, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T13:00:26.371751", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-06T13:00:26.371751", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:21:25.7149691", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-06T12:21:25.7149691", durationSeconds = 489, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:07:54.0702478", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-06T12:07:54.0702478", durationSeconds = 320, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T12:01:31.4949015", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T12:01:31.4949015", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T11:37:48.0185472", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T11:37:48.0185472", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T03:21:10.9150125", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T03:21:10.9150125", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-06T00:00:00", startTimeUtc = "2026-10-06T02:50:29.5547188", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-06T02:50:29.5547188", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T14:10:59.8916334", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T14:10:59.8916334", durationSeconds = 195, pagesRead = 0 } } }, + { seriesId = 7453, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T12:18:33.1689018", chapters = { + { chapterId = 11273, startTimeUtc = "2026-10-05T12:18:33.1689018", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T11:54:12.1093305", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-05T11:54:12.1093305", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T11:34:55.3786363", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-05T11:34:55.3786363", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-05T00:00:00", startTimeUtc = "2026-10-05T09:15:25.8448735", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-05T09:15:25.8448735", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-04T00:00:00", startTimeUtc = "2026-10-04T09:36:48.7199331", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-04T09:36:48.7199331", durationSeconds = 226, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-04T00:00:00", startTimeUtc = "2026-10-04T06:13:00.6097898", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-04T06:13:00.6097898", durationSeconds = 412, pagesRead = 1 } } }, + { seriesId = 9249, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T14:24:26.495891", chapters = { + { chapterId = 13493, startTimeUtc = "2026-10-03T14:24:26.495891", durationSeconds = 337, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T13:00:16.6885142", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-03T13:00:16.6885142", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10588, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T12:25:37.0931958", chapters = { + { chapterId = 16914, startTimeUtc = "2026-10-03T12:25:37.0931958", durationSeconds = 358, pagesRead = 24 } } }, + { seriesId = 7460, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T12:09:12.6479717", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-03T12:09:12.6479717", durationSeconds = 409, pagesRead = 1 } } }, + { seriesId = 7540, localDate = "2026-10-03T00:00:00", startTimeUtc = "2026-10-03T02:10:46.4251132", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-03T02:10:46.4251132", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-10-02T00:00:00", startTimeUtc = "2026-10-02T04:04:43.6820861", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-02T04:04:43.6820861", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-02T00:00:00", startTimeUtc = "2026-10-02T01:31:26.0795951", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-02T01:31:26.0795951", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-02T00:00:00", startTimeUtc = "2026-10-02T01:19:47.6481957", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-02T01:19:47.6481957", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T14:01:45.997983", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T14:01:45.997983", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10585, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T13:36:40.8506172", chapters = { + { chapterId = 16862, startTimeUtc = "2026-10-01T13:36:40.8506172", durationSeconds = 113, pagesRead = 8 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T13:35:51.0806955", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T13:35:51.0806955", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:55:01.4289659", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:55:01.4289659", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:41:02.5910426", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:41:02.5910426", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:28:36.4902671", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:28:36.4902671", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:10:02.1536935", chapters = { + { chapterId = 11285, startTimeUtc = "2026-10-01T11:10:02.1536935", durationSeconds = 289, pagesRead = 0 } } }, + { seriesId = 10585, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T11:04:28.7600787", chapters = { + { chapterId = 16862, startTimeUtc = "2026-10-01T11:04:28.7600787", durationSeconds = 241, pagesRead = 15 } } }, + { seriesId = 7540, localDate = "2026-10-01T00:00:00", startTimeUtc = "2026-10-01T10:32:28.7130273", chapters = { + { chapterId = 13394, startTimeUtc = "2026-10-01T10:32:28.7130273", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T13:03:27.0677663", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-30T13:03:27.0677663", durationSeconds = 1530, pagesRead = -3 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T13:02:32.9357375", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T13:02:32.9357375", durationSeconds = 22, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T12:28:33.282795", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T12:28:33.282795", durationSeconds = 189, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T11:37:13.1197026", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-30T11:37:13.1197026", durationSeconds = 25, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T11:33:44.6966312", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T11:33:44.6966312", durationSeconds = 130, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T09:14:25.3316858", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T09:14:25.3316858", durationSeconds = 37, pagesRead = -4 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T08:52:37.2436808", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T08:52:37.2436808", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T07:54:07.7610298", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T07:54:07.7610298", durationSeconds = 5, pagesRead = 0 } } }, + { seriesId = 7805, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:56:53.2380567", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-30T03:56:53.2380567", durationSeconds = 6, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:42:57.6124947", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T03:42:57.6124947", durationSeconds = 1749, pagesRead = 4 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:23:47.6591832", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T03:23:47.6591832", durationSeconds = 548, pagesRead = 0 } } }, + { seriesId = 10684, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T03:12:37.6514083", chapters = { + { chapterId = 18895, startTimeUtc = "2026-09-30T03:12:37.6514083", durationSeconds = 68, pagesRead = 15 } } }, + { seriesId = 10556, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T01:58:37.2644751", chapters = { + { chapterId = 16398, startTimeUtc = "2026-09-30T01:58:37.2644751", durationSeconds = 5, pagesRead = 6 } } }, + { seriesId = 7805, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:43:20.1361231", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-30T01:16:48.8842393", durationSeconds = 387, pagesRead = 0 }, + { chapterId = 11791, startTimeUtc = "2026-09-30T00:43:20.1361231", durationSeconds = 204, pagesRead = 1 } } }, + { seriesId = 8661, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:46:55.2653707", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-30T00:46:55.2653707", durationSeconds = 1330, pagesRead = 3 } } }, + { seriesId = 7460, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:25:09.4803818", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-30T00:37:14.7633119", durationSeconds = 43, pagesRead = 0 }, + { chapterId = 11285, startTimeUtc = "2026-09-30T00:25:09.4803818", durationSeconds = 32, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:30:04.5325361", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-30T00:30:04.5325361", durationSeconds = 222, pagesRead = -1 } } }, + { seriesId = 9249, localDate = "2026-09-30T00:00:00", startTimeUtc = "2026-09-30T00:27:17.7123717", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-30T00:27:17.7123717", durationSeconds = 108, pagesRead = 1 } } }, + { seriesId = 10584, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:27:07.2391439", chapters = { + { chapterId = 16853, startTimeUtc = "2026-09-29T15:27:07.2391439", durationSeconds = 6, pagesRead = 6 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:23:24.6913136", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T15:23:24.6913136", durationSeconds = 51, pagesRead = 1 } } }, + { seriesId = 10584, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:11:40.8997791", chapters = { + { chapterId = 16853, startTimeUtc = "2026-09-29T15:11:40.8997791", durationSeconds = 24, pagesRead = 14 } } }, + { seriesId = 8661, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:10:15.9077958", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-29T15:10:15.9077958", durationSeconds = 23, pagesRead = 6 } } }, + { seriesId = 7540, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T15:02:32.6735695", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-29T15:02:32.6735695", durationSeconds = 452, pagesRead = 7 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:58:04.6106466", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T14:58:04.6106466", durationSeconds = 82, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:38:04.1555096", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-29T14:38:04.1555096", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:12:48.9320003", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-29T14:12:48.9320003", durationSeconds = 86, pagesRead = 3 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T14:07:43.3739949", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T14:07:43.3739949", durationSeconds = 439, pagesRead = 20 } } }, + { seriesId = 10560, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T13:55:37.9561391", chapters = { + { chapterId = 16493, startTimeUtc = "2026-09-29T13:55:37.9561391", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 9249, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:39:52.7733874", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-29T12:39:52.7733874", durationSeconds = 31, pagesRead = 3 } } }, + { seriesId = 10559, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:33:10.2857117", chapters = { + { chapterId = 16479, startTimeUtc = "2026-09-29T12:33:10.2857117", durationSeconds = 7, pagesRead = 15 } } }, + { seriesId = 10560, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:51:35.4694759", chapters = { + { chapterId = 16493, startTimeUtc = "2026-09-29T12:22:43.7993875", durationSeconds = 936, pagesRead = 2 }, + { chapterId = 16493, startTimeUtc = "2026-09-29T11:51:35.4694759", durationSeconds = 1223, pagesRead = 12 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:58:50.1222492", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T12:21:19.3748615", durationSeconds = 909, pagesRead = -2 }, + { chapterId = 11285, startTimeUtc = "2026-09-29T11:58:50.1222492", durationSeconds = 20, pagesRead = 0 } } }, + { seriesId = 10563, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:17:34.2571271", chapters = { + { chapterId = 16505, startTimeUtc = "2026-09-29T12:17:34.2571271", durationSeconds = 36, pagesRead = 17 } } }, + { seriesId = 10562, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T12:07:43.0627869", chapters = { + { chapterId = 16502, startTimeUtc = "2026-09-29T12:07:43.0627869", durationSeconds = 70, pagesRead = 17 } } }, + { seriesId = 7910, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:50:25.270629", chapters = { + { chapterId = 11904, startTimeUtc = "2026-09-29T11:50:25.270629", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7910, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:25:02.6769601", chapters = { + { chapterId = 11896, startTimeUtc = "2026-09-29T11:25:16.5490822", durationSeconds = 442, pagesRead = 6 }, + { chapterId = 11898, startTimeUtc = "2026-09-29T11:25:02.6769601", durationSeconds = 328, pagesRead = 1 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:24:52.8021347", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T11:24:52.8021347", durationSeconds = 525, pagesRead = 15 } } }, + { seriesId = 10639, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T11:08:39.2618986", chapters = { + { chapterId = 18031, startTimeUtc = "2026-09-29T11:08:39.2618986", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 10556, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:56:40.6001656", chapters = { + { chapterId = 16398, startTimeUtc = "2026-09-29T10:56:40.6001656", durationSeconds = 11, pagesRead = 9 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:45:47.6455857", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T10:45:47.6455857", durationSeconds = 4, pagesRead = 4 } } }, + { seriesId = 7462, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:45:05.5896105", chapters = { + { chapterId = 11290, startTimeUtc = "2026-09-29T10:45:05.5896105", durationSeconds = 3, pagesRead = 1 } } }, + { seriesId = 7540, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:35:52.0518521", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-29T10:35:52.0518521", durationSeconds = 39, pagesRead = 6 } } }, + { seriesId = 7805, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:34:39.8658599", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-29T10:34:39.8658599", durationSeconds = 12, pagesRead = 3 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:25:25.4088288", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:25:25.4088288", durationSeconds = 86, pagesRead = 2 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:22:33.7903381", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T10:22:33.7903381", durationSeconds = 167, pagesRead = 4 } } }, + { seriesId = 7453, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T10:01:44.7835505", chapters = { + { chapterId = 11271, startTimeUtc = "2026-09-29T10:01:44.7835505", durationSeconds = 230, pagesRead = 0 } } }, + { seriesId = 10001, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:57:30.1875022", chapters = { + { chapterId = 14591, startTimeUtc = "2026-09-29T09:57:30.1875022", durationSeconds = 14, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:39:33.8232177", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-29T09:39:33.8232177", durationSeconds = 332, pagesRead = 19 } } }, + { seriesId = 7476, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:30:15.0902649", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-29T09:30:15.0902649", durationSeconds = 27, pagesRead = 0 } } }, + { seriesId = 7476, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T09:02:28.8339509", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-29T09:02:28.8339509", durationSeconds = 267, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T08:51:39.2655404", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T08:51:39.2655404", durationSeconds = 39, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T08:33:15.8755207", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T08:33:15.8755207", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10004, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T08:14:10.4993494", chapters = { + { chapterId = 14594, startTimeUtc = "2026-09-29T08:14:10.4993494", durationSeconds = 106, pagesRead = 0 } } }, + { seriesId = 7476, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T07:47:38.8544242", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-29T08:02:48.272453", durationSeconds = 461, pagesRead = -1 }, + { chapterId = 11317, startTimeUtc = "2026-09-29T07:47:38.8544242", durationSeconds = 39, pagesRead = 7 } } }, + { seriesId = 7452, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T07:51:52.786463", chapters = { + { chapterId = 11269, startTimeUtc = "2026-09-29T07:51:52.786463", durationSeconds = 365, pagesRead = 115 } } }, + { seriesId = 10042, localDate = "2026-09-29T00:00:00", startTimeUtc = "2026-09-29T07:39:42.880422", chapters = { + { chapterId = 14638, startTimeUtc = "2026-09-29T07:39:42.880422", durationSeconds = 50, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-28T00:00:00", startTimeUtc = "2026-09-28T09:16:47.6382365", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-28T09:16:47.6382365", durationSeconds = 59, pagesRead = 0 } } }, + { seriesId = 9158, localDate = "2026-09-28T00:00:00", startTimeUtc = "2026-09-27T17:16:38.7193514", chapters = { + { chapterId = 13395, startTimeUtc = "2026-09-27T17:16:38.7193514", durationSeconds = 29, pagesRead = 1 } } }, + { seriesId = 10683, localDate = "2026-09-28T00:00:00", startTimeUtc = "2026-09-27T17:13:53.8061535", chapters = { + { chapterId = 18893, startTimeUtc = "2026-09-27T17:13:53.8061535", durationSeconds = 16, pagesRead = -1 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T15:13:47.085122", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T15:13:47.085122", durationSeconds = 746, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T13:34:49.3907937", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T13:34:49.3907937", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T13:03:53.8173515", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T13:03:53.8173515", durationSeconds = 9, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T09:21:25.6490847", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T09:21:25.6490847", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T09:03:41.6524393", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T09:03:41.6524393", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-27T00:00:00", startTimeUtc = "2026-09-27T01:38:10.6211012", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-27T01:38:10.6211012", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7540, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T15:13:21.9970834", chapters = { + { chapterId = 13394, startTimeUtc = "2026-09-26T15:13:21.9970834", durationSeconds = 14, pagesRead = 4 } } }, + { seriesId = 8110, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:58:04.4305334", chapters = { + { chapterId = 12126, startTimeUtc = "2026-09-26T14:58:04.4305334", durationSeconds = 181, pagesRead = 1 } } }, + { seriesId = 8110, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:37:55.4114027", chapters = { + { chapterId = 12126, startTimeUtc = "2026-09-26T14:37:55.4114027", durationSeconds = 55, pagesRead = 1 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:33:39.6298963", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T14:33:39.6298963", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T14:19:48.5269015", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T14:19:48.5269015", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10676, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T13:34:15.9269344", chapters = { + { chapterId = 18818, startTimeUtc = "2026-09-26T13:34:15.9269344", durationSeconds = 1021, pagesRead = 54 } } }, + { seriesId = 10676, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T12:08:23.540117", chapters = { + { chapterId = 18818, startTimeUtc = "2026-09-26T12:08:23.540117", durationSeconds = 107, pagesRead = 11 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T12:07:39.7719041", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T12:07:39.7719041", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T01:55:50.078051", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T01:55:50.078051", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T01:32:58.4149147", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T01:32:58.4149147", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-26T00:00:00", startTimeUtc = "2026-09-26T01:13:02.4223873", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-26T01:13:02.4223873", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T14:23:56.0117314", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-25T14:23:56.0117314", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T13:59:56.4928672", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-25T13:59:56.4928672", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T07:58:26.2227579", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-25T07:58:26.2227579", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 8110, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T07:08:30.8014023", chapters = { + { chapterId = 12126, startTimeUtc = "2026-09-25T07:08:30.8014023", durationSeconds = 7, pagesRead = 3 } } }, + { seriesId = 7460, localDate = "2026-09-25T00:00:00", startTimeUtc = "2026-09-25T01:28:12.7465578", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-25T01:28:12.7465578", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10663, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T14:34:51.9798262", chapters = { + { chapterId = 18514, startTimeUtc = "2026-09-24T14:34:51.9798262", durationSeconds = 59, pagesRead = 10 } } }, + { seriesId = 10682, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T14:00:55.5695168", chapters = { + { chapterId = 18889, startTimeUtc = "2026-09-24T14:00:55.5695168", durationSeconds = 65, pagesRead = 8 } } }, + { seriesId = 10634, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T13:41:48.3170857", chapters = { + { chapterId = 17855, startTimeUtc = "2026-09-24T13:41:48.3170857", durationSeconds = 328, pagesRead = 65 } } }, + { seriesId = 10663, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T12:55:37.0956115", chapters = { + { chapterId = 18514, startTimeUtc = "2026-09-24T12:55:37.0956115", durationSeconds = 44, pagesRead = 8 } } }, + { seriesId = 10634, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T12:54:21.9067307", chapters = { + { chapterId = 17855, startTimeUtc = "2026-09-24T12:54:21.9067307", durationSeconds = 8, pagesRead = 4 } } }, + { seriesId = 10634, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T11:36:17.6978208", chapters = { + { chapterId = 17855, startTimeUtc = "2026-09-24T11:36:17.6978208", durationSeconds = 56, pagesRead = 14 } } }, + { seriesId = 10682, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T09:54:25.899822", chapters = { + { chapterId = 18889, startTimeUtc = "2026-09-24T09:54:25.899822", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 10674, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T09:27:10.4132213", chapters = { + { chapterId = 18789, startTimeUtc = "2026-09-24T09:27:10.4132213", durationSeconds = 8, pagesRead = 3 } } }, + { seriesId = 9249, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T07:47:32.97548", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-24T07:47:32.97548", durationSeconds = 461, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T07:26:01.1542479", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-24T07:26:01.1542479", durationSeconds = 146, pagesRead = 0 } } }, + { seriesId = 9095, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-24T06:46:54.4314754", chapters = { + { chapterId = 13282, startTimeUtc = "2026-09-24T06:46:54.4314754", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 9649, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-23T16:09:03.1098014", chapters = { + { chapterId = 14126, startTimeUtc = "2026-09-23T16:09:03.1098014", durationSeconds = 4, pagesRead = 2 } } }, + { seriesId = 7461, localDate = "2026-09-24T00:00:00", startTimeUtc = "2026-09-23T16:05:48.0362145", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-23T16:05:48.0362145", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-23T00:00:00", startTimeUtc = "2026-09-23T13:47:22.8458997", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-23T13:47:22.8458997", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 8137, localDate = "2026-09-23T00:00:00", startTimeUtc = "2026-09-23T05:52:39.9019755", chapters = { + { chapterId = 12159, startTimeUtc = "2026-09-23T05:52:39.9019755", durationSeconds = 79, pagesRead = 18 } } }, + { seriesId = 9249, localDate = "2026-09-23T00:00:00", startTimeUtc = "2026-09-23T03:51:46.3681335", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-23T03:51:46.3681335", durationSeconds = 327, pagesRead = 0 } } }, + { seriesId = 9262, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T13:38:38.3358566", chapters = { + { chapterId = 13508, startTimeUtc = "2026-09-22T13:38:38.3358566", durationSeconds = 52, pagesRead = 4 } } }, + { seriesId = 9249, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T13:22:52.4340931", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-22T13:22:52.4340931", durationSeconds = 5, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T10:28:46.3070635", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T10:28:46.3070635", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T09:53:02.9688203", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T09:53:02.9688203", durationSeconds = 515, pagesRead = 1 } } }, + { seriesId = 9257, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T09:45:09.829169", chapters = { + { chapterId = 13503, startTimeUtc = "2026-09-22T09:45:09.829169", durationSeconds = 5, pagesRead = 11 } } }, + { seriesId = 9249, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:59:44.2021935", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-22T08:59:44.2021935", durationSeconds = 85, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:57:31.3039746", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T08:57:31.3039746", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:34:21.7362395", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T08:34:21.7362395", durationSeconds = 697, pagesRead = 0 } } }, + { seriesId = 9249, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T08:00:48.3941463", chapters = { + { chapterId = 13493, startTimeUtc = "2026-09-22T08:00:48.3941463", durationSeconds = 149, pagesRead = 2 } } }, + { seriesId = 9180, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T03:13:37.560087", chapters = { + { chapterId = 13420, startTimeUtc = "2026-09-22T03:13:37.560087", durationSeconds = 11, pagesRead = 7 } } }, + { seriesId = 7460, localDate = "2026-09-22T00:00:00", startTimeUtc = "2026-09-22T02:24:02.4880326", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-22T02:24:02.4880326", durationSeconds = 163, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T13:24:04.9528675", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-21T13:24:04.9528675", durationSeconds = 307, pagesRead = 1 } } }, + { seriesId = 7805, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T13:07:31.7048466", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-21T13:07:31.7048466", durationSeconds = 8, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T13:04:31.936106", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-21T13:04:31.936106", durationSeconds = 84, pagesRead = 0 } } }, + { seriesId = 8661, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T10:07:50.9423535", chapters = { + { chapterId = 12763, startTimeUtc = "2026-09-21T10:07:50.9423535", durationSeconds = 563, pagesRead = 5 } } }, + { seriesId = 7805, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T09:56:54.7828239", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-21T09:56:54.7828239", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 9110, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T04:49:43.5918775", chapters = { + { chapterId = 13318, startTimeUtc = "2026-09-21T04:49:43.5918775", durationSeconds = 207, pagesRead = 4 } } }, + { seriesId = 7603, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T04:49:04.8491169", chapters = { + { chapterId = 11484, startTimeUtc = "2026-09-21T04:49:04.8491169", durationSeconds = 6, pagesRead = 4 } } }, + { seriesId = 7603, localDate = "2026-09-21T00:00:00", startTimeUtc = "2026-09-21T03:38:08.3558687", chapters = { + { chapterId = 11484, startTimeUtc = "2026-09-21T03:38:08.3558687", durationSeconds = 8, pagesRead = 4 } } }, + { seriesId = 8247, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T14:14:20.693305", chapters = { + { chapterId = 12300, startTimeUtc = "2026-09-20T14:14:20.693305", durationSeconds = 86, pagesRead = 6 } } }, + { seriesId = 8281, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T14:11:24.8897015", chapters = { + { chapterId = 12334, startTimeUtc = "2026-09-20T14:11:24.8897015", durationSeconds = 25, pagesRead = 1 } } }, + { seriesId = 7476, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T13:17:19.1246015", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-20T13:17:19.1246015", durationSeconds = 34, pagesRead = 7 } } }, + { seriesId = 7805, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T13:07:24.1160188", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-20T13:07:24.1160188", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 8310, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T09:52:07.5117003", chapters = { + { chapterId = 12363, startTimeUtc = "2026-09-20T09:52:07.5117003", durationSeconds = 671, pagesRead = 3 } } }, + { seriesId = 8310, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T09:32:51.5623005", chapters = { + { chapterId = 12363, startTimeUtc = "2026-09-20T09:32:51.5623005", durationSeconds = 364, pagesRead = 1 } } }, + { seriesId = 8106, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T08:11:17.3798059", chapters = { + { chapterId = 12122, startTimeUtc = "2026-09-20T08:11:17.3798059", durationSeconds = 35, pagesRead = 5 } } }, + { seriesId = 7510, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:50:30.9737641", chapters = { + { chapterId = 11360, startTimeUtc = "2026-09-20T07:50:30.9737641", durationSeconds = 19, pagesRead = 0 } } }, + { seriesId = 7805, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:47:25.7922257", chapters = { + { chapterId = 11791, startTimeUtc = "2026-09-20T07:47:25.7922257", durationSeconds = 3, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:25:56.7820012", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T07:25:56.7820012", durationSeconds = 427, pagesRead = 2 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T07:01:03.0337544", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T07:01:03.0337544", durationSeconds = 311, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T04:37:11.2011378", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T04:37:11.2011378", durationSeconds = 407, pagesRead = 0 } } }, + { seriesId = 7460, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T04:29:53.9882097", chapters = { + { chapterId = 11285, startTimeUtc = "2026-09-20T04:29:53.9882097", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-20T00:00:00", startTimeUtc = "2026-09-20T03:23:39.822214", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-20T03:23:39.822214", durationSeconds = 431, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T14:37:14.3112506", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T14:37:14.3112506", durationSeconds = 460, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T14:16:12.9574126", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T14:16:12.9574126", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T13:33:23.8175739", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T13:33:23.8175739", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T13:01:57.6991072", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T13:01:57.6991072", durationSeconds = 102, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T10:51:52.8573558", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T10:51:52.8573558", durationSeconds = 445, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T09:58:37.3332857", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T09:58:37.3332857", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T06:19:27.9750172", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T06:19:27.9750172", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T05:44:36.041471", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T05:44:36.041471", durationSeconds = 500, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T05:08:30.2036102", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T05:08:30.2036102", durationSeconds = 263, pagesRead = 4 } } }, + { seriesId = 7560, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T04:47:13.2207635", chapters = { + { chapterId = 11430, startTimeUtc = "2026-09-19T04:47:13.2207635", durationSeconds = 1, pagesRead = 1 } } }, + { seriesId = 7556, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T04:07:25.0646351", chapters = { + { chapterId = 11426, startTimeUtc = "2026-09-19T04:07:25.0646351", durationSeconds = 0, pagesRead = 1 } } }, + { seriesId = 7561, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T03:29:58.6171005", chapters = { + { chapterId = 11438, startTimeUtc = "2026-09-19T03:29:58.6171005", durationSeconds = 5, pagesRead = 4 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T02:37:58.1533148", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T02:37:58.1533148", durationSeconds = 524, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-19T00:00:00", startTimeUtc = "2026-09-19T02:00:00.8956888", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-19T02:00:00.8956888", durationSeconds = 524, pagesRead = 1 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T13:54:08.9566107", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T13:54:08.9566107", durationSeconds = 174, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T12:53:09.8665339", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T12:53:09.8665339", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T09:50:06.0469366", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T09:50:06.0469366", durationSeconds = 0, pagesRead = 0 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T09:25:33.4181389", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T09:25:33.4181389", durationSeconds = 738, pagesRead = 1 } } }, + { seriesId = 7490, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T07:52:05.2045118", chapters = { + { chapterId = 11335, startTimeUtc = "2026-09-18T07:52:05.2045118", durationSeconds = 6, pagesRead = 2 } } }, + { seriesId = 7476, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T06:59:54.0156885", chapters = { + { chapterId = 11317, startTimeUtc = "2026-09-18T06:59:54.0156885", durationSeconds = 2, pagesRead = 2 } } }, + { seriesId = 7461, localDate = "2026-09-18T00:00:00", startTimeUtc = "2026-09-18T06:47:37.6019707", chapters = { + { chapterId = 11312, startTimeUtc = "2026-09-18T06:47:37.6019707", durationSeconds = 0, pagesRead = 0 } } }, +} diff --git a/tests/kavita/kamare_update_spec.lua b/tests/kavita/kamare_update_spec.lua new file mode 100644 index 0000000..8ca2c28 --- /dev/null +++ b/tests/kavita/kamare_update_spec.lua @@ -0,0 +1,202 @@ +--[[-- +moonsource_kavita.kamare_update:kamare 目标描述(只问 api.github.com、探测已装版本、装到 kamare 目录)。流程本身由 features.update 的 spec 覆盖。 + +@module tests.moonsource_kavita.kamare_update_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") + +local shown, closed, ticks = {}, {}, {} +local restarted = 0 +package.preload["ui/uimanager"] = function() + return { + nextTick = function(_, fn) ticks[#ticks + 1] = fn end, + } +end +local function flush() + while #ticks > 0 do table.remove(ticks, 1)() end +end +local connected = true +package.preload["ui/network/manager"] = function() + return { isConnected = function() return connected end } +end +package.preload["json"] = function() + return { decode = function(value) return value end } +end +package.preload["utils.log"] = function() + return { warn = function() end, dbg = function() end, info = function() end } +end +package.preload["utils.paths"] = function() + return { + ensureDir = function() return true end, + root = function() return "/tmp" end, + } +end + +-- 探测结果与安装根目录由用例控制。 +local probe_result = { ok = false, state = "missing" } +local plugins_dir = "/fake/plugins" +package.preload["moonsource_kavita.cache"] = function() + return { + probe = function() return probe_result end, + pluginsDir = function() return plugins_dir end, + } +end + +local function dialogModule() + return { + new = function(_, opts) + function opts:show() shown[#shown + 1] = self end + function opts:close() closed[#closed + 1] = self end + return opts + end, + } +end +package.preload["ui.themes.widgets.text_viewer"] = dialogModule +package.preload["ui.themes.widgets.toast"] = dialogModule +package.preload["ui.themes.widgets.progress_dialog"] = function() + return { + new = function(_, opts) + function opts:show() shown[#shown + 1] = self end + function opts:close() closed[#closed + 1] = self end + function opts:bytes(done, total) + self.progress, self.progress_max = done, total + end + function opts:set(text, percent) + self.status, self.percent = text, percent + end + return opts + end, + } +end + +local check_cbs, gets = {}, 0 +local download_cb, download_opts +package.preload["http.request"] = function() + return { + get = function(url, _, cb) + gets = gets + 1 + check_cbs[#check_cbs + 1] = { url = url, cb = cb } + return { cancel = function() end } + end, + download = function(opts, _, cb) + download_opts, download_cb = opts, cb + return { cancel = function() end } + end, + } +end +local pick_calls = 0 +package.preload["http.github"] = function() + return { + pickRelease = function(release, cb) + pick_calls = pick_calls + 1 + cb(release.url) + return { cancel = function() end } + end, + } +end + +local job_opts, job_worker +package.preload["workers.job"] = function() + return { + run = function(worker, opts) + job_worker, job_opts = worker, opts + return { cancel = function() end } + end, + } +end +local install_args +package.preload["utils.plugin_install"] = function() + return { + run = function(archive, parent, sha, opts) + install_args = { archive = archive, parent = parent, sha = sha, opts = opts } + return true, "kamare.koplugin" + end, + } +end +package.preload["utils.restart"] = function() + return { now = function() restarted = restarted + 1 end } +end + +local Kamare = require("moonsource_kavita.kamare_update") + +local hash = string.rep("a", 64) +local direct = "https://github.com/backtracker/kamare.koplugin/releases/download/v0.10.4/kamare.koplugin.zip" +local function release(tag, digest) + local asset = { + name = "kamare.koplugin.zip", + browser_download_url = "https://github.com/backtracker/kamare.koplugin/releases/download/" + .. tag .. "/kamare.koplugin.zip", + size = 2048, + } + if digest ~= false then asset.digest = "sha256:" .. hash end + return { tag_name = tag, body = "## 新增\n\n- **蓝牙翻页器**\n", assets = { asset } } +end + +---@return table|nil, any +local function check(response) + local got, got_err + check_cbs = {} + Kamare:check(function(r, e) got, got_err = r, e end) + for _idx, entry in ipairs(check_cbs) do entry.cb(response) end + flush() + return got, got_err +end + +-- 版本和 digest 先问 api.ankio.net 的转发。 +check_cbs = {} +Kamare:check(function() end) +Assert.eq(#check_cbs, 1) +Assert.eq(check_cbs[1].url, "https://api.ankio.net/gh/repos/backtracker/kamare.koplugin/releases/latest") +check_cbs[1].cb(release("v0.10.4")) +flush() + +-- 已装版本来自探测;没装 / 官方版同版本也要提示安装。 +probe_result = { ok = true, state = "enhanced", version = "0.10.4-dev" } +local parsed = check(release("v0.10.4")) +Assert.eq(parsed.installed, "0.10.4-dev") +Assert.eq(parsed.sha256, hash) +Assert.is_true(parsed.available, "开发版低于同号正式版") +probe_result = { ok = true, state = "enhanced", version = "0.10.4" } +Assert.is_false(check(release("v0.10.4")).available) +probe_result = { ok = false, state = "official", version = "0.10.4" } +Assert.is_true(check(release("v0.10.4")).available) +Assert.is_nil(check(release("v0.10.4", false)).sha256, "kamare 的 digest 可选") + +-- 已是最新:toast 带 kamare 前缀;没装:安装提示。 +local function startCheck(response) + shown, closed = {}, {} + check_cbs = {} + Kamare:manualCheck(nil) + for _idx, entry in ipairs(check_cbs) do entry.cb(response) end + flush() +end +probe_result = { ok = true, state = "enhanced", version = "0.10.4" } +startCheck(release("v0.10.4")) +Assert.matches(shown[#shown].text, "已是最新版本(kamare 0%.10%.4)") +probe_result = { ok = false, state = "missing" } +startCheck(release("v0.10.4")) +local prompt = shown[#shown] +Assert.eq(prompt.title, "更新 kamare") +Assert.matches(prompt.text, "当前未安装可用的 kamare 增强版") + +-- 装到 kamare 当前所在目录,带目录名;没有 digest 只直连。 +plugins_dir = "/mnt/us/koreader/plugins" +prompt.buttons[2].callback() +Assert.eq(download_opts.url, direct) +download_cb(true) +job_worker() +Assert.eq(install_args.sha, hash) +Assert.eq(install_args.opts.name, "kamare.koplugin") +Assert.eq(install_args.parent, plugins_dir) +job_opts.on_done() +flush() +Assert.eq(restarted, 1) + +local nosha = check(release("v0.10.4", false)) +pick_calls = 0 +Kamare:install(nosha, nil, function() end) +Assert.eq(pick_calls, 0, "没有 digest 不走镜像") + +return true diff --git a/tests/kavita/migration_spec.lua b/tests/kavita/migration_spec.lua new file mode 100644 index 0000000..ce787d9 --- /dev/null +++ b/tests/kavita/migration_spec.lua @@ -0,0 +1,108 @@ +--[[-- +Kavita 一次性迁移:卷行继承容器元数据并退出书架。 + +@module tests.moonsource_kavita.migration_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") + +local db_path = Config.dir() .. "/kavita_migration_spec.sqlite3" +local state_path = Config.dir() .. "/settings/moonsource_kavita_meta.lua" +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +for _idx, suffix in ipairs({ "", ".old" }) do os.remove(state_path .. suffix) end + +package.loaded["utils.paths"] = nil +package.preload["utils.paths"] = function() + return { dbPath = function() return db_path end, ensureSettings = function() end, + sanitizeSourceId = function(id) return id end } +end + +local DB = require("utils.db") +require("book.books_db") +Assert.not_nil(DB.open()) + +local function insert(source_id, stable_id, authors, intro, deleted, sync_status, path) + Assert.is_true(DB.exec([[ + INSERT INTO books (source_id, stable_id, title, authors, intro, deleted, sync_status, path) + VALUES (?, ?, ?, ?, ?, ?, ?, ?); + ]], source_id, stable_id, "书 " .. stable_id, authors, intro, deleted, sync_status, path)) +end + +insert("kavita", "10", "容器作者", "容器简介", 0, 1, nil) +insert("kavita", "10:100", nil, "", 0, 0, "/books/volume.epub") +insert("kavita", "10:101", "卷作者", "卷简介", 0, 0, nil) +insert("kavita", "10:102", nil, nil, 1, 0, nil) +insert("other", "10:100", nil, "", 0, 0, nil) + +local cfg = { base_url = "http://kavita/", api_key = "key" } +package.loaded["utils.settings"] = { + getSource = function() return cfg end, + saveSource = function() end, +} +package.loaded["source.base"] = { + loadMeta = function(id) return { id = id, name = "Kavita", type = "book" } end, + capabilities = function() return {} end, + defer = function(_self, cb, ...) + local args = { ... } + cb(unpack(args)) + return { cancel = function() end } + end, +} +package.loaded["moonsource_kavita.client"] = { new = function(options) return options end } +package.loaded["moonsource_kavita.annotation"] = {} +package.loaded["moonsource_kavita.position"] = {} +package.loaded["moonsource_kavita.stats"] = {} +package.loaded["moonsource_kavita.cache"] = { resetShelf = function() end } +package.loaded["moonsource_kavita.volume_list"] = {} +package.loaded["book.note.normalize"] = {} + +local Source = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/source.lua") +Source.new() + +local function row(source_id, stable_id) + local authors, intro, deleted, sync_status, path = DB.rowexec([[ + SELECT authors, intro, deleted, sync_status, path FROM books + WHERE source_id=? AND stable_id=?; + ]], source_id, stable_id) + return authors, intro, tonumber(deleted), tonumber(sync_status), path +end + +local authors, intro, deleted, sync_status, path = row("kavita", "10:100") +Assert.eq(authors, "容器作者") +Assert.eq(intro, "容器简介") +Assert.eq(deleted, 1, "卷行从书架隐藏") +Assert.eq(sync_status, 1, "迁移后的远端卷行标为已同步") +Assert.eq(path, "/books/volume.epub", "保留已下载文件路径") + +authors, intro, deleted, sync_status = row("kavita", "10:101") +Assert.eq(authors, "卷作者", "保留已有作者") +Assert.eq(intro, "卷简介", "保留已有简介") +Assert.eq(deleted, 1, "所有旧卷行都从书架隐藏") +Assert.eq(sync_status, 1) + +authors, intro, deleted, sync_status = row("kavita", "10:102") +Assert.eq(authors, "容器作者", "已隐藏卷行也补齐元数据") +Assert.eq(intro, "容器简介") +Assert.eq(deleted, 1) +Assert.eq(sync_status, 0, "不改原本已隐藏行的脏状态") + +authors, intro, deleted = row("other", "10:100") +Assert.is_nil(authors, "迁移只影响 Kavita") +Assert.eq(intro, "") +Assert.eq(deleted, 0) + +local state = require("luasettings"):open( + require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") +Assert.eq(tonumber(state:readSetting("schema_version")), 1) + +insert("kavita", "10:103", nil, nil, 0, 0, nil) +Source.new() +local _, _, still_visible = row("kavita", "10:103") +Assert.eq(still_visible, 0, "schema_version 阻止重复迁移") + +DB.close() +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +for _idx, suffix in ipairs({ "", ".old" }) do os.remove(state_path .. suffix) end + +return true diff --git a/tests/kavita/on_deck_spec.lua b/tests/kavita/on_deck_spec.lua new file mode 100644 index 0000000..626f7ac --- /dev/null +++ b/tests/kavita/on_deck_spec.lua @@ -0,0 +1,171 @@ +--[[-- +extensions/moonsource-kavita.koplugin 首页组件 On Deck:在线且已配置才拉,5 分钟内复用; +两行 × 5 列封面网格(网格尺寸走 CoverCell.denseCoverMetrics / Book.widget,同首页最近阅读), +点开走月读开书;失败 / 空列表 / 离线给提示。 + +@module tests.moonsource_kavita.on_deck_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") +local Themed = require("support.theme_stubs") +Themed.install() +local Widget = require("ui/widget/widget") + +local TITLE_EXTRA = 26 +local covers = {} +package.preload["ui.widgets.book"] = function() + return { + captionExtra = function(show_title) return show_title ~= false and TITLE_EXTRA or 0 end, + widget = function(_plugin, _source, book, cw, ch, opts) + local slot_w = (opts and opts.slot_w) or cw + covers[#covers + 1] = { book = book, w = cw, h = ch, slot_w = slot_w, home = opts and opts.home } + return Widget:new{ dimen = { w = slot_w, h = ch + TITLE_EXTRA } } + end, + } +end +package.preload["ui.widgets.cover"] = function() + return { + gridCoverMaxH = function() return 320 end, + denseCoverMetrics = function(w, _budget, opts) + local cols = opts.min_cols or 5 + local gap, row_gap = 8, 10 + local slot_w = math.max(1, math.floor((w - gap * (cols - 1)) / cols)) + local cw = slot_w + local ch = math.min(math.floor(cw * 3 / 2), opts.max_h or 320) + return slot_w, cw, ch, cols, gap, row_gap, ch + opts.title_extra + end, + } +end +local opened = {} +package.preload["desktop.open"] = function() + return { book = function(_plugin, book) opened[#opened + 1] = book end } +end + +local online, configured = true, true +package.loaded["ui/network/manager"] = { isConnected = function() return online end } +local calls, reply = {}, nil +local source = { + configured = function() return configured end, + client = { + json = function(_self, method, path, query, body, cb) + calls[#calls + 1] = { method = method, path = path, query = query, body = body } + reply = cb + return { cancel = function() reply = nil end } + end, + }, +} +package.loaded["source.registry"] = { resolve = function(id) return id == "kavita" and source or nil end } + +local Deck = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/on_deck.lua") +Assert.eq(Deck.id, "kavita.on_deck") + +local desktop = { plugin = {} } +local deck = Deck:new{} +deck:build({ desktop = desktop, plugin = desktop.plugin }, + { width = 300, height = deck:heightRange(nil, { width = 300 }).height }) +Assert.contains(Kit.texts(deck.slot), "联网后显示 Kavita 上在读的书") + +-- 激活拉一次:POST on-deck,进度按 pagesRead / pages。 +deck:activate() +Assert.len(calls, 1) +Assert.eq(calls[1].method, "POST") +Assert.eq(calls[1].path, "/api/Series/on-deck") +Assert.eq(calls[1].query.pageSize, 10) +local list = {} +for i = 1, 12 do list[i] = { id = i, name = "S" .. i, pages = 10, pagesRead = i } end +reply(list) +Assert.eq(deck.data[3].stable_id, "3") +Assert.eq(deck.data[3].source_id, "kavita") +Assert.eq(deck.data[3].percent, 30) +-- 一页 4 本(跟首页最近阅读一样),12 本分 3 页。 +Assert.eq(#covers, 4, "一页 4 本") +Assert.is_true(covers[1].home, "On Deck 走首页封面策略") +Assert.eq(covers[1].book.title, "S1") +Assert.contains(Kit.texts(deck.slot), "1 / 3") + +-- 一页 4 本、多的分页:翻到后面不该重画前面的书。 +covers = {} +deck.page = 2 +deck:refresh() +Assert.eq(#covers, 4) +Assert.eq(covers[1].book.title, "S5", "第二页从第 5 本开始") +Assert.contains(Kit.texts(deck.slot), "2 / 3") +deck.page = 3 +covers = {} +deck:refresh() +Assert.eq(#covers, 4, "最后一页 4 本") +Assert.eq(covers[1].book.title, "S9") +deck.page = 1 +covers = {} +deck:refresh() + +-- 5 分钟内重新激活不再请求;过期再拉。 +deck:deactivate() +deck:activate() +Assert.len(calls, 1) +deck.loaded_at = os.time() - 301 +deck:deactivate() +deck:activate() +Assert.len(calls, 2) + +-- 离开首页取消在飞请求;失败显示原因;空列表给提示。 +deck:deactivate() +Assert.is_nil(reply) +deck.loaded_at = nil +deck:activate() +reply(nil, "API Key 无效") +Assert.eq(covers[1].book.title, "S1", "失败保留上次的列表") +deck.data, deck.loaded_at = nil, nil +deck:deactivate() +deck:activate() +reply(nil, "API Key 无效") +Assert.contains(Kit.texts(deck.slot), "API Key 无效") +deck.loaded_at = nil +deck:deactivate() +deck:activate() +reply({}) +Assert.contains(Kit.texts(deck.slot), "Kavita 上没有在读的书") + +-- 离线 / 未配置不请求。 +local before = #calls +deck.loaded_at = nil +deck:deactivate() +online = false +deck:activate() +deck:deactivate() +online, configured = true, false +deck:activate() +Assert.len(calls, before) + +-- 点封面走月读开书。 +deck.data = { { source_id = "kavita", stable_id = "9", title = "九" } } +deck:refresh() +local taps = Kit.taps(deck.slot) +Assert.len(taps, 1) +taps[1]:onTapThemeArea() +Assert.eq(opened[1].stable_id, "9") + +-- 一页 4 本,封面按宽度分满,槽宽/封面宽一致,10 本分 3 页。 +covers = {} +online, configured = true, true +local wide = Deck:new{} +local nat = wide:heightRange(nil, { width = 568 }).height +wide:build({ desktop = desktop, plugin = desktop.plugin }, { width = 568, height = nat }) +wide:activate() +local ten = {} +for i = 1, 10 do ten[i] = { id = i, name = "S" .. i, pages = 10, pagesRead = i } end +reply(ten) +Assert.len(wide.data, 10) +Assert.eq(#covers, 4, "每页 4 本") +Assert.contains(Kit.texts(wide.slot), "1 / 3") +-- 内容高不能超过 heightRange(超了 widget 会掉出槽位)。 +Assert.is_true(wide.slot[1]:getSize().h <= nat, "内容高不超过 heightRange") +-- 每格用同一个槽宽(Book.widget 把封面居中到 slot_w),不会有一本看着变小 / 错位。 +for _i, c in ipairs(covers) do + Assert.eq(c.slot_w, covers[1].slot_w, "每格槽宽一致") + Assert.eq(c.w, covers[1].w, "每格封面宽一致") +end diff --git a/tests/kavita/position_spec.lua b/tests/kavita/position_spec.lua new file mode 100644 index 0000000..6e781c2 --- /dev/null +++ b/tests/kavita/position_spec.lua @@ -0,0 +1,90 @@ +--[[-- +extensions/moonsource-kavita.koplugin:xpointer ↔ Kavita pageNum / bookScrollId 换算。 + +@module tests.moonsource_kavita.position_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") + +local Position = dofile((debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") .. "/position.lua") + +-- spine:DocFragment[D] = spine D-1;单 spine 书没有下标。 +Assert.eq(Position.spine("/body/DocFragment[8]/body/p[2]/text().0"), 7) +Assert.eq(Position.spine("/body[1]/DocFragment[1]/body[1]/p"), 0) +Assert.eq(Position.spine("/body/DocFragment/body/p"), 0) +Assert.is_nil(Position.spine(nil)) +Assert.is_nil(Position.spine("#_doc_fragment_3")) + +-- 上报:补全 [1]、丢文本偏移;两种 crengine 写法都认。 +Assert.eq(Position.toScrollId("/body/DocFragment[8]/body/section/p[3]/text().0"), "//body/section[1]/p[3]") +Assert.eq(Position.toScrollId("/body[1]/DocFragment[8]/body[1]/div[2]/p/text()[1].5"), "//body/div[2]/p[1]") +Assert.eq(Position.toScrollId("/body/DocFragment/body/p[4]"), "//body/p[4]") +Assert.is_nil(Position.toScrollId("/body/DocFragment[2]/body"), "body 本身没有章内位置") +Assert.is_nil(Position.toScrollId(nil)) + +-- 下行:[1] 省略;读完(pageNum == pages)落回最后一个 spine;单 spine 书不带下标。 +Assert.eq(Position.toXPointer(7, "//body/section[1]/p[3]", 10), "/body/DocFragment[8]/body/section/p[3]") +Assert.eq(Position.toXPointer(10, nil, 10), "/body/DocFragment[10]/body") +Assert.eq(Position.toXPointer(0, "//body/p[2]", 1), "/body/DocFragment/body/p[2]") +Assert.eq(Position.toXPointer(3, "id(\"x\")", 10), "/body/DocFragment[4]/body", "未解析的锚点只按 spine 定位") + +-- 往返:上报出去的锚点拉回来落在同一段。 +local here = "/body/DocFragment[5]/body/div[2]/p[7]/text().12" +Assert.eq(Position.toXPointer(Position.spine(here), Position.toScrollId(here), 9), "/body/DocFragment[5]/body/div[2]/p[7]") + +-- 网页端的 id("X"):读本地 epub 第 spine 个文档找元素路径。 +local files = { + ["META-INF/container.xml"] = [[]], + ["OEBPS/content.opf"] = [[ + + + ]], + ["OEBPS/text/two.xhtml"] = [[ +

a


b

c

]], +} +local opened, closed = nil, false +package.loaded["ffi/archiver"] = { + Reader = { + new = function() + return { + open = function(_self, path) opened = path; return path == "/book.epub" end, + iterate = function() return function() end end, + extractToMemory = function(_self, name) return files[name] end, + close = function() closed = true end, + } + end, + }, +} +Assert.eq(Position.resolveScrollId("/book.epub", 1, 'id("target")'), "//body/section[1]/div[1]/p[1]") +Assert.eq(opened, "/book.epub") +Assert.is_true(closed) +Assert.eq(Position.resolveScrollId(nil, 1, "//body/p[2]"), "//body/p[2]", "自己上报的路径原样用") +Assert.is_nil(Position.resolveScrollId("/book.epub", 1, 'id("missing")')) +Assert.is_nil(Position.resolveScrollId("/book.epub", 5, 'id("target")'), "spine 越界") +Assert.is_nil(Position.resolveScrollId(nil, 1, 'id("target")'), "没下载过的书没法解析") +Assert.is_nil(Position.resolveScrollId("/other.epub", 1, 'id("target")'), "打不开的文件") +-- 划线锚点:按段落文本找路径,忽略空白、实体、脚注标记;跨段用首末行各定一段。 +files["OEBPS/text/one.xhtml"] = [[

前言

+

甲乙丙&丁 戊己¹[3]庚辛壬癸

子丑寅卯辰巳

]] +local anchor = Position.anchor("丙&丁\n戊己", "/body/DocFragment[1]/body/p[2]/text().2", "/book.epub") +Assert.eq(anchor.pageNumber, 0) +Assert.eq(anchor.xPath, "//body/p[2]") +Assert.eq(anchor.endingXPath, "//body/p[2]") +anchor = Position.anchor("戊己庚辛壬癸\n子丑寅", "/body/DocFragment[1]/body/p[2]/text().6", "/book.epub") +Assert.eq(anchor.xPath, "//body/p[2]") +Assert.eq(anchor.endingXPath, "//body/div[1]/p[1]", "跨段") +anchor = Position.anchor("c", "/body/DocFragment[1]/body/p", "/book.epub") +Assert.is_nil(anchor, "单字太短,不猜") +anchor = Position.anchor("b", "/body/DocFragment[1]/body/p", "/book.epub") +Assert.is_nil(anchor) +files["OEBPS/text/two.xhtml"] = files["OEBPS/text/two.xhtml"]:gsub("

b", "

挪到第二章") +anchor = Position.anchor("挪到第二章", "/body/DocFragment[1]/body/p[2]", "/book.epub") +Assert.eq(anchor.pageNumber, 1, "pos0 所在 spine 没有就去邻近 spine 找") +Assert.eq(anchor.xPath, "//body/section[1]/p[2]") +Assert.is_nil(Position.anchor("不存在的文字", "/body/DocFragment[1]/body/p", "/book.epub")) +Assert.is_nil(Position.anchor("甲乙丙", "/body/DocFragment[1]/body/p", nil), "没下载过") + +files["META-INF/container.xml"] = nil +Assert.is_nil(Position.resolveScrollId("/book.epub", 1, 'id("target")'), "坏 epub 降级成只按 spine") diff --git a/tests/kavita/reconcile_spec.lua b/tests/kavita/reconcile_spec.lua new file mode 100644 index 0000000..14d38ca --- /dev/null +++ b/tests/kavita/reconcile_spec.lua @@ -0,0 +1,385 @@ +--[[-- +Kavita 统计对账:真实响应 fixture 走「拉取钩子 → replaceSynced 入库 → 展示查询」全链, +逐项对 spec 的验收基线。HTTP 与目录缓存打桩,其余全真:源(分页 / 身份判定 / 物化)、 +统计纯核心、真实 sqlite 的 reading_stats 与 books 库。 + +对账基线(research-kavita-stats-pull.md): + §2 全量逐日(29 天 / Σ=60,238s)、§3 样本 7453 逐日(13,921 + 316)、§4 系列累计。 +数字都来自实测响应(fixture 数值逐条未改),不是照实现倒推的。 + +@module tests.moonsource_kavita.reconcile_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") +local Json = require("support.json_stub") +local Stubs = require("support.stubs") + +-- 日 / 时归属按进程时区(POSIX TZ)计算:钉死 CST-8,与 fixture 拉取时用的 Asia/Shanghai 对齐, +-- 断言就不会随宿主机时区漂移。 +local ffi = require("ffi") +ffi.cdef[[ int setenv(const char*, const char*, int); void tzset(void); ]] +ffi.C.setenv("TZ", "CST-8", 1) +ffi.C.tzset() + +local sqlite_ok = pcall(require, "lua-ljsqlite3/init") +if not sqlite_ok then + Assert.skip("当前离线环境没有 ljsqlite3 Lua 模块") +end + +-- 沙箱库:books 与 reading_stats 同库,物化行和统计行一起对账。 +local db_path = Config.dir() .. "/kavita_reconcile_spec.sqlite3" +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +package.loaded["utils.paths"] = nil +package.preload["utils.paths"] = function() + return { + dbPath = function() return db_path end, + ensureSettings = function() end, + sanitizeSourceId = function(id) return id end, + } +end + +-- 响应体 / 分页头走真实编解码(source_spec 的往返桩同形);books 的 meta 列也用它。 +package.loaded["json"] = nil +package.preload["json"] = function() + return { encode = Json.encode, decode = Json.decode } +end + +-- 设备时钟(POSIX → IANA 映射)与扩展配置;stats_db 也会问 merge_local_stats(本用例默认关)。 +local clock = { timezone = "CST-8" } +local cfg = { base_url = "http://kav/", api_key = " k ", libraries = { ["8"] = true, ["10"] = true } } +package.loaded["utils.settings"] = nil +package.preload["utils.settings"] = function() + local common = { active_source = "local" } + return { + get = function(key) return key == "features.clock" and clock or common end, + getSource = function() return cfg end, + } +end + +-- 插件模块走 preload:不把插件根塞进 package.path(main.lua 会顶掉月读的 main)。 +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +for _idx, name in ipairs({ "client", "position", "annotation", "cache", "volume_list", "source", "stats" }) do + package.preload["moonsource_kavita" .. (name == "source" and ".source" or "." .. name)] = function() + return dofile(PLUGIN .. "/" .. (name == "source" and "source" or name) .. ".lua") + end +end + +-- HTTP:只服务阅读历史;目录全部命中缓存,物化与身份判定不发请求。 +-- 分页头与 body 同一套编解码(同真服务端:PageSize=200、总页数在响应头里)。 +local pagination_calls = {} +local sample = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_all.lua") +local history = sample +local function history_pages() + local pages = { {}, {} } + for _idx, entry in ipairs(history) do + local page = #pages[1] < 200 and 1 or 2 + pages[page][#pages[page] + 1] = entry + end + return pages +end +local function query(opts, key) return opts.url:match("[?&]" .. key .. "=([^&]*)") end +package.loaded["http.request"] = { + ok = function(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 + end, + header = function(res, name) + for key, value in pairs(res and res.headers or {}) do + if type(key) == "string" and key:lower() == name:lower() then return value end + end + end, + request = function(opts, cb) + local page = tonumber(query(opts, "PageNumber")) or 1 + pagination_calls[#pagination_calls + 1] = opts.url + -- 只认阅读历史:目录 / 其它接口意外被请求时返回 404(身份判定该走目录缓存, + -- 真机也是:判定结果记在状态文件里,不该为身份反复请求目录)。 + local history_call = opts.url:find("/api/Stats/reading%-history", 1) ~= nil + require("ui/uimanager"):nextTick(function() + if not history_call then + cb({ code = 404, body = "" }) + return + end + cb({ + code = 200, + body = Json.encode(history_pages()[page]), + headers = { Pagination = Json.encode({ + currentPage = page, + itemsPerPage = 200, + totalItems = #history, + totalPages = math.max(1, math.ceil(#history / 200)), + }) }, + }) + end) + return { cancel = function() end } + end, +} + +-- 目录缓存(source.toc)替身:身份判定只关心「1 章还是多章」,物化只用条目 title。 +-- 7453 用实测目录(4 卷含卷名,research §5 / series-detail);已知实测章数的系列对齐 §5; +-- 其余按云端读到的章构造 —— 判定结果只影响单书身份粒度,不影响账户日桶。 +local CLOUD_TITLES = { + ["7453"] = { + { chapterId = 11271, title = "2001:太空漫游" }, + { chapterId = 11273, title = "2010:太空漫游" }, + { chapterId = 11270, title = "2061:太空漫游" }, + { chapterId = 11272, title = "3001:太空漫游" }, + }, +} +local TOC_COUNTS = { ["7453"] = 4, ["10634"] = 27, ["7460"] = 2, ["10720"] = 5, ["8661"] = 1, ["7606"] = 1 } +local tocs = {} +for _idx, entry in ipairs(sample) do + local series_id = tostring(entry.seriesId) + local toc = tocs[series_id] + if not toc then toc = {}; tocs[series_id] = toc end + -- 全量取并:同一系列各条会话可能各读不同章,真目录里这些章都在。 + for _i, chapter in ipairs(entry.chapters) do + if chapter.chapterId then + local known = false + for _k, item in ipairs(toc) do + if item.chapterId == chapter.chapterId then known = true end + end + if not known then toc[#toc + 1] = { chapterId = chapter.chapterId } end + end + end +end +for series_id, entries in pairs(CLOUD_TITLES) do tocs[series_id] = entries end +for series_id, count in pairs(TOC_COUNTS) do + -- 补齐到实测章数:补齐条目不带 chapterId,只有 #toc 参与单卷 / 多卷判定。 + while #tocs[series_id] < count do tocs[series_id][#tocs[series_id] + 1] = {} end +end +package.loaded["source.toc"] = { + read = function(_sid, series_id) return tocs[tostring(series_id)] end, + put = function(_sid, series_id, list) tocs[tostring(series_id)] = list; return true end, +} + +-- 统计状态文件(上次身份 + 章数判定)是上一轮的残留:连 .old 备份一起清, +-- 清了才是「首次拉取」(LuaSettings 读不到主文件会回落 .old)。 +local STATS_STATE = require("datastorage"):getSettingsDir() .. "/moonsource_kavita_stats.lua" +local function clearStatsState() + for _idx, suffix in ipairs({ "", ".old" }) do os.remove(STATS_STATE .. suffix) end +end +clearStatsState() + +local Base = require("utils.db") +local StatsDB = require("book.stats_db") +local BookDB = require("book.books_db") +local ProgressDB = require("book.progress_db") +local Kavita = require("moonsource_kavita.source") +Assert.not_nil(Base.open()) + +-- 书架容器行(书架同步的产物):统计侧只当物化标题 / 元数据来源。作者只给断言用到的那本。 +local function container(id, title, authors) + Assert.is_true(BookDB.upsertRemote({ source_id = "kavita", stable_id = id, title = title, + authors = authors, deleted = 0 }, false, true)) +end +container("7453", "太空漫游", "阿瑟·克拉克") +container("8661", "人类简史") +container("7460", "三国演义") +container("10634", "大剑") + +-- 本机逐页记录:10-14 已上报(云端会话已含,不能再算一遍);10-17 拉取后才读(未上报)。 +local L1_T = os.time({ year = 2026, month = 10, day = 14, hour = 21 }) +Assert.is_true(StatsDB.add({ + source_id = "kavita", stable_id = "7453:11273", record_type = "page", + page = 30, start_time = L1_T, duration = 900, total_pages = 150, +}, StatsDB.SYNCED)) + +-- 固定拉取时刻(2026-10-16 20:00 本地,晚于全量最后一天):只看 nil 参数的 os.time。 +local FETCHED = 1792152000 +local real_time = os.time +os.time = function(t) + if t == nil then return FETCHED end + return real_time(t) +end +local source = Kavita.new() + +--- 一次完整的统计同步:拉取 → 入库 → commit(状态文件只在入库成功后前进)。 +---@return BookStatsPullResult +local function pull() + local result, err + source:pullStatsAsync(function(res, pull_err) result, err = res, pull_err end) + Stubs.flush() + Assert.not_nil(result, err) + Assert.not_nil(StatsDB.replaceSynced("kavita", result.replace, result.rows), "入库必须成功") + result.commit() + return result +end + +local pulled = pull() + +--- 逐日聚合(dailyBySource):ymd → { seconds, pages }。 +local function calendar() + local rows = {} + for _idx, row in ipairs(StatsDB.dailyBySource("kavita")) do rows[row.ymd] = row end + return rows +end + +-- ① 单书累计:与云端 Σ 一致(§3 的 7453 两卷 / §4 的系列累计)。 +-- 10-14 的本地 900s 已含在云端快照里(sync_status=1 且早于拉取时刻):不加第二遍。 +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").total_seconds, 13921, "样本卷累计 = 云端 Σ") +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11271").total_seconds, 316, "同系列另一卷(只在其它设备读过)") +Assert.eq(StatsDB.summaryByBook("kavita", "7453").total_seconds, 0, "多卷系列不读在容器行上") +Assert.eq(StatsDB.summaryByBook("kavita", "8661").total_seconds, 3555, "单卷系列读在 series 行(§4)") +Assert.eq(StatsDB.summaryByBook("kavita", "7460:11285").total_seconds, 9517, "多章目录 → 逐卷身份(§4)") +-- 页数:云端会话的 pagesRead + 未被会话覆盖的本地页(18 号票)。10-14 的本地 1 页已上报、 +-- 当天有会话覆盖,不再加;22 是该卷各云端会话 pagesRead 之和。 +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").pages, 22, "单书页数 = 云端会话 pagesRead 之和") + +-- ② 日历逐日与 §2 一致;合计 = __kv:total。 +-- 页数口径与 §2 的 hist_p 在 9-19 / 9-24 / 9-29 差 1 / 1 / 2 页:那 4 页来自零时长条目, +-- 设计上整条丢弃(§4 已记「零时长条目 100 条,其中带页数 4 条合计 4 页」)。 +local CLOUD_DAYS = { + { "2026-09-18", 920, 5 }, { "2026-09-19", 2824, 10 }, { "2026-09-20", 2813, 25 }, + { "2026-09-21", 1183, 18 }, { "2026-09-22", 1682, 25 }, { "2026-09-23", 406, 18 }, + { "2026-09-24", 1179, 114 }, { "2026-09-25", 10, 3 }, { "2026-09-26", 1378, 71 }, + { "2026-09-27", 755, 0 }, { "2026-09-28", 104, 0 }, { "2026-09-29", 7942, 312 }, + { "2026-09-30", 6640, 22 }, { "2026-10-01", 643, 23 }, { "2026-10-03", 1104, 25 }, + { "2026-10-04", 638, 1 }, { "2026-10-05", 195, 0 }, { "2026-10-06", 809, 0 }, + { "2026-10-07", 503, 0 }, { "2026-10-08", 3663, 10 }, { "2026-10-09", 1092, 93 }, + { "2026-10-10", 363, 10 }, { "2026-10-11", 649, 26 }, { "2026-10-12", 1803, 103 }, + { "2026-10-13", 4514, 244 }, { "2026-10-14", 11665, 120 }, { "2026-10-15", 4541, 118 }, + { "2026-10-16", 220, 6 }, +} +local days = calendar() +local day_count = 0 +for _ymd in pairs(days) do day_count = day_count + 1 end +Assert.eq(day_count, #CLOUD_DAYS, "只有有有效时长的日子落桶(10-02 三条会话全零时长)") +Assert.is_nil(days["2026-10-02"], "零时长日不留桶") +-- 本地逐页记录按条累加;云端日桶显式 0 页不能被补成 1 页。 +local ZERO_PAGE_DAYS = 0 +for _idx, expected in ipairs(CLOUD_DAYS) do + local row = days[expected[1]] + Assert.not_nil(row, "缺日桶 " .. expected[1]) + Assert.eq(row.seconds, expected[2], "日时长 " .. expected[1]) + local stored_pages = expected[3] + (expected[1] == "2026-10-14" and 1 or 0) + if expected[3] == 0 then ZERO_PAGE_DAYS = ZERO_PAGE_DAYS + 1 end + Assert.eq(row.pages, stored_pages, "日页数增量 " .. expected[1]) +end +Assert.eq(ZERO_PAGE_DAYS, 5, "云端 0 页日就 5 天(09-27 / 09-28 / 10-05~10-07)") +local calendar_sum, calendar_pages = 0, 0 +for _ymd, row in pairs(days) do + calendar_sum = calendar_sum + row.seconds + calendar_pages = calendar_pages + row.pages +end +Assert.eq(StatsDB.summaryBySource("kavita").total_pages, calendar_pages, "总页数 = 日历逐日之和") +Assert.eq(calendar_sum, 60238, "各日之和 = 云端全量 Σ(§2)") +local total_row +for _idx, row in ipairs(pulled.rows) do + if row.record_type == "total" then total_row = row end +end +Assert.eq(total_row.duration, calendar_sum, "总时长 = __kv:total") +Assert.eq(StatsDB.summaryBySource("kavita").total_seconds, calendar_sum, "总览合计 = 日历合计") + +-- 分页:分页头说 2 页就拉 2 页,参数形态同真服务端。 +Assert.len(pagination_calls, 2) +Assert.matches(pagination_calls[1], "Libraries=8") +Assert.matches(pagination_calls[1], "Libraries=10") +Assert.matches(pagination_calls[1], "PageNumber=1&PageSize=200") +Assert.matches(pagination_calls[1], "TimeZoneId=Asia%%2FShanghai") +Assert.matches(pagination_calls[2], "PageNumber=2&") + +-- ③ 当日书单:云端读过、本机从没打开过的书也在;单书逐日与云端一致。 +local by_day_book = {} +for _idx, row in ipairs(StatsDB.dailyBooksBySource("kavita")) do + by_day_book[row.ymd] = by_day_book[row.ymd] or {} + by_day_book[row.ymd][row.stable_id] = row +end +Assert.eq(by_day_book["2026-09-29"]["7453:11271"].seconds, 316, "只在其它设备读过的卷进当日书单") +Assert.eq(by_day_book["2026-09-29"]["7453:11271"].max_total_pages, 0, "只有云端时长的那天没有页坐标") +Assert.eq(by_day_book["2026-09-30"]["8661"].seconds, 2885, "单卷系列按 series 身份进当日书单") +Assert.eq(by_day_book["2026-10-15"]["10634:17868"].seconds, 531, "多卷按章拆到各卷(210 + 321)") + +-- 12 号票物化的隐藏身份行:书单里的云端书能显示书名(不是裸 ID),且不上架 / 不标脏 / 不写进度。 +local cloud_only = BookDB.get("kavita", "7453:11271") +Assert.eq(cloud_only.title, "太空漫游 · 2001:太空漫游", "标题 = 系列 · 卷名") +Assert.eq(cloud_only.authors, "阿瑟·克拉克", "作者继承容器行") +Assert.eq(cloud_only.deleted, 1, "隐藏身份行:不进书架") +Assert.eq(cloud_only.sync_status, 1, "隐藏身份行:不标脏、不推云端") +Assert.is_nil(ProgressDB.get("kavita", "7453:11271"), "统计拉取不写进度:不会因此冒进「最近阅读」") +local shelf_ids = BookDB.libraryStableIdsBySource("kavita") +local materialized_on_shelf = false +for _idx, id in ipairs(shelf_ids) do + if id == "7453:11271" or id == "7453:11273" then materialized_on_shelf = true end +end +Assert.is_false(materialized_on_shelf, "物化行不是书架成员") +-- 容器行缺失的系列:物化跳过(12 号票语义),统计行照写。 +Assert.is_nil(BookDB.get("kavita", "7910:11896"), "没有容器行就不物化") +Assert.eq(by_day_book["2026-09-29"]["7910:11896"] ~= nil, true, "不物化不影响统计行") + +-- 单书逐日(详情页「最近几天」)与云端 §3 一致;10-14 = 云端 6734(本地 900 已含,不再加)。 +local function book_days(stable_id) + local rows, count = {}, 0 + for _idx, row in ipairs(StatsDB.dailyByBook("kavita", stable_id, 40)) do + rows[row.ymd] = row.seconds + count = count + 1 + end + return rows, count +end +local sample_days = { + ["2026-10-05"] = 195, ["2026-10-07"] = 503, ["2026-10-08"] = 2036, ["2026-10-11"] = 512, + ["2026-10-13"] = 979, ["2026-10-14"] = 6734, ["2026-10-15"] = 2962, +} +local sample_rows, sample_day_count = book_days("7453:11273") +Assert.eq(sample_rows["2026-10-14"], 6734, "云+本地同一天不双计") +Assert.eq(sample_day_count, 7, "只列有数据的日子(零时长日不出现)") +for ymd, seconds in pairs(sample_days) do Assert.eq(sample_rows[ymd], seconds, "单书逐日 " .. ymd) end +Assert.eq(book_days("7453:11271")["2026-09-29"], 316) + +-- ④ 时段:云端时段桶 + 本机逐页记录,合并口径与按天一致。 +local hourly = StatsDB.hourlyBySource("kavita") +local hourly_days = 0 +for _ymd in pairs(hourly) do hourly_days = hourly_days + 1 end +Assert.eq(hourly["2026-10-14"][22], 1043, "10-14 21 点:云端该格 1043s(本机同格已上报,不叠加)") +Assert.eq(hourly_days, 28, "有云端时长的每天都有时段分布") +Assert.eq(hourly["2026-09-18"][18], 738, "纯云端的日子也有时段(21 点 174 + 17 点 738 …)") +-- 日页面「标题时长 = 时段图逐格之和」:逐日必须对得上 +for _idx, row in ipairs(StatsDB.dailyBySource("kavita")) do + local sum = 0 + for h = 1, 24 do sum = sum + (hourly[row.ymd] and hourly[row.ymd][h] or 0) end + Assert.eq(sum, row.seconds, "时段逐日之和 = 日历 " .. row.ymd) +end + +-- ⑤ 拉取后本地新读:云端快照 + 增量,两边都不双计。 +local L2_T = FETCHED + 5 * 3600 +Assert.is_true(StatsDB.add({ + source_id = "kavita", stable_id = "7453:11273", record_type = "page", + page = 31, start_time = L2_T, duration = 90, total_pages = 150, +}, StatsDB.PENDING)) +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").total_seconds, 13921 + 90, "快照 + 拉取后新读") +Assert.eq(book_days("7453:11273")["2026-10-17"], 90, "增量单落到它自己的日子") +Assert.eq(calendar()["2026-10-17"].seconds, 90, "日历同样叠加增量") +Assert.eq(StatsDB.summaryBySource("kavita").total_seconds, 60238 + 90, "总览 = __kv:total + 拉取后新读") +Assert.eq(StatsDB.hourlyBySource("kavita")["2026-10-17"][2], 90, "增量进时段(1 点 = 第 2 格)") + +-- 再拉一次(本次只回样本 7453):整本替换不累加,云端消失的日桶清掉,本地逐页记录不动。 +history = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_7453.lua") +pulled = pull() +Assert.not_nil(pulled.rows[1]) +Assert.eq(StatsDB.summaryByBook("kavita", "7453:11273").total_seconds, 13921 + 90, "重拉不累加,增量仍在") +Assert.eq(StatsDB.summaryByBook("kavita", "8661").total_seconds, 0, "云端消失的书回落本地(没有本地记录 = 0)") +local again = calendar() +Assert.is_nil(again["2026-09-18"], "上一轮的云端日桶被全量重拉清掉") +Assert.eq(again["2026-10-14"].seconds, 6734, "样本日重写为本次回包值") +Assert.eq(again["2026-10-17"].seconds, 90, "本地逐页记录不受替换影响") +Assert.eq(StatsDB.hourlyBySource("kavita")["2026-10-14"][22], 716, "时段格重写为本次回包值(本机同格已上报,不叠加)") +Assert.is_nil(StatsDB.hourlyBySource("kavita")["2026-09-18"], "回包里消失的时段格清掉") + +-- 12 号票物化标题的第二轮回归:二次拉取时章数已判定(不再读目录),卷名必须取自状态文件里的 +-- 持久化卷名 —— 不能退容器名,更不能把上一轮物化出的好标题改写成「太空漫游 · 太空漫游」。 +Assert.eq(BookDB.get("kavita", "7453:11271").title, "太空漫游 · 2001:太空漫游", "二次拉取后标题不回退") +Assert.eq(BookDB.get("kavita", "7453:11273").title, "太空漫游 · 2010:太空漫游") + +-- 升级路径:老状态文件只有章数、没有卷名(本机第一轮物化时还没有持久化)。此时兜底标题 +-- 只能用于新行,不得覆盖既有行的真实标题。 +local stats_state = require("luasettings"):open(STATS_STATE) +stats_state:saveSetting("titles", {}) +stats_state:flush() +pulled = pull() +Assert.eq(BookDB.get("kavita", "7453:11271").title, "太空漫游 · 2001:太空漫游", + "没有持久化卷名时,兜底标题不覆盖既有标题") + +os.time = real_time +Base.close() +for _idx, suffix in ipairs({ "", "-wal", "-shm" }) do os.remove(db_path .. suffix) end +clearStatsState() diff --git a/tests/kavita/reviews_spec.lua b/tests/kavita/reviews_spec.lua new file mode 100644 index 0000000..b98d117 --- /dev/null +++ b/tests/kavita/reviews_spec.lua @@ -0,0 +1,59 @@ +--[[-- Kavita 系列书评:章节过滤、归属校验与卷共用缓存。 @module tests.moonsource_kavita.reviews_spec --]] +local Assert = require("support.assert") +local Stubs = require("support.stubs") +package.loaded.json = require("support.json_stub") +local Mapper = require("moonsource_kavita.mapper") +local wire = { reviews = { + { body = "

Book review

", tagline = "Title", chapterId = 0, seriesId = 5, + username = "Reader", rating = 4, totalVotes = 3, isExternal = false }, + { body = "Chapter review", chapterId = 8, seriesId = 5, username = "Reader" }, + { body = "External book review", chapterId = 0, seriesId = 0, + username = "External", isExternal = true }, +} } +local page, err = Mapper.bookReviewPage(wire, "5") +Assert.is_nil(err) +Assert.len(page.items, 2) +Assert.eq(page.items[1].text, "Title\nBook review") +Assert.eq(page.items[1].grade, 4) +Assert.eq(page.items[1].likes, 3) +Assert.eq(page.items[1].time, "", "协议无日期,不编造日期") +Assert.eq(page.items[2].text, "External book review") +Assert.len(Mapper.bookReviewPage({ reviews = {} }, "5").items, 0) +for _idx, bad in ipairs({ + {}, { reviews = { { body = "Bad", username = "Reader", chapterId = 0, seriesId = 99 } } }, + { reviews = { { body = false } } }, +}) do + local value, reason = Mapper.bookReviewPage(bad, "5") + Assert.is_nil(value) + Assert.eq(reason, "响应无效") +end +local source = require("moonsource_kavita.source").new() +local connected, requests, failed = true, 0, false +package.loaded["ui/network/manager"] = { isConnected = function() return connected end } +source.client.json = function(_self, method, path, query, _body, cb) + requests = requests + 1 + Assert.eq(method, "GET") + Assert.eq(path, "/api/Metadata/series-detail-plus") + Assert.eq(query.seriesId, 5) + if failed then cb(nil, "server failed") else cb(wire) end + return { cancel = function() end } +end +source:bookReviewsAsync({ source_id = "kavita", stable_id = "5:8" }, function(value, reason) + page, err = value, reason +end) +Assert.is_nil(err) +Assert.len(page.items, 2) +connected = false +source:bookReviewsAsync({ source_id = "kavita", stable_id = "5:9" }, function(value, reason) + page, err = value, reason +end) +Stubs.flush() +Assert.is_nil(err) +Assert.len(page.items, 2) +Assert.eq(requests, 1, "两个卷使用所属系列的整书缓存") +connected, failed = true, true +source:bookReviewsAsync({ source_id = "kavita", stable_id = "5" }, function(value, reason) + page, err = value, reason +end) +Assert.is_nil(page) +Assert.eq(err, "server failed") diff --git a/tests/kavita/setting_spec.lua b/tests/kavita/setting_spec.lua new file mode 100644 index 0000000..70d2f87 --- /dev/null +++ b/tests/kavita/setting_spec.lua @@ -0,0 +1,644 @@ +--[[-- +Kavita 设置页:服务器 / API Key / 书库 / 漫画缓存 / 进度心跳 / 请求超时 / 连接测试。 + +@module tests.moonsource_kavita.setting_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") + +local cfg = {} +local saved = 0 +local invalidated = 0 +local events = {} +package.preload["utils.settings"] = function() + return { + getSource = function() return cfg end, + saveSource = function(_, value) + cfg = value + saved = saved + 1 + events[#events + 1] = "save" + end, + } +end +package.preload["source.registry"] = function() + return { invalidate = function() invalidated = invalidated + 1 end } +end +-- 源模块只在设置行里读两个默认值;真常量由 client_spec / source_spec 钉住。 +-- 「测试连接」还要走 client:request,返回内容由 request_reply 控制。 +local request_reply = { version = "0.9.0" } +package.preload["moonsource_kavita.client"] = function() + return { + DEFAULT_TIMEOUT = 60, + new = function() + return { + api_key = "k", + configured = function() return true end, + request = function(_, _method, _path, _query, _body, callback) + callback(request_reply.version, request_reply.err) + end, + } + end, + } +end +package.preload["ui/network/manager"] = function() + return { isConnected = function() return true end } +end +-- 同步删除的忙碌窗会先强制重绘再动手;占用统计在下一拍算(03 E),测试里手动 flush。 +local repaints = 0 +local pending_ticks = {} +local function flush() + while #pending_ticks > 0 do + local tick = table.remove(pending_ticks, 1) + tick() + end +end +package.preload["ui/uimanager"] = function() + return { + forceRePaint = function() repaints = repaints + 1 end, + nextTick = function(_, fn) pending_ticks[#pending_ticks + 1] = fn end, + } +end +package.preload["moonsource_kavita.source"] = function() + return { DEFAULT_HEARTBEAT_INTERVAL = 30 } +end +package.preload["ui.themes.widgets.row"] = function() + return { widget = function(opts) return opts end, note = function(_width, text) return { text = text } end } +end +package.loaded["ui.themes"] = nil +package.preload["ui.themes"] = function() + return { + current = function() + return { space = { md = 8 }, color = { muted = 1, page = 2 } } + end, + px = function(n) return n end, + } +end +package.loaded["ui/geometry"] = nil +package.preload["ui/geometry"] = function() + return { new = function(_, opts) return opts end } +end +package.loaded["ui/widget/container/centercontainer"] = nil +package.preload["ui/widget/container/centercontainer"] = function() + return { new = function(_, opts) return opts end } +end +package.loaded["ui.themes.widgets.text"] = nil +package.preload["ui.themes.widgets.text"] = function() + return { + box = function(_, text, _width, _opts) + return { text = text, getSize = function() return { h = 10 } end } + end, + } +end + +-- 缓存适配层:探测 / 详情 / 保存后镜像;真实现由 cache_spec 钉住。 +local probe_result = { ok = false, state = "missing" } +local feature_text = "缓存(离线阅读与清理) · 双页拆分 · 裁切边框" +local mirror_failed = false +local register_calls, register_ok = {}, true +local available = {} +local summary_result +local summary_all_result +local chapters_result = {} +local delete_calls, delete_all_calls = {}, 0 +local delete_ok, delete_code = true, nil +local delete_all_ok, delete_all_code, delete_all_detail = true, nil, nil +-- 占用 / 计划只在详情页各取一次(06 B 的「占用只算一次」)。 +local summary_calls, summary_all_calls, chapters_calls = 0, 0, 0 +package.preload["moonsource_kavita.cache"] = function() + return { + probe = function() return probe_result end, + featureText = function() return feature_text end, + pluginsDir = function() return "/fake/plugins" end, + reprobe = function() return probe_result end, + mirrorFailed = function() return mirror_failed end, + registerServer = function(base_url, api_key) + register_calls[#register_calls + 1] = { base_url = base_url, api_key = api_key } + events[#events + 1] = "register" + if register_ok then return "srv-1" end + return nil, "settings_write_failed" + end, + available = function(cap) return available[cap] == true end, + summary = function() + summary_calls = summary_calls + 1 + return summary_result + end, + summaryAll = function() + summary_all_calls = summary_all_calls + 1 + return summary_all_result + end, + chapters = function() + chapters_calls = chapters_calls + 1 + return chapters_result + end, + plan = function(entries, filter, toc_read) + local out = { chapters = 0, bytes = 0, ids = {}, queued = 0, open = false } + for __, entry in ipairs(entries or {}) do + local pages = tonumber(entry.pages) or 0 + local server = toc_read and (tonumber(toc_read[tostring(entry.chapterId)]) or 0) or 0 + local read = entry.read == true or (pages > 0 and server >= pages) + if filter ~= "read" or read then + out.chapters = out.chapters + 1 + out.bytes = out.bytes + (tonumber(entry.bytes) or 0) + out.ids[#out.ids + 1] = entry.chapterId + if entry.queued then out.queued = out.queued + 1 end + if entry.open then out.open = true end + end + end + return out + end, + delete = function(ids) + delete_calls[#delete_calls + 1] = ids + if not delete_ok then return nil, delete_code, "nope" end + local wanted = {} + for __, id in ipairs(ids or {}) do wanted[tostring(id)] = true end + local kept = {} + for __, entry in ipairs(chapters_result) do + if not wanted[tostring(entry.chapterId)] then kept[#kept + 1] = entry end + end + chapters_result = kept + return true + end, + deleteAll = function() + delete_all_calls = delete_all_calls + 1 + if delete_all_ok then return true, nil, nil, delete_all_detail end + return nil, delete_all_code, "nope" + end, + resetShelf = function() end, + capabilityNames = function(caps, separator) + local names = {} + for name, on in pairs(caps or {}) do + if on == true then names[#names + 1] = tostring(name) end + end + table.sort(names) + return #names > 0 and table.concat(names, separator or ",") or "none" + end, + sizeText = function(bytes) + local value = tonumber(bytes) + if not value then return "未知" end + return string.format("%.1f MB", value / (1024 * 1024)) + end, + } +end +local Themed = require("support.theme_stubs") +Themed.install() + +-- kamare 在线更新:设置页只负责把行接上,网络 / 安装流程由 kamare_update_spec 钉住。 +local kamare_started = 0 +package.preload["moonsource_kavita.kamare_update"] = function() + return { + manualCheck = function() kamare_started = kamare_started + 1 end, + } +end + +local Config = require("support.config") +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +package.preload["moonsource_kavita.setting"] = function() + return dofile(PLUGIN .. "/setting.lua") +end +package.preload["moonsource_kavita.busy"] = function() + return dofile(PLUGIN .. "/busy.lua") +end + +local overlays, shelf_events, overlay_updates = {}, {}, 0 +local fake_desktop = { + settings_overlay = nil, + onEvent = function(_, event) shelf_events[#shelf_events + 1] = event end, +} +package.preload["desktop.pages.setting.overlay"] = function() + return { + push = function(desktop, spec) + overlays[#overlays + 1] = spec + desktop.settings_overlay = { + updateView = function() overlay_updates = overlay_updates + 1 end, + } + end, + } +end + +local Setting = require("moonsource_kavita.setting") + +local rows = Setting.rows({ path = PLUGIN, desktop = fake_desktop }) +-- 顺序用文案钉住(索引不再稳定),「漫画缓存」插在「书库」之后。 +local titles = {} +for _idx, make in ipairs(rows) do titles[#titles + 1] = make(600).title end +Assert.eq(#rows, 7, "服务器 / API Key / 书库 / 漫画缓存 / 进度心跳 / 请求超时 / 连接测试") +Assert.eq(table.concat(titles, "|"), + "服务器地址|API Key|书库|漫画缓存|进度心跳间隔|请求超时|测试连接", + "「漫画缓存」紧跟「书库」") + +-- 03 原型的三块分组:连接 / 缓存与同步 / 诊断。 +local sections = Setting.sections({ path = PLUGIN, desktop = fake_desktop }) +Assert.eq(#sections, 3, "设置页分三块") +local grouped = {} +for _idx, section in ipairs(sections) do + local names = {} + for _row_idx, make in ipairs(section.rows) do names[#names + 1] = make(600).title end + grouped[#grouped + 1] = section.title .. ":" .. table.concat(names, ",") +end +Assert.eq(table.concat(grouped, "|"), + "连接:服务器地址,API Key,书库|缓存与同步:漫画缓存,进度心跳间隔,请求超时|诊断:测试连接", + "分组与原型一致,扁平的 rows 顺序不变") + +--- 按标题找行(索引会随增删漂移)。 +---@param title string +---@return table +local function rowAt(title) + for _idx, make in ipairs(rows) do + local row = make(600) + if row.title == title then return row end + end + error("没有这一行: " .. title) +end + +Assert.eq(Setting.remote[1].key, "base_url") +Assert.eq(Setting.remote[2].key, "api_key") +Assert.is_true(Setting.remote[2].secret) +-- 远程管理网页表单只含连接配置;开关要在设备上调。 +Assert.len(Setting.remote, 2, "远程管理表单只有服务器地址与 API Key") + +-- 进度心跳:默认 30 秒,可调;0 = 关闭阅读期心跳。 +local hb = rowAt("进度心跳间隔") +Assert.eq(hb.kind, "nav") +Assert.eq(hb.status, "30 秒") +Assert.is_true(hb.status_on) +-- 副标题单行截断(行里有状态 + 箭头,文字位很窄),必须短到放得下;「为什么」在输入框提示里。 +Assert.eq(hb.subtitle, "阅读时补推进度,0 关闭") +hb.callback() +local spin = Themed.last("spin") +Assert.eq(spin.fields[1].value, 30) +Assert.eq(spin.fields[1].step, 10, "10 秒一档") +Assert.eq(spin.fields[1].min, 0) +Assert.eq(spin.fields[1].max, 600) +Assert.eq(spin.fields[1].label, "秒") +spin.callback(120) +Assert.eq(cfg.heartbeat_interval, 120) +Assert.eq(rowAt("进度心跳间隔").status, "120 秒") +Assert.eq(spin.shown and saved, 1, "保存一次") + +spin.callback(0) +Assert.eq(cfg.heartbeat_interval, 0, "0 落盘成关闭") +local off = rowAt("进度心跳间隔") +Assert.eq(off.status, "已关闭") +Assert.is_false(off.status_on) + +spin.callback(30) +Assert.is_nil(cfg.heartbeat_interval, "回到默认值不落盘") + +-- 请求超时:默认 60 秒,10 秒一档。 +local to = rowAt("请求超时") +Assert.eq(to.status, "60 秒") +Assert.is_false(to.status_on, "默认值不高亮") +to.callback() +spin = Themed.last("spin") +Assert.eq(spin.fields[1].value, 60) +Assert.eq(spin.fields[1].step, 10, "10 秒一档") +Assert.eq(spin.fields[1].min, 10) +spin.callback(180) +Assert.eq(cfg.timeout, 180) +Assert.eq(rowAt("请求超时").status, "180 秒") +Assert.is_true(rowAt("请求超时").status_on) +spin.callback(60) +Assert.is_nil(cfg.timeout, "回到默认值不落盘") + +Assert.eq(saved, 5) +Assert.eq(invalidated, 5, "每次保存都作废源实例,新配置立即生效,但不广播 SourceChanged") + +---------------------------------------------------------------------- +-- 漫画缓存:七态(含旧接口/镜像失败)+ 只读详情 + 09 手动安装说明。 +---------------------------------------------------------------------- +local function checkStatus(probe, expected, on, mirror) + probe_result = probe + mirror_failed = mirror == true + local row = rowAt("漫画缓存") + Assert.eq(row.kind, "nav") + Assert.eq(row.status, expected) + Assert.eq(row.status_on, on, expected) +end + +checkStatus({ ok = false, state = "missing" }, "未安装 / 未启用", false) +checkStatus({ ok = false, state = "official" }, "官方版(无缓存接口)", false) +checkStatus({ ok = false, state = "incompatible", api_version = 2 }, "版本不兼容", false) +checkStatus({ ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { chapters = true, delete = true, delete_all = true } }, + "增强版 v0.10.0-dev", true) +-- 旧接口:有 kamarecache 但没有 chapters / delete,清理不可用,不高亮。 +checkStatus({ ok = true, state = "enhanced", api_version = 1, version = "0.9.22", + capabilities = { status = true, summary = true } }, + "增强版 v0.9.22(旧接口)", false) +checkStatus({ ok = true, state = "enhanced", api_version = 1 }, "增强版(旧接口)", false) +checkStatus({ ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev" }, + "配置同步失败", false, true) + +-- 详情页:状态 → 清理;增强态不显示安装说明。 +local MB = 1024 * 1024 +cfg.base_url, cfg.api_key = "http://kav", "k" +local cache_path = "/fake/plugins/kamare.koplugin/src/kamarecache.lua" +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { open = true, index = true, status = true, summary = true, + chapters = true, delete = true, delete_all = true }, + path = cache_path, +} +mirror_failed = false +available = { summary = true } +summary_result = { used = 3 * MB, available = 9 * MB, chapters = 12 } +summary_all_result = { used = 4 * MB, available = 9 * MB, chapters = 15 } +chapters_result = { + { chapterId = 1, pages = 10, bytes = 1 * MB, read = false, queued = false, open = false }, + { chapterId = 2, pages = 10, bytes = 2 * MB, read = true, queued = false, open = false }, +} + +local function findSection(sections, title) + for __, section in ipairs(sections or {}) do + if section.title == title then return section end + end +end + +local function sectionRows(sections, title) + local section = findSection(sections, title) + local out = {} + for i, make in ipairs(section and section.rows or {}) do out[i] = make(600) end + return out +end + +local function statusOf(rows_list, title) + for __, row in ipairs(rows_list) do + if row.title == title then return row end + end +end + +--- 最近一次详情页的最终 sections:先取一拍(触发占用统计),flush 后再取一次。 +---@return BookThemeSection[] +local function currentSections() + overlays[#overlays].sections() + flush() + return overlays[#overlays].sections() +end + +rowAt("漫画缓存").callback() +local page = overlays[#overlays] +Assert.not_nil(page, "详情走叠层,不再用 ConfirmBox") +Assert.eq(page.title, "漫画缓存") +summary_calls, summary_all_calls, chapters_calls = 0, 0, 0 +overlay_updates = 0 +local pending_sections = page.sections() +Assert.eq(summary_calls + summary_all_calls, 0, "先画「正在统计…」,不在这一拍走盘") +Assert.eq(statusOf(sectionRows(pending_sections, "状态"), "缓存占用").subtitle, "正在统计…") +Assert.eq(chapters_calls, 1, "清理计划一次 chapters() 取全") +flush() +Assert.eq(summary_calls, 1, "下一拍算本服务器占用") +Assert.eq(summary_all_calls, 1, "「清理全部」的合计也算出来") +Assert.eq(overlay_updates, 1, "算完刷新叠层") +local sections = page.sections() +Assert.eq(chapters_calls, 2, "重画不重算占用,只重取计划") +local status_rows = sectionRows(sections, "状态") +local version_row = statusOf(status_rows, "kamare 增强版") +Assert.eq(version_row.status, "0.10.0-dev") +Assert.is_true(version_row.chevron, "版本行可点") +Assert.eq(version_row.subtitle, "点按检查 kamare 增强版更新") +version_row.callback() +Assert.eq(kamare_started, 1, "版本行交给 kamare 在线更新模块") +Assert.eq(statusOf(status_rows, "增强版功能").subtitle, feature_text, "功能清单原样显示") + +-- 清单缺失 / 不合法:不显示整行,版本行不受影响。 +feature_text = nil +local without_features = sectionRows(page.sections(), "状态") +Assert.is_nil(statusOf(without_features, "增强版功能"), "没有清单隐藏功能行") +Assert.not_nil(statusOf(without_features, "kamare 增强版"), "版本行仍在") +Assert.eq(statusOf(status_rows, "加载路径").subtitle, cache_path) +Assert.eq(statusOf(status_rows, "缓存占用").status, "12 章") +Assert.matches(statusOf(status_rows, "缓存占用").subtitle, "已用 3.0 MB,可用 9.0 MB") + +local cleanup_rows = sectionRows(sections, "清理") +Assert.eq(cleanup_rows[1].title, "清理已读") +Assert.matches(cleanup_rows[1].subtitle, "1 章") +Assert.eq(cleanup_rows[2].title, "清理本服务器") +Assert.matches(cleanup_rows[2].subtitle, "2 章") +Assert.eq(cleanup_rows[3].title, "清理全部") +Assert.matches(cleanup_rows[3].subtitle, "含未关联服务器 · 15 章", "全部清理用合计,不用本服务器") +Assert.is_nil(findSection(sections, "获取增强版"), "增强态不显示安装说明") + +-- 维护组已移除:更新入口只在诊断页。 +Assert.is_nil(findSection(sections, "维护")) + +-- 清理已读:确认 → 忙碌窗 → 删除 → 复查 → 刷新。 +delete_calls = {} +cleanup_rows[1].callback() +local read_confirm = Themed.last("confirm") +Assert.not_nil(read_confirm) +Assert.matches(read_confirm.text, "将删除 1 章") +local repaints_before = repaints +read_confirm.ok_callback() +local busy = Themed.last("progress_dialog") +Assert.not_nil(busy, "同步删除先弹忙碌窗") +Assert.eq(busy.title, "清理已读") +Assert.eq(busy.text, "正在清理…") +Assert.is_true(busy.dismissable == false, "忙碌窗不可关") +Assert.is_true(busy.shown, "先显示再删除") +Assert.is_true(busy.closed, "删完关闭") +Assert.eq(repaints, repaints_before + 1, "删除前强制重绘一次") +Assert.eq(#delete_calls, 1, "清理已读调用一次批量删除") +Assert.eq(#delete_calls[1], 1, "只删已读完的那一章") +Assert.matches(Themed.last("toast").text, "已清理 1 章") +Assert.eq(shelf_events[#shelf_events], "shelf_changed", "删除后刷新书架") + +-- 删除后占用必须重算(03 E):只 updateView 会留下删前的数字。 +summary_result = { used = 2 * MB, available = 9 * MB, chapters = 11 } +summary_all_result = { used = 3 * MB, available = 9 * MB, chapters = 14 } +local usage_calls_before = summary_calls + summary_all_calls +local after_cleanup = page.sections() +Assert.eq(statusOf(sectionRows(after_cleanup, "状态"), "缓存占用").subtitle, + "正在统计…", "删除后先画「正在统计…」") +flush() +Assert.eq(summary_calls + summary_all_calls, usage_calls_before + 2, "删除后重算本服务器与合计") +Assert.eq(statusOf(sectionRows(page.sections(), "状态"), "缓存占用").status, + "11 章", "占用数字跟着删除刷新") +Assert.matches(sectionRows(page.sections(), "清理")[3].subtitle, + "含未关联服务器 · 14 章", "清理全部的数字也刷新") + +-- 空缓存:三项都置灰(03 待确认 3),清理全部不再可点。 +cfg.base_url, cfg.api_key = "http://kav", "k" +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { summary = true, chapters = true, delete = true, delete_all = true }, + path = cache_path, +} +available = { summary = true } +local saved_chapters = chapters_result +chapters_result = {} +summary_result = { used = 0, available = 9 * MB, chapters = 0 } +summary_all_result = { used = 0, available = 9 * MB, chapters = 0 } +rowAt("漫画缓存").callback() +local empty_rows = sectionRows(currentSections(), "清理") +for idx = 1, 3 do + Assert.is_false(empty_rows[idx].enabled, "空缓存置灰:" .. empty_rows[idx].title) + Assert.is_false(empty_rows[idx].chevron, "空缓存不显示箭头:" .. empty_rows[idx].title) + Assert.eq(empty_rows[idx].subtitle, "没有可清理的缓存", "空缓存文案:" .. empty_rows[idx].title) +end +chapters_result = saved_chapters +summary_result = { used = 3 * MB, available = 9 * MB, chapters = 12 } +summary_all_result = { used = 4 * MB, available = 9 * MB, chapters = 15 } + +-- 旧接口:不出清理项,只写升级说明;设置行也不承诺清理。 +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.9.22", + capabilities = { status = true, summary = true }, path = cache_path, +} +Assert.eq(rowAt("漫画缓存").subtitle, "状态与获取增强版", "旧接口不承诺清理") +Assert.eq(rowAt("漫画缓存").status, "增强版 v0.9.22(旧接口)") +rowAt("漫画缓存").callback() +local old_rows = sectionRows(currentSections(), "清理") +Assert.eq(#old_rows, 1, "旧接口只有一段说明") +Assert.eq(old_rows[1].title, "当前 kamare 没有清理接口") +Assert.matches(old_rows[1].subtitle, "chapters / delete_all", "说明要升级到什么") +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { open = true, index = true, status = true, summary = true, + chapters = true, delete = true, delete_all = true }, + path = cache_path, +} + +-- 清理全部:没有服务器也能用,确认文案含未关联。 +cfg.base_url, cfg.api_key = "", "" +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { summary = true, chapters = true, delete = true, delete_all = true }, + path = cache_path, +} +available = { summary = true } +rowAt("漫画缓存").callback() +summary_all_calls, summary_calls = 0, 0 +local unconfigured = currentSections() +Assert.eq(sectionRows(unconfigured, "清理")[1].title, "未配置服务器") +Assert.eq(summary_all_calls, 1, "没有服务器时占用取合计") +Assert.eq(summary_calls, 0, "没有服务器时不查单服务器") +Assert.matches(statusOf(sectionRows(unconfigured, "状态"), "缓存占用").subtitle, "含未关联服务器") +sectionRows(unconfigured, "清理")[2].callback() +local all_confirm = Themed.last("confirm") +Assert.matches(all_confirm.text, "含未关联服务器") +Assert.matches(all_confirm.text, "共 15 章", "确认框用所有服务器的合计,不用本服务器") +all_confirm.ok_callback() +Assert.eq(Themed.last("progress_dialog").title, "清理全部缓存", "全部清理同样有忙碌窗") +Assert.eq(delete_all_calls, 1, "清理全部走 deleteAll") + +-- 未安装:安装说明;路径归一;不显示占用。 +probe_result = { ok = false, state = "missing" } +available = {} +cfg.base_url = "" +rowAt("漫画缓存").callback() +local missing = currentSections() +local missing_version = statusOf(sectionRows(missing, "状态"), "kamare 增强版") +Assert.eq(missing_version.status, "未安装") +Assert.eq(missing_version.subtitle, "点按检查并安装 kamare 增强版", "没有 kamare 时引导点版本行") +local install = findSection(missing, "获取增强版") +Assert.not_nil(install, "非增强态显示安装说明") +local install_text = install.rows[1](600).text or "" +Assert.matches(install_text, "releases/latest") +Assert.matches(install_text, "kamarecache.lua") +Assert.matches(install_text, "增强版功能随版本不同") +Assert.matches(install_text, "上方「kamare 增强版」") +Assert.matches(install_text, "koreader/plugins", "手动安装路径带 koreader/ 前缀") +Assert.is_nil(findSection(missing, "清理"), "未安装不显示清理") + +-- 版本不兼容:安装说明前先讲清 API 不兼容(03 原型)。 +probe_result = { ok = false, state = "incompatible", api_version = 2 } +rowAt("漫画缓存").callback() +local incompatible = sectionRows(currentSections(), "版本与获取") +Assert.eq(incompatible[1].title, "版本不兼容") +Assert.matches(incompatible[1].subtitle, "API v2") +Assert.not_nil(incompatible[2].text, "后面仍是安装说明") + +-- 镜像失败:状态区给出警告 + 重试同步。 +probe_result = { + ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { summary = true, chapters = true, delete = true, delete_all = true }, + path = "/fake/plugins//kamare.koplugin/kamarecache.lua", +} +mirror_failed = true +available = { summary = true } +rowAt("漫画缓存").callback() +local mirrored = currentSections() +local mirror_row = statusOf(sectionRows(mirrored, "状态"), "配置同步失败") +Assert.not_nil(mirror_row, "镜像失败在状态区") +Assert.eq(mirror_row.status, "重试同步") +Assert.is_nil(statusOf(sectionRows(mirrored, "状态"), "加载路径").subtitle:find("//", 1, true), + "加载路径归一成单斜杠") +mirror_failed = false + +-- 保存后镜像:先落 moon 自己的配置,再 register_server;失败 toast 但不阻断。 +cfg.base_url, cfg.api_key = "http://kav", "k" +probe_result = { ok = true, state = "enhanced", api_version = 1, version = "0.10.0" } +register_calls, register_ok, events = {}, true, {} +local before = saved +rowAt("进度心跳间隔").callback() +Themed.last("spin").callback(70) +Assert.eq(saved, before + 1) +Assert.eq(register_calls[1].base_url, "http://kav") +Assert.eq(register_calls[1].api_key, "k") +Assert.eq(events[#events - 1], "save", "先存 moon 自己的配置") +Assert.eq(events[#events], "register", "镜像失败也不影响 moon 保存") + +register_ok = false +before = saved +rowAt("进度心跳间隔").callback() +Themed.last("spin").callback(60) +Assert.eq(Themed.last("toast").text, "无法同步配置到 kamare", "用户主动保存失败要提示") +Assert.eq(saved, before + 1, "toast 不阻断 moon 自己的保存") + +-- 未安装:不假装能镜像。 +probe_result = { ok = false, state = "missing" } +register_calls = {} +rowAt("进度心跳间隔").callback() +Themed.last("spin").callback(30) +Assert.len(register_calls, 0, "没有缓存接口时跳过镜像") + +---------------------------------------------------------------------- +-- 测试连接:只测 Kavita,不碰 kamare。 +---------------------------------------------------------------------- +Assert.eq(rowAt("测试连接").kind, "action") +Assert.eq(rowAt("测试连接").subtitle, "检查 Kavita 服务器连接与版本") + +---@param probe table +---@param mirror boolean|nil +---@param version string|nil +---@param err string|nil +---@return string +local function connectToast(probe, mirror, version, err) + probe_result = probe + mirror_failed = mirror == true + request_reply = { version = version, err = err } + rowAt("测试连接").callback() + return Themed.last("toast").text +end + +local enhanced = { ok = true, state = "enhanced", api_version = 1, version = "0.10.0-dev", + capabilities = { chapters = true, delete = true, delete_all = true } } +Assert.eq(connectToast(enhanced, false, "0.9.0"), "连接正常\nKavita 0.9.0") +Assert.eq(connectToast(enhanced, true, "0.9.0"), "连接正常\nKavita 0.9.0", + "kamare 镜像失败不影响 Kavita 连接结果") +Assert.eq(connectToast({ ok = false, state = "missing" }, false, "0.9.0"), + "连接正常\nKavita 0.9.0", "测试连接不碰 kamare") +Assert.eq(connectToast({ ok = false, state = "incompatible", api_version = 2 }, false, "0.9.0"), + "连接正常\nKavita 0.9.0") +-- 版本过旧 / 请求失败仍报真正原因,不能让缓存状态盖过去。 +Assert.eq(connectToast(enhanced, false, "0.8.9"), + "连接正常\nKavita 0.8.9 过旧,需要 0.9 及以上") +Assert.eq(connectToast(enhanced, false, nil, "HTTP 401"), "连接失败\nHTTP 401") +Assert.eq(connectToast(enhanced, false, nil, nil), "连接正常\n无法识别 Kavita 版本") + +-- 换服务器清理失败:共享配置、磁盘、kamare 镜像都必须保持旧值。 +do + cfg.base_url, cfg.api_key = "http://old", "old-key" + local saved_before, mirrored_before = saved, #register_calls + package.loaded["source.logout"] = { + replaceLibrary = function() return false end, + } + rowAt("服务器地址").callback() + Themed.last("input").callback("http://new") + Assert.eq(cfg.base_url, "http://old") + Assert.eq(cfg.api_key, "old-key") + Assert.eq(saved, saved_before) + Assert.eq(#register_calls, mirrored_before) + Assert.eq(Themed.last("toast").text, "准备本地同步失败") +end diff --git a/tests/kavita/shelf_cache_spec.lua b/tests/kavita/shelf_cache_spec.lua new file mode 100644 index 0000000..7a08a62 --- /dev/null +++ b/tests/kavita/shelf_cache_spec.lua @@ -0,0 +1,237 @@ +--[[-- +Kavita 源的书架缓存钩子:shelf_cache 能力、shelfCache 同步返回投影、 +syncBooksAsync 同步后预热(05 A1)、coverRequest 优先本地封面(05 A8)。 + +不复用 source_spec 的整套书架夹具:这里只碰钩子本身,HTTP / 书库 / 目录都最小打桩。 + +@module tests.moonsource_kavita.shelf_cache_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Stubs = require("support.stubs") +Stubs.install() + +-- 日志:pcall 的失败必须被检查并记录,不能静默吞掉(项目审计口径)。 +local warns = {} +package.loaded["utils.log"] = { + dbg = function() end, + info = function() end, + error = function() end, + warn = function(...) + local parts = {} + for index = 1, select("#", ...) do + parts[#parts + 1] = tostring(select(index, ...)) + end + warns[#warns + 1] = table.concat(parts, " ") + end, +} + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +-- 走 preload 不改 package.path:插件根上的 main.lua 会顶掉月读的 main。 +for _idx, name in ipairs({ "client", "position", "annotation", "source", "cache", "volume_list", "stats" }) do + package.preload["moonsource_kavita" .. (name == "source" and ".source" or "." .. name)] = function() + return dofile(PLUGIN .. "/" .. (name == "source" and "source" or name) .. ".lua") + end +end + +-- 往返桩:encode 登记表并发令牌,decode 凭令牌取回(不是令牌就报错,同真解析器)。 +local encoded = {} +package.preload["json"] = function() + return { + encode = function(value) + encoded[#encoded + 1] = value + return "\0json" .. #encoded + end, + decode = function(text) + return encoded[tonumber(text:match("^%z?json(%d+)$"))] or error("not json: " .. text) + end, + } +end + +local cfg = { base_url = "http://kav/", api_key = "k", libraries = { ["1"] = true } } +package.preload["utils.settings"] = function() + return { + get = function() return { active_source = "local" } end, + save = function() end, + getSource = function() return cfg end, + saveSource = function() end, + } +end + +-- HTTP:只有书架快照这一个路由。 +local routes, requested = {}, {} +package.preload["http.request"] = function() + return { + ok = function(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 + end, + header = function() end, + request = function(opts, cb) + requested[#requested + 1] = opts + local route = routes[opts.method .. " " .. opts.url:match("^http://kav(/[^?]*)")] + require("ui/uimanager"):nextTick(function() + cb(route and route(opts) or { code = 404, body = "" }) + end) + return { cancel = function() end } + end, + } +end + +-- 本地库:钩子只需要「取一本书」与「已同步身份」。 +local books = {} +package.loaded["book.books_db"] = { + get = function(_source_id, stable_id) return books[stable_id] end, + libraryStableIdsBySource = function() return {} end, +} +package.loaded["book.progress_db"] = { + get = function() return nil end, +} +package.loaded["book.store"] = { rememberMany = function() end } + +local sequence = {} +package.loaded["source.shelf"] = { + reconcile = function(_source_id, list) + sequence[#sequence + 1] = "reconcile" + return { pulled = #list, pushed = 0, hidden = 0, conflicts = 0, skipped = false } + end, +} + +-- 封面路径只关心「本地缓存 / 在线地址」的分支:目录查不到卷时退回系列封面(卷封面见 source_spec)。 +package.loaded["source.toc"] = { read = function() return nil end } +local SourceMod = require("moonsource_kavita.source") +local Cache = require("moonsource_kavita.cache") +local source = SourceMod.new() + +-- 能力:声明 shelf_cache,UI 据此决定断网时是否收窄书架(05 A2)。 +local caps = source:capabilities() +Assert.is_true(caps.shelf_cache, "Kavita 声明书架缓存能力") +Assert.is_true(caps.stats_pull, "原有能力不受影响") + +-- shelfCache:同步返回适配层记忆的投影;未配置不触盘。 +local projection = { series_ids = { ["700"] = true }, mark = { ["700"] = true }, cover = {} } +local shelf_calls = 0 +local real_shelf = Cache.shelf +Cache.shelf = function() + shelf_calls = shelf_calls + 1 + return projection +end +Assert.eq(source:shelfCache(), projection, "shelfCache 原样交回适配层投影") +Assert.eq(shelf_calls, 1) +cfg.base_url = "" +Assert.is_nil(SourceMod.new():shelfCache(), "未配置返回 nil") +Assert.eq(shelf_calls, 1, "未配置不读投影") +cfg.base_url = "http://kav/" + +-- coverRequest:投影里有本地封面且文件存在 → 本地路径,不再走鉴权 URL(05 A8)。 +local cover_path = Config.dir() .. "/shelf_cover_700.jpg" +local file = assert(io.open(cover_path, "wb")) +file:write("jpg") +file:close() +Cache.shelf = function() return { series_ids = {}, mark = {}, cover = { ["700"] = cover_path } } end +local req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700" })) +Assert.eq(req.url, cover_path, "已缓存系列用本地封面") +Assert.is_nil(req.headers, "本地文件不需要鉴权头") +Assert.eq(req.authoritative, true, "源封面压过本地抽页缓存") +-- 卷身份同样借系列封面(chapter-cover 是扫描页,不能当封面)。 +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700:7001" })) +Assert.eq(req.url, cover_path, "卷身份也用已缓存系列封面") +-- 投影给了路径但文件没了 → 维持在线系列封面。 +Cache.shelf = function() return { series_ids = {}, mark = {}, cover = { ["700"] = cover_path .. ".gone" } } end +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700" })) +Assert.is_true(req.url:find("series-cover", 1, true) ~= nil, "文件不存在退回在线封面") +Assert.not_nil(req.headers) +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700:7001" })) +Assert.is_true(req.url:find("series-cover", 1, true) ~= nil, "卷身份也走系列封面") +-- 适配层没给投影(无 index):照旧在线封面。 +Cache.shelf = function() return nil end +req = select(1, source:coverRequest({ source_id = "kavita", stable_id = "700" })) +Assert.is_true(req.url:find("series-cover", 1, true) ~= nil) +Cache.shelf = real_shelf + +-- syncBooksAsync 预热:对账后、回调前把投影建好,进书架时 O(1)(05 A1)。 +sequence, requested = {}, {} +Cache.shelf = function() + sequence[#sequence + 1] = "shelf" + return projection +end +routes["POST /api/Series/all-v2"] = function() + return { code = 200, body = require("json").encode({ + { id = 700, name = "漫画一", libraryName = "漫画", wordCount = 10 }, + }) } +end +source.backfillMeta = function() end +local synced +source:syncBooksAsync(nil, function(result, err) + sequence[#sequence + 1] = "cb" + synced = { result = result, err = err } +end) +Stubs.flush() +Assert.not_nil(synced) +Assert.is_nil(synced.err) +Assert.eq(synced.result.pulled, 1, "对账结果照旧回调") +Assert.eq(table.concat(sequence, ","), "reconcile,shelf,cb", "预热排在回调之前") + +-- 手动刷新 / 书库重扫(force)必须让投影失效并重建;后台同步沿用记忆(05 A1)。 +-- 拉回的新缓存状态看不见 = 用户点了刷新但书架标记不更新。 +sequence, requested = {}, {} +local resets = 0 +local real_reset = Cache.resetShelf +Cache.resetShelf = function() + resets = resets + 1 + sequence[#sequence + 1] = "reset" +end +Cache.shelf = function() + sequence[#sequence + 1] = "shelf" + return projection +end +local background +source:syncBooksAsync(nil, function(result, err) background = { result = result, err = err } end) +Stubs.flush() +Assert.not_nil(background and background.result) +Assert.eq(resets, 0, "后台同步不丢投影") +Assert.eq(table.concat(sequence, ","), "reconcile,shelf", "后台同步只预热现有记忆") +sequence = {} +local forced +source:syncBooksAsync({ force = true }, function(result, err) forced = { result = result, err = err } end) +Stubs.flush() +Assert.not_nil(forced and forced.result) +Assert.eq(resets, 1, "手动刷新让投影失效") +Assert.eq(table.concat(sequence, ","), "reset,reconcile,shelf", "重扫先失效再重建,回调前投影已就绪") +sequence = {} +Cache.resetShelf = real_reset + +-- 预热失败不拖垮同步:投影只是书架标记,缓存模块异常照样要回调对账结果。 +sequence, requested = {}, {} +warns = {} +local broken_sequence = sequence +Cache.shelf = function() + broken_sequence[#broken_sequence + 1] = "shelf" + error("kamare index broken") +end +local second +source:syncBooksAsync(nil, function(result, err) second = { result = result, err = err } end) +Stubs.flush() +Assert.not_nil(second and second.result, "预热异常不影响同步结果") +Assert.eq(table.concat(sequence, ","), "reconcile,shelf") +-- 第二次仍失败:不能每次同步都刷一行日志(一次性),但也不能静默。 +source:syncBooksAsync(nil, function(result, err) second = { result = result, err = err } end) +Stubs.flush() +Assert.eq(#warns, 1, "投影预热失败检查并只记一次") +Assert.matches(warns[1] or "", "shelf") +Cache.shelf = real_shelf + +-- Registry.reload() 会重建源实例:新实例顺手丢掉旧服务器的投影(05 A1 的第三类失效点)。 +local resets = 0 +local real_reset = Cache.resetShelf +Cache.resetShelf = function() + resets = resets + 1 + return real_reset() +end +SourceMod.new() +Assert.eq(resets, 1, "重建源实例即失效书架投影") +Cache.resetShelf = real_reset + +return true diff --git a/tests/kavita/source_spec.lua b/tests/kavita/source_spec.lua new file mode 100644 index 0000000..e3eeac4 --- /dev/null +++ b/tests/kavita/source_spec.lua @@ -0,0 +1,2980 @@ +--[[-- +extensions/moonsource-kavita.koplugin:经源注册表发现;书架、开书(单卷 / 选卷 / 失败)、 +封面、进度双向换算。HTTP 与书库全部打桩。 + +@module tests.moonsource_kavita.source_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Stubs = require("support.stubs") +local Themed = require("support.theme_stubs") + +-- 往返桩:encode 登记表并发一个令牌串,decode 凭令牌取回(不是令牌就报错,同真解析器)。 +local encoded = {} +local JSON = { + encode = function(value) + encoded[#encoded + 1] = value + return "\0json" .. #encoded + end, + decode = function(text) + return encoded[tonumber(text:match("^%z?json(%d+)$"))] or error("not json: " .. text) + end, +} +package.loaded["json"] = JSON +Themed.install() +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +-- 走 preload 不改 package.path:runner 只还原 preload/loaded,插件根上的 main.lua 会顶掉月读的 main。 +for _idx, name in ipairs({ "client", "position", "annotation", "source", "setting", "cache", "volume_list", "stats" }) do + package.preload["moonsource_kavita" .. (name == "source" and ".source" or "." .. name)] = function() + return dofile(PLUGIN .. "/" .. (name == "source" and "source" or name) .. ".lua") + end +end +-- 首页组件另有 on_deck_spec;这里只验证描述表把它交出去。 +local on_deck = { id = "kavita.on_deck" } +package.preload["moonsource_kavita.on_deck"] = function() return on_deck end + +local cfg = { base_url = "http://kav/", api_key = " k ", libraries = { ["2"] = true, ["1"] = true } } +local ffi = require("ffi") +ffi.cdef("int setenv(const char *name, const char *value, int overwrite);") +local function setTZ(tz) ffi.C.setenv("TZ", tz, 1) end +setTZ("CST-8") +package.preload["utils.settings"] = function() + local common = { active_source = "local" } + return { + get = function() return common end, + save = function() end, + getSource = function() return cfg end, + saveSource = function() end, + } +end +for _idx, id in ipairs({ "local", "moon", "wechat", "jdread", "copymanga", "fanqie" }) do + package.loaded["source." .. id] = { + meta = function() return { id = id, name = id, type = "book" } end, + new = function() return { id = id } end, + } +end + +local online = true +package.loaded["ui/network/manager"] = { isConnected = function() return online end } + +-- HTTP:按 "METHOD /path" 路由;值为响应表或 fun(opts) → 响应表。 +local routes, calls, held = {}, {}, {} +local download = { code = 200, body = "PK\3\4epub" } +package.loaded["http.request"] = { + ok = function(code) + code = tonumber(code) + return code ~= nil and code >= 200 and code < 300 + end, + -- 与真 Request.header 同语义(大小写不敏感;测试里响应头是普通表)。 + header = function(res, name) + for key, value in pairs(res and res.headers or {}) do + if type(key) == "string" and key:lower() == name:lower() then return value end + end + end, + request = function(opts, cb) + calls[#calls + 1] = opts + local route = routes[opts.method .. " " .. opts.url:match("^http://kav(/[^?]*)")] + require("ui/uimanager"):nextTick(function() + local response = type(route) == "function" and route(opts) or route or { code = 404, body = "" } + -- { hold = true, reply = … }:把回包压住,测试用 held 自行放出(验证取消 / 在途中止)。 + if type(response) == "table" and response.hold then + held[#held + 1] = function() cb(response.reply) end + return + end + cb(response) + end) + return { cancel = function() end } + end, + download = function(opts, dest, cb) + calls[#calls + 1] = opts + local file = assert(io.open(dest, "wb")) + file:write(download.body) + file:close() + require("ui/uimanager"):nextTick(function() cb(true, nil, { code = download.code }) end) + return { cancel = function() end } + end, +} +local function json(data, headers) return { code = 200, body = JSON.encode(data), headers = headers } end +local function query(opts, key) return opts.url:match("[?&]" .. key .. "=([^&]*)") end + +-- 书库:books 行(path)、目录缓存、本地进度。 +local books, tocs, stale, progress, remembered, touched, reconciled = {}, {}, {}, {}, {}, {}, nil +local fixed = {} +-- 脏行(sync_status=0):漫画走 kamare 时只写 upsertRemote,任何 upsert 都是回归。 +local dirty = {} +local toc_fresh = true +local shelf_ids, written, written_opts = {}, {}, {} +package.loaded["book.books_db"] = { + get = function(_sid, id) return books[id] end, + getToc = function(_sid, id) return stale[id] end, + libraryStableIdsBySource = function() return shelf_ids end, + -- 补空字段:脏行也允许补,但不覆盖非空值(与真实现同步)。 + fillEmptyMeta = function(_sid, id, authors, intro) + local row = books[id] + if not row then return false end + local changed = false + if authors and authors ~= "" and (row.authors == nil or row.authors == "") then + row.authors, changed = authors, true + end + if intro and intro ~= "" and (row.intro == nil or row.intro == "") then + row.intro, changed = intro, true + end + return changed + end, +} +package.loaded["book.progress_db"] = { + get = function(_sid, id) return progress[id] end, + list = function(_sid, series_id) + local rows = {} + local prefix = series_id .. ":" + for id, row in pairs(progress) do + if id:sub(1, #prefix) == prefix then rows[id] = row end + end + return rows + end, + upsertRemote = function(_sid, id, pos, opts) + written[id] = pos + written_opts[id] = opts + return true + end, + upsert = function(_sid, id, pos) + dirty[id] = true + written[id] = pos + return true + end, + unsynced = function() + local ids = {} + for id in pairs(dirty) do ids[#ids + 1] = id end + table.sort(ids) + return ids + end, + fixRemoteTime = function(_sid, id, at) + fixed[id] = at + return true + end, +} +package.loaded["book.store"] = { + touch = function(path, ref) + touched[#touched + 1] = { path = path, stable_id = ref.stable_id } + books[ref.stable_id] = { path = path } + return true + end, + rememberMany = function(list) + for _idx, book in ipairs(list) do remembered[book.stable_id] = book end + end, +} +package.loaded["source.toc"] = { + -- allow_stale:过期目录也认(身份判定用;卷数 / 卷身份不随时间变)。 + read = function(_sid, id, allow_stale) + return (allow_stale or toc_fresh) and tocs[id] or (stale[id] and JSON.decode(stale[id])) + end, + put = function(_sid, id, list) + tocs[id] = list + return true + end, +} +package.loaded["source.shelf"] = { + reconcile = function(source_id, list, force) + reconciled = { source_id = source_id, books = list, force = force } + return { pulled = #list, pushed = 0, hidden = 0, conflicts = 0, skipped = false } + end, +} +local WORK = Config.dir() .. "/kavita_spec" +-- 后台补简介的 done 状态落在沙箱 settings 里:上一轮跑挂留下的状态会让本轮跳过补全。 +os.remove(require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") +-- 统计状态(上次身份 + 系列章数)同理:留着会让本轮读不到「首次拉取」的行为。 +-- .old 备份一起去掉:主文件被删时 LuaSettings 会回落它(别的 spec 中断留下的档就活过来了)。 +local STATS_STATE = require("datastorage"):getSettingsDir() .. "/moonsource_kavita_stats.lua" +for _idx, suffix in ipairs({ "", ".old" }) do os.remove(STATS_STATE .. suffix) end +os.execute("rm -rf '" .. WORK .. "'") +package.loaded["utils.db"] = { transaction = function(fn) return fn() end } +package.loaded["utils.paths"] = { + ensureBookWork = function(id) os.execute("mkdir -p '" .. WORK .. "/" .. id .. "'") end, + bookWorkDir = function(id) return WORK .. "/" .. id end, +} + +package.loaded["pluginloader"] = { enabled_plugins = { Config.selfPlugin() } } +package.loaded["source.registry"] = nil +package.preload["source.kavita"] = function() return require("moonsource_kavita.source") end +local Registry = require("source.registry") + +Assert.eq(Registry.meta("kavita").type, "book") +local source = Registry.resolve("kavita") +Assert.is_true(source:configured()) +Assert.is_false(source:capabilities().shelf_push, "Kavita 书架只拉不推") +Assert.eq(require("moonsource_kavita.source").DEFAULT_HEARTBEAT_INTERVAL, 30, "设置页读的默认心跳间隔") + +---@return any, any, any +local function run(method, ...) + local a, b, c + local n = select("#", ...) + local args = { ... } + args[n + 1] = function(x, y, z) a, b, c = x, y, z end + source[method](source, unpack(args, 1, n + 1)) + Stubs.flush() + return a, b, c +end + +-- 书架:按库分页拉 series,库名即分类;Key 去空白、地址去尾斜杠。 +local series_page = {} +for i = 1, 500 do series_page[i] = { id = i, name = "S" .. i, libraryName = "小说", wordCount = i == 1 and 120000 or 0, + lastChapterAddedUtc = i == 1 and "2026-01-02T03:04:05.123" or nil } end +routes["POST /api/Series/all-v2"] = function(opts) + local body = JSON.decode(opts.body) + local lib, page = body.Statements[1].Value, query(opts, "pageNumber") + if lib == "1" and page == "1" then return json(series_page) end + if lib == "1" then return json({ { id = 501, name = "S501", libraryName = "小说" } }) end + return json({ { id = 900, name = "漫画一", libraryName = "漫画", format = 1, pages = 20, pagesRead = 5, + latestReadDate = "2026-01-02T03:04:05.123" } }) +end +local result = run("syncBooksAsync", nil) +Assert.eq(#reconciled.books, 502) +Assert.eq(result.pulled, 503, "对账 502 本 + 1 本漫画进度") +Assert.eq(reconciled.source_id, "kavita") +Assert.eq(reconciled.books[502].category, "漫画") +Assert.eq(reconciled.books[1].stable_id, "1") +Assert.eq(reconciled.books[1].meta.words, 120000, "书架带字数(0 = 未知,入库时丢掉)") +Assert.eq(reconciled.books[1].series, "S1", "系列列填 Kavita series 名,否则图书馆系列页签全是「无系列」") +Assert.eq(reconciled.books[1].inserted_at, 1767323045, "加入时间用 lastChapterAddedUtc,图书馆「最近添加」才跟 Kavita 一致") +Assert.eq(calls[1].headers["x-api-key"], "k") +Assert.matches(calls[1].url, "^http://kav/api/Series/all%-v2%?") +Assert.eq(calls[1].timeout, 60, "拉书架带足够长的超时,慢设备不会一拉就 30s 超时") +Assert.is_true(run("syncBooksAsync", { dirty_only = true }).skipped, "没有删书接口,只推脏行时跳过") +cfg.libraries = {} +local none, err = run("syncBooksAsync", nil) +Assert.is_nil(none) +Assert.matches(err, "选择书库") +cfg.libraries = { ["1"] = true } + +-- 单卷 series:拉目录(标题退到文件名)、写作者简介、下载到 series 行。 +routes["GET /api/Series/10"] = json({ id = 10, name = "长夜", libraryId = 1, format = 3 }) +routes["GET /api/Series/volumes"] = function(opts) + local sid = query(opts, "seriesId") + if sid == "10" then + return json({ { id = 100, name = "1", chapters = { { + id = 1000, title = "-100000", titleName = "", format = 3, pages = 12, pagesRead = 0, + files = { { filePath = "/books/长夜/Long Night.epub" } }, + } } } }) + end + if sid == "20" then + return json({ + { id = 200, name = "1", chapters = { { id = 2001, titleName = "第一卷", format = 3, pages = 8, pagesRead = 8 } } }, + { id = 201, name = "2", chapters = { { id = 2002, titleName = "第二卷", format = 3, pages = 10, pagesRead = 0, + summary = "第二卷简介" } } }, + }) + end + if sid == "30" then + return json({ { id = 300, chapters = { { id = 3000, titleName = "图册", format = 4, pages = 50 } } } }) + end + return json({ { id = 400, chapters = { { id = 4000, titleName = "散图", format = 0, pages = 3 } } } }) +end +routes["GET /api/Series/metadata"] = json({ summary = "简介", writers = { { name = "甲" }, { name = "乙" } }, + publishers = { { name = "某出版社" } }, releaseYear = 2019, language = "zh" }) +for _idx, sid in ipairs({ 20, 30, 40, 50 }) do + routes["GET /api/Series/" .. sid] = json({ id = sid, name = "合集" .. sid, libraryId = 2 }) +end + +-- 增量书架:快照指纹没变、本地书架非空就跳过对账;漫画按已读页回填远端进度(本地同页不重写)。 +cfg.libraries = { ["2"] = true, ["1"] = true } +Assert.eq(written["900"].page, 6, "首轮同步就回填漫画进度(pageNum 5 → 本地第 6 页)") +Assert.eq(written["900"].fraction, 0.3, "fraction 与 page 同口径") +Assert.eq(written["900"].total_pages, 20) +Assert.eq(written["900"].updated_at, 1767323045, "Kavita 时间按 UTC 解析") +reconciled, shelf_ids = nil, { "1" } +progress["900"] = { page = 6 } +result = run("syncBooksAsync", nil) +Assert.is_nil(reconciled, "快照没变不对账") +Assert.eq(result.pulled, 0) +progress["900"] = nil +Assert.eq(run("syncBooksAsync", nil).pulled, 1, "只有漫画进度变了也让书架重绘") +shelf_ids = {} +run("syncBooksAsync", nil) +Assert.is_true(reconciled ~= nil, "本地书架空了(书库被清)照常对账") + +-- 对账后后台补简介 / 作者:缺任意一项就补,一本一请求,失败就跳过。 +reconciled = nil +books["1"], books["2"], books["3"] = { intro = "已有", authors = "甲" }, {}, {} +local meta_calls = {} +local metadata_route = routes["GET /api/Series/metadata"] +routes["GET /api/Series/metadata"] = function(opts) + meta_calls[#meta_calls + 1] = query(opts, "seriesId") + return metadata_route +end +run("syncBooksAsync", { force = true }) +Assert.is_true(reconciled ~= nil, "force 不看指纹") +Assert.is_true(reconciled.force, "force 传给对账,书架 meta 覆盖本地") +Assert.eq(table.concat(meta_calls, ","), "2,3") +Assert.eq(remembered["2"].intro, "简介") +Assert.eq(remembered["2"].authors, "甲 / 乙") +Assert.eq(remembered["2"].meta.publisher, "某出版社") +Assert.eq(remembered["2"].meta.published, 2019) +Assert.eq(remembered["2"].meta.language, "zh") +Assert.is_nil(remembered["2"].title, "不碰标题") +-- 书库把空简介存成 NULL:补过的记在单独文件里,TTL 内不再重拉。 +meta_calls, books["2"], books["3"] = {}, {}, {} +source:backfillMeta({ "2", "3" }) +Stubs.flush() +Assert.len(meta_calls, 0, "补过的不再补") +local done_file = require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua" +Assert.eq(type(require("luasettings"):open(done_file):readSetting("done")["2"]), "number", + "状态记的是检查时间戳,不是终身布尔") +-- 指纹没变(不对账)也要接着补:换源 / 断网中断过的书不能永远停在未知作者。 +meta_calls, remembered["3"] = {}, nil +books["2"], books["3"] = { intro = "已有", authors = "甲" }, {} +os.remove(done_file) +Assert.is_true(run("syncBooksAsync", nil).skipped == false, "快照没变也跑完整同步(补简介)") +Assert.eq(table.concat(meta_calls, ","), "3", "没补过的接着补") +Assert.eq(remembered["3"].authors, "甲 / 乙") +os.remove(done_file) +routes["GET /api/Series/metadata"] = function(opts) + local sid = query(opts, "seriesId") + meta_calls[#meta_calls + 1] = sid + -- 只有 2 号失败:后面的 3 号不能被一个坏请求拖住。 + if sid == "2" then return { code = 500, body = "" } end + return metadata_route +end +meta_calls, remembered["3"], books["2"] = {}, nil, {} +run("syncBooksAsync", { force = true }) +Assert.eq(table.concat(meta_calls, ","), "2,3", "单本失败跳过,后面继续补") +Assert.eq(remembered["3"].authors, "甲 / 乙") +online = false +meta_calls = {} +source:backfillMeta({ "2" }) +Stubs.flush() +Assert.len(meta_calls, 0, "离线不补") +online = true +routes["GET /api/Series/metadata"] = metadata_route + +-- 补全门禁:空串算缺数据、旧布尔当过期、TTL / force / server 分区 / 裁剪 / 失败与空响应。 +local State = function() return require("luasettings"):open(done_file) end +local function reset_state(done, server) + local st = State() + st:saveSetting("server", server or "http://kav") + st:saveSetting("done", done or {}) + st:flush() +end +local function state_done() return State():readSetting("done") or {} end +local function flush_backfill(...) + source:backfillMeta(...) + Stubs.flush() +end + +local record_route = function(opts) + meta_calls[#meta_calls + 1] = query(opts, "seriesId") + return metadata_route +end +routes["GET /api/Series/metadata"] = record_route + +os.remove(done_file) +reset_state({ ["2"] = true }) +books["2"] = { intro = "", authors = "" } +meta_calls = {} +flush_backfill({ "2" }) +Assert.eq(table.concat(meta_calls, ","), "2", "intro='' + 旧布尔 true 也要补(空串不是已补全)") +Assert.eq(type(state_done()["2"]), "number", "补完写检查时间戳") + +reset_state({ ["2"] = os.time() }) +books["2"] = {} +meta_calls = {} +flush_backfill({ "2" }) +Assert.len(meta_calls, 0, "TTL 内不重拉") + +reset_state({ ["2"] = os.time() - 8 * 86400 }) +meta_calls = {} +flush_backfill({ "2" }) +Assert.eq(table.concat(meta_calls, ","), "2", "TTL 过期重试") + +reset_state({ ["2"] = os.time() }) +meta_calls = {} +flush_backfill({ "2" }, { force = true }) +Assert.eq(table.concat(meta_calls, ","), "2", "手动刷新忽略 TTL") + +reset_state({ ["2"] = true }) +books["2"] = { intro = "有", authors = "甲" } +meta_calls = {} +flush_backfill({ "2" }) +Assert.len(meta_calls, 0, "完整行永久跳过,旧布尔也一样") + +reset_state({ ["2"] = os.time() }, "http://old") +books["2"] = {} +meta_calls = {} +flush_backfill({ "2" }) +Assert.eq(table.concat(meta_calls, ","), "2", "换服务器后旧标记作废") +Assert.eq(State():readSetting("server"), "http://kav", "记录当前服务器") + +reset_state({}) +books["2"] = {} +meta_calls = {} +local good_route = record_route +routes["GET /api/Series/metadata"] = { code = 500, body = "" } +flush_backfill({ "2" }) +Assert.is_nil(state_done()["2"], "请求失败不推进 checked_at") +routes["GET /api/Series/metadata"] = json({}) +flush_backfill({ "2" }) +Assert.eq(type(state_done()["2"]), "number", "空 DTO 也算检查过(TTL 后再看)") +routes["GET /api/Series/metadata"] = good_route + +reset_state({ ["2"] = os.time(), ["999"] = os.time() }) +meta_calls = {} +flush_backfill({ "2" }) +Assert.is_nil(state_done()["999"], "不在本轮书架的 series 从状态里裁掉") + +-- 快照没变时书架 id 里混着卷行(seriesId:chapterId):不能拿它请求 series metadata(Kavita 判 400)。 +reset_state({}) +books["2"], books["2:2001"] = {}, { title = "第二卷" } +meta_calls = {} +flush_backfill({ "2", "2:2001" }) +Assert.eq(table.concat(meta_calls, ","), "2", "卷行 id 不补 series 元数据") +books["2:2001"] = nil + +reset_state({}) +books["2"] = {} +routes["GET /api/Series/metadata"] = json({ summary = " ", writers = {} }) +flush_backfill({ "2" }) +Assert.is_nil(remembered["2"].intro, "空白 summary 归一成 nil,不写空串") +Assert.is_nil(remembered["2"].authors, "空 writers 归一成 nil") +routes["GET /api/Series/metadata"] = good_route + +-- 60 秒预算:到点停止,已处理的记 checked_at,下一轮接着补。 +reset_state({}) +books["31"], books["32"], books["33"] = {}, {}, {} +meta_calls = {} +local real_time, fake_now = os.time, os.time() +os.time = function() return fake_now end +routes["GET /api/Series/metadata"] = function(opts) + meta_calls[#meta_calls + 1] = query(opts, "seriesId") + fake_now = fake_now + 61 + return metadata_route +end +flush_backfill({ "31", "32", "33" }, { force = true }) +os.time = real_time +routes["GET /api/Series/metadata"] = good_route +Assert.eq(table.concat(meta_calls, ","), "31", "预算到点停止") +Assert.eq(type(state_done()["31"]), "number", "已处理的记时间戳") +Assert.is_nil(state_done()["32"], "没处理的不记,下一轮续跑") +books["31"], books["32"], books["33"] = nil, nil, nil + +-- 容器补全后,读过的卷行在同步里自动继承作者 / 简介(不用展示层兜底)。 +local saved_all = routes["POST /api/Series/all-v2"] +routes["POST /api/Series/all-v2"] = function(opts) + local body = JSON.decode(opts.body) + if body.Statements[1].Value == "2" then + return json({ { id = 71, name = "漫画七", libraryName = "漫画", format = 1, pages = 10, pagesRead = 5, + latestReadDate = "2026-01-02T03:04:05.123" } }) + end + return json({}) +end +tocs["71"] = { { chapterId = 7101, title = "第1话", pages = 10 } } +progress["71:7101"] = { page = 5, fraction = 0.5 } +books["71"] = { title = "漫画七", authors = "作者甲", intro = "整部简介" } +books["71:7101"] = { title = "漫画七 · 第1话" } +shelf_ids = {} +run("syncBooksAsync", { force = true }) +Assert.eq(remembered["71:7101"].authors, "作者甲", "卷行继承容器作者") +Assert.eq(remembered["71:7101"].intro, "整部简介", "卷行继承容器简介") + +-- 脏卷行:本地改过的标题保留,空的作者 / 简介从容器补上(不走 upsertRemote 覆盖)。 +books["71:7101"] = { title = "本地改名", sync_status = 0 } +remembered["71:7101"] = nil +run("syncBooksAsync", { force = true }) +Assert.eq(books["71:7101"].authors, "作者甲", "脏卷行只补空作者") +Assert.eq(books["71:7101"].title, "本地改名", "本地标题保留") +Assert.is_nil(remembered["71:7101"], "脏行不走远端整行覆盖") + +routes["POST /api/Series/all-v2"] = saved_all +books["71"], books["71:7101"] = nil, nil +tocs["71"], progress["71:7101"] = nil, nil + +books["1"], books["2"], books["3"] = nil, nil, nil +cfg.libraries = { ["1"] = true } + +local path = run("openBookAsync", { source_id = "kavita", stable_id = "10", book = { title = "长夜" } }, nil) +Assert.eq(path, WORK .. "/10/1000.epub") +Assert.eq(touched[1].stable_id, "10") +Assert.eq(tocs["10"][1].title, "Long Night", "卷名是纯数字、标题是哨兵时退到文件名") +Assert.eq(tocs["10"][1].libraryId, 1) +Assert.eq(remembered["10"].authors, "甲 / 乙") +Assert.eq(remembered["10"].intro, "简介") +Assert.eq(calls[#calls].headers["x-api-key"], "k", "下载带鉴权头") + +-- 已下载:直接开,不联网也不重新登记。 +online = false +local before = #calls +Assert.eq(run("openBookAsync", { source_id = "kavita", stable_id = "10" }, nil), path) +Assert.eq(#calls, before) +online = true + +-- 下载失败:非 2xx 删文件报状态码;2xx 但文件头不对(反代错误页)删文件报校验失败。 +download.code, download.body = 500, "oops" +routes["GET /api/Series/11"] = json({ id = 11, name = "坏书", libraryId = 1 }) +local saved = routes["GET /api/Series/volumes"] +routes["GET /api/Series/volumes"] = json({ { id = 110, chapters = { { id = 1100, titleName = "坏", format = 3, pages = 1 } } } }) +local failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "11" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "500") +Assert.is_nil(io.open(WORK .. "/11/1100.epub")) +download.code = 200 +tocs["11"] = nil +failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "11" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "校验失败") +Assert.is_nil(io.open(WORK .. "/11/1100.epub")) +routes["GET /api/Series/volumes"] = saved +download.body = "PK\3\4epub" + +-- 图片目录格式没有可下载的单文件。 +failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "40" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "图片目录") + +-- 离线:没缓存目录就当场失败;有过期目录照用(这里卷已下载,直接开)。 +online = false +failed, ferr = run("openBookAsync", { source_id = "kavita", stable_id = "50" }, nil) +Assert.is_nil(failed) +Assert.matches(ferr, "网络不可用") +online = true + +-- 多卷:选卷列表标已读,选中后下到隐藏卷行。 +local multi = { source_id = "kavita", stable_id = "20", book = { stable_id = "20", title = "合集", authors = "丙" } } +local opened, oerr +source:openBookAsync(multi, nil, function(p, e) opened, oerr = p, e end) +Stubs.flush() +local list = Themed.last("list") +Assert.len(list.items, 2) +Assert.eq(list.items[1].mandatory, "已读") +Assert.is_nil(list.items[2].mandatory) +Themed.choose(list, 2) +Stubs.flush() +Assert.eq(opened, WORK .. "/20:2002/2002.epub") +Assert.eq(remembered["20:2002"].title, "合集 · 第二卷") +Assert.eq(remembered["20:2002"].series, "合集") +Assert.eq(remembered["20:2002"].authors, "丙", "卷行继承容器作者,最近阅读里不再是未知作者") +Assert.is_nil(remembered["20:2002"].deleted, "卷行不上书架") + +-- 多卷 series 的阅读统计都记在卷行上:容器详情用 statsIdentities 把各卷并进来。 +local ids = source:statsIdentities({ source_id = "kavita", stable_id = "20" }) +Assert.eq(table.concat(ids or {}, ","), "20:2001,20:2002") +Assert.is_nil(source:statsIdentities({ source_id = "kavita", stable_id = "20:2002" }), + "卷行只看自己") +Assert.is_nil(source:statsIdentities({ source_id = "kavita", stable_id = "10" }), + "单卷 series 直接记在 series 行") + +-- 容器行的作者是 fetchToc 在这次开书里才写回的,identity.book 是开书那一刻的旧快照: +-- 选卷要用重读后的容器行,否则新 series 第一次打开写下的卷行又是「未知作者」。 +books["21"] = { stable_id = "21", title = "合集21", authors = "丁" } +routes["GET /api/Series/21"] = json({ id = 21, name = "合集21", libraryId = 2 }) +local volumes_route = routes["GET /api/Series/volumes"] +routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") == "21" then + return json({ + { id = 210, name = "1", chapters = { { id = 2101, titleName = "上", format = 3, pages = 5 } } }, + { id = 211, name = "2", chapters = { { id = 2102, titleName = "下", format = 3, pages = 5 } } }, + }) + end + return volumes_route(opts) +end +source:openBookAsync( + { source_id = "kavita", stable_id = "21", book = { stable_id = "21", title = "合集21" } }, + nil, function() end) +Stubs.flush() +Themed.choose(Themed.last("list"), 1) +Stubs.flush() +Assert.eq(remembered["21:2101"].authors, "丁", "卷行取重读后的容器行,不用开书时的旧快照") +routes["GET /api/Series/volumes"] = volumes_route +books["21"] = nil + +-- 关掉选卷列表 = 取消。 +source:openBookAsync(multi, nil, function(p, e) opened, oerr = p, e end) +Stubs.flush() +list = Themed.last("list") +Assert.eq(list.items[2].mandatory, "已下载") +list:close() +Stubs.flush() +Assert.matches(oerr, "已取消") + +-- 点开系列 = 立即拉一次最新进度:目录缓存 6 小时内不更新,选卷列表要显示服务器上的已读状态。 +do + tocs["8701"] = { + { chapterId = 87010, title = "第1卷", pages = 100, pagesRead = 0, format = 1 }, + { chapterId = 87011, title = "第2卷", pages = 100, pagesRead = 0, format = 1 }, + } + books["8701"] = { stable_id = "8701", title = "系列87", authors = "作者" } + routes["GET /api/Series/8701"] = json({ id = 8701, name = "系列87", libraryId = 2, format = 1 }) + local base_volumes = routes["GET /api/Series/volumes"] + routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") ~= "8701" then return base_volumes(opts) end + return json({ + { id = 870, chapters = { { id = 87010, titleName = "第1卷", format = 1, pages = 100, pagesRead = 100 } } }, + { id = 871, chapters = { { id = 87011, titleName = "第2卷", format = 1, pages = 100, pagesRead = 30 } } }, + }) + end + source:openBookAsync({ source_id = "kavita", stable_id = "8701", book = books["8701"] }, nil, + function() end) + Stubs.flush() + Assert.eq(tocs["8701"][1].pagesRead, 100, "打开系列就拉到最新进度") + Assert.eq(tocs["8701"][2].pagesRead, 30) + local live = Themed.last("list") + Assert.eq(live.items[1].mandatory, "已读", "选卷列表按服务器最新进度显示已读") + Assert.eq(live.items[2].mandatory, "在读") + live:close() + Stubs.flush() + routes["GET /api/Series/volumes"] = base_volumes + books["8701"] = nil +end + +-- 封面:系列行取系列封面,卷行取这一卷自己的封面;chapter-cover 是扫描版第一页,不用。 +local cover = source:coverRequest({ stable_id = "10" }) +Assert.eq(cover.url, "http://kav/api/Image/series-cover?seriesId=10") +Assert.eq(cover.headers["x-api-key"], "k") +Assert.eq(cover.authoritative, true, "源封面压过本地抽页 / 旧封面缓存") +-- 目录里能查到这一卷 → volume-cover(「当前阅读」要显示正在读的那一卷)。 +tocs["70"] = { { chapterId = 7001, volumeId = 701, title = "第一卷", pages = 10 } } +local volume_cover = source:coverRequest({ stable_id = "70:7001" }) +Assert.eq(volume_cover.url, "http://kav/api/Image/volume-cover?volumeId=701", "卷行用卷封面") +Assert.eq(volume_cover.authoritative, true) +-- 目录里查不到这一卷(没拉过目录)→ 退回系列封面。 +Assert.eq(source:coverRequest({ stable_id = "71:7101" }).url, + "http://kav/api/Image/series-cover?seriesId=71", "查不到卷退回系列封面") +tocs["70"] = nil +-- 卷身份折叠:图书馆最近阅读按系列归并,点开再选卷。 +Assert.eq(source:volumeParent("20:2002"), "20") +Assert.is_nil(source:volumeParent("20")) + +-- 拉进度:远端 spine + 锚点 → xpointer;没读过算空。 +local volume = { source_id = "kavita", stable_id = "20:2002" } +local remote = { pageNum = 3, bookScrollId = "//body/div[1]/p[5]" } +routes["GET /api/Reader/get-progress"] = function() return json(remote) end +local pos, _err, meta = run("getProgressAsync", volume) +Assert.eq(pos.locator, "/body/DocFragment[4]/body/div/p[5]") +Assert.eq(pos.fraction, 0.3) +Assert.is_nil(pos.page, "epub 不给页码:Kavita 的页是 spine,不是渲染页") +Assert.is_true(meta and meta.page_level == true, "页级源必须声明 page_level:core 才不按百分比判") +Assert.is_nil(_err) +-- 同一 spine:锚点与本机上次同步的位置不同(网页端在同一条里往后读了几页)→ 用远端坐标, +-- 不能返回本地行——否则 core 的 synced 基线永远看不到「云端动过」。 +progress["20:2002"] = { + locator = "/body/DocFragment[4]/body/p[9]/text().3", + fraction = 0.34, + synced = { locator = "/body/DocFragment[4]/body/p[3]/text().0" }, +} +local moved = run("getProgressAsync", volume) +Assert.eq(moved.locator, "/body/DocFragment[4]/body/div/p[5]", "同 spine 锚点变了就要跟远端") +Assert.eq(moved.fraction, 0.3) +-- 同一 spine 且锚点就是上次同步的位置 → 交回本地行(粒度噪声不当冲突,也不跳) +progress["20:2002"].synced = { locator = "/body/DocFragment[4]/body/div[1]/p[5]" } +Assert.eq(run("getProgressAsync", volume), progress["20:2002"]) +-- 同一 spine 但远端只有 spine 粒度(没带锚点 / 锚点解不出)→ 交回本地行,不把人拽回节首。 +routes["GET /api/Reader/get-progress"] = function() return json({ pageNum = 3 }) end +Assert.eq(run("getProgressAsync", volume), progress["20:2002"]) +-- 旧行没有基线(synced 为空)→ 保守交回本地行,不拿不可比的粒度去判 +routes["GET /api/Reader/get-progress"] = function() return json(remote) end +progress["20:2002"].synced = nil +Assert.eq(run("getProgressAsync", volume), progress["20:2002"]) +remote = { pageNum = 0 } +local empty, _e, meta = run("getProgressAsync", volume) +Assert.is_nil(empty) +Assert.is_true(meta.empty) +routes["GET /api/Reader/get-progress"] = { code = 400, body = "" } +_e, _e, meta = run("getProgressAsync", volume) +Assert.is_true(meta.empty) + +-- 推进度:spine + 章内路径;读完发 pages。 +local sent +routes["POST /api/Reader/progress"] = function(opts) + sent = JSON.decode(opts.body) + return { code = 200, body = "" } +end +Assert.is_true(run("putProgressAsync", volume, { fraction = 0.25, locator = "/body/DocFragment[3]/body/div/p[2]/text().0" })) +Assert.eq(sent.pageNum, 2) +Assert.eq(sent.bookScrollId, "//body/div[1]/p[2]") +Assert.eq(sent.chapterId, 2002) +Assert.eq(sent.volumeId, 201) +Assert.eq(sent.libraryId, 2) +Assert.eq(sent.seriesId, 20) +run("putProgressAsync", volume, { fraction = 1, locator = "/body/DocFragment[10]/body/p" }) +Assert.eq(sent.pageNum, 10) + +-- PDF:按页换算;series 行靠登记的文件名认卷。 +local pdf = { source_id = "kavita", stable_id = "30" } +Assert.eq(run("openBookAsync", pdf, nil), nil, "文件头不是 %PDF") +download.body = "%PDF-1.7" +Assert.eq(run("openBookAsync", pdf, nil), WORK .. "/30/3000.pdf") +run("putProgressAsync", pdf, { fraction = 0.2, page = 11, total_pages = 50 }) +Assert.eq(sent.pageNum, 10) +Assert.is_nil(sent.bookScrollId) +routes["GET /api/Reader/get-progress"] = function() return json({ pageNum = 20 }) end +pos = run("getProgressAsync", pdf) +Assert.eq(pos.page, 21) +Assert.eq(pos.total_pages, 50) +progress["30"] = { page = 21, fraction = 0.41 } +Assert.eq(run("getProgressAsync", pdf), progress["30"]) + +-- 离线且目录过期:卷信息退回旧目录,进度照样能推(推送本身由队列等网)。 +toc_fresh, online = false, false +stale["20"] = JSON.encode(tocs["20"]) +Assert.is_true(run("putProgressAsync", volume, { fraction = 0.5, locator = "/body/DocFragment[6]/body/p" })) +Assert.eq(sent.pageNum, 5) +toc_fresh, online = true, true + +-- 推送(spec §8):先按章对账一次,再逐条新建 / 更新;用 do 收住局部变量(Lua 单函数 200 个上限)。 +do + -- 注解:推送前先按章对账一次(一批一次 GET),create 必须拿到 id,写失败整批留脏。 + -- 远端仓库 / 当前用户 / 服务端落库行为全部打桩,断言只看向外的请求与回填。 + local epub = { + ["META-INF/container.xml"] = [[]], + ["content.opf"] = [[]], + ["a.xhtml"] = [[

春眠不觉晓

处处闻啼鸟

]], + } + package.loaded["ffi/archiver"] = { Reader = { new = function() + return { + open = function(_self, file) return file == WORK .. "/20:2002/2002.epub" end, + iterate = function() return function() end end, + extractToMemory = function(_self, name) return epub[name] end, + close = function() end, + } + end } } + -- 坐标守卫 / 远端赢只留日志:收起来断言,不弹窗也不干扰别的断言。 + local push_warnings = {} + do + local log = require("utils.log") + log.warn = function(...) push_warnings[#push_warnings + 1] = table.concat({ ... }, " ") end + end + local function warned(text) + for _idx, line in ipairs(push_warnings) do + if line:find(text, 1, true) then return true end + end + return false + end + + -- 远端注解仓库:GET all 读它,create / update 往里写,bulk-delete 从它删;属主固定成当前用户。 + local USER, next_id = 5, 101 + local remote, created, updated, deleted = {}, {}, {}, {} + local fail_list, fail_create, fail_update, blank_create, drop_create, create_fail_at + local fail_delete, reject_delete, list_calls = false, false, 0 + routes["GET /api/Users/me"] = json({ id = USER }) + routes["GET /api/Annotation/all"] = function(opts) + list_calls = list_calls + 1 + if fail_list then return { code = 500, body = "" } end + local chapter = tonumber(query(opts, "chapterId")) or 0 + local out = {} + for _idx, item in ipairs(remote[chapter] or {}) do out[#out + 1] = item end + return json(out) + end + --- 服务端落库:create 分配 id;update 只覆盖可写四字段(坐标改不了,与 Kavita 一致)。 + local function persist(body, is_update) + local chapter = tonumber(body.chapterId) or 0 + remote[chapter] = remote[chapter] or {} + local item + if is_update then + for _idx, row in ipairs(remote[chapter]) do + if tonumber(row.id) == tonumber(body.id) then item = row end + end + else + body.id, next_id = next_id, next_id + 1 + body.ownerUserId = USER + item = body + remote[chapter][#remote[chapter] + 1] = item + end + if item then + item.comment, item.commentHtml = body.comment, body.commentHtml + item.selectedSlotIndex, item.containsSpoiler = body.selectedSlotIndex, body.containsSpoiler + end + return item + end + routes["POST /api/Annotation/create"] = function(opts) + local body = JSON.decode(opts.body) + created[#created + 1] = body + if fail_create or (create_fail_at and #created >= create_fail_at) then return { code = 500, body = "" } end + local item + if not drop_create then item = persist(body, false) end + -- blank_create:反代吞掉 DTO(2xx 空体),但服务端确实建成了。 + if blank_create or not item then return { code = 200, body = "" } end + return json({ id = item.id }) + end + routes["POST /api/Annotation/update"] = function(opts) + local body = JSON.decode(opts.body) + updated[#updated + 1] = body + if fail_update then return { code = 500, body = "" } end + persist(body, true) + return json({ id = body.id }) + end + -- 删除:body 是裸 id 数组;不存在的 id 静默忽略(与 Kavita 一致)。 + -- reject_delete 用来模拟「不是你的 / 服务端拒绝」的 400 分支。 + routes["POST /api/Annotation/bulk-delete"] = function(opts) + local ids = JSON.decode(opts.body) + deleted[#deleted + 1] = ids + if fail_delete then return { code = 500, body = "" } end + if reject_delete then return { code = 400, body = "" } end + local wanted = {} + for _idx, id in ipairs(ids) do wanted[tonumber(id)] = true end + for _chapter, rows in pairs(remote) do + for i = #rows, 1, -1 do + if wanted[tonumber(rows[i].id)] then table.remove(rows, i) end + end + end + return { code = 200, body = "" } + end + --- 每个场景从干净状态开始:远端仓库、写请求计数、故障开关。 + local function resetPush() + remote, next_id, created, updated, deleted = {}, 101, {}, {}, {} + fail_list, fail_create, fail_update = false, false, false + blank_create, drop_create, create_fail_at = false, false, nil + fail_delete, reject_delete, list_calls = false, false, 0 + push_warnings = {} + end + + -- 非 epub:零请求,pushed=0(核心据此不谎报「同步过」)。 + resetPush() + local calls_before = #calls + local ok_epub, _err_epub, data_epub = run("pushNotesAsync", pdf, + { { drawer = "lighten", text = "图", pos0 = "x" } }) + Assert.is_true(ok_epub) + Assert.eq(data_epub.pushed, 0) + Assert.eq(#calls, calls_before, "非 epub 一个请求都不发") + + -- 对账 GET 失败:宁可这轮不推,也不盲建重复;一个写请求都不发。 + resetPush() + fail_list = true + local ok_net, err_net = run("pushNotesAsync", volume, + { { drawer = "lighten", text = "春眠\n不觉晓", note = "好诗", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } }) + Assert.is_nil(ok_net) + Assert.matches(err_net, "500") + Assert.len(created, 0) + Assert.len(updated, 0) + + -- 新建:请求体按 §5.1 的 Web 兼容形态;成功判据是 DTO 里有 id,id 原地回填给核心落库。 + resetPush() + local anns = { + { drawer = "lighten", text = "春眠\n不觉晓", note = "好诗", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" }, + { drawer = "underscore", text = "处处闻啼鸟", pos0 = "/body/DocFragment[1]/body/p[2]/text().0" }, + } + local ok_new, err_new, data_new = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_new) + Assert.is_nil(err_new) + Assert.eq(data_new.pushed, 2) + Assert.eq(data_new.adopted, 0) + Assert.len(created, 2) + Assert.len(updated, 0) + Assert.eq(created[1].xPath, "//body/p[1]") + Assert.eq(created[1].endingXPath, "//body/p[1]") + Assert.eq(created[1].pageNumber, 0) + Assert.eq(created[1].selectedText, "春眠\n不觉晓") + Assert.eq(created[1].highlightCount, 6, "按 UTF-16 码元计") + Assert.eq(created[1].chapterId, 2002) + Assert.eq(created[1].volumeId, 201) + Assert.eq(created[1].libraryId, 2) + Assert.eq(created[1].seriesId, 20) + Assert.eq(JSON.decode(created[1].comment).ops[1].insert, "好诗\n", "备注写 Quill Delta,网页端才打得开") + Assert.eq(created[1].commentHtml, "

好诗

") + Assert.eq(created[2].comment, "{}", "空备注写空 Delta(网页端 JSON.parse 不崩)") + Assert.eq(created[2].commentHtml, "") + Assert.eq(anns[1].kavita_id, 101) + Assert.eq(anns[1].kavita_note, "好诗") + Assert.eq(anns[1].kavita_xpath, "//body/p[1]", "远端坐标回填给诊断与坐标守卫") + Assert.eq(anns[2].kavita_id, 102) + Assert.eq(anns[2].kavita_note, "", "空备注的基线是空串,不是 nil(否则每轮都判改过)") + + -- 再推一轮:没有改动 → 零请求,pushed=0。 + created, updated = {}, {} + local ok_same, _err_same, data_same = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_same) + Assert.eq(data_same.pushed, 0) + Assert.len(created, 0, "推过的不重建") + Assert.len(updated, 0) + + -- 改备注且远端没变 → 一次 update(整条替换);未改动的槽位 / 剧透回传远端原值。 + anns[1].kavita_slot, anns[1].kavita_spoiler = 3, true + anns[1].note = "改了" + local ok_up, _err_up, data_up = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_up) + Assert.eq(data_up.pushed, 1) + Assert.eq(data_up.adopted, 0, "update 是写入,只算 pushed;adopted 只数「认到 id 但没写」") + Assert.eq(data_up.conflicts, 0) + Assert.len(updated, 1) + Assert.eq(updated[1].id, 101) + Assert.eq(updated[1].xPath, "//body/p[1]", "update 也带坐标(服务端忽略,形状要对)") + Assert.eq(JSON.decode(updated[1].comment).ops[1].insert, "改了\n") + Assert.eq(updated[1].selectedSlotIndex, 3, "颜色不回传就会被服务端清成默认") + Assert.eq(updated[1].containsSpoiler, true) + Assert.eq(anns[1].kavita_note, "改了") + + -- 坐标守卫:现算锚点与远端记录不一致 → 跳过 update 并留日志(服务端改不了坐标,硬发会写到旧位置)。 + anns[1].note = "坐标漂了" + anns[1].kavita_xpath = "//body/p[9]" + local ok_guard, _err_guard, data_guard = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_guard) + Assert.eq(data_guard.pushed, 0) + Assert.len(updated, 1, "坐标不一致不 update") + Assert.is_true(warned("drifted"), "跳过的原因要能在日志里定位") + Assert.eq(anns[1].kavita_note, "改了", "没写成功,基线不能动") + anns[1].kavita_xpath = nil + + -- 双方都改过:远端赢,零写请求;本地文本存 kavita_local_note 备查,基线不动(等下轮 pull 采纳远端)。 + anns[1].note, anns[1].kavita_note = "设备改的", "上次同步" + remote[2002][1].comment, remote[2002][1].commentHtml = nil, "

网页改的

" + local ok_lose, _err_lose, data_lose = run("pushNotesAsync", volume, anns) + Assert.is_true(ok_lose) + Assert.eq(data_lose.pushed, 0) + Assert.eq(data_lose.conflicts, 1) + Assert.len(updated, 1) + Assert.eq(anns[1].kavita_local_note, "设备改的") + Assert.eq(anns[1].kavita_note, "上次同步") + Assert.is_true(warned("remote"), "远端赢要留日志") + + -- 对账列表按 ownerUserId 收窄:账号开了「查看他人注解」后混进来的条目不能被认领 / 改写。 + resetPush() + remote[2002] = { { id = 5, ownerUserId = 99, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠\n不觉晓", commentHtml = "

别人

" } } + local mine = { drawer = "lighten", text = "春眠\n不觉晓", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + Assert.is_true(run("pushNotesAsync", volume, { mine })) + Assert.eq(mine.kavita_id, 101, "别人的同键注解不认领") + Assert.len(created, 1) + + -- 首次认领:本地没 id、远端同键已有 → 采纳(同键多条取 id 最小),不新建。 + resetPush() + remote[2002] = { + { id = 43, ownerUserId = USER, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠\n不觉晓", commentHtml = "

重复

" }, + { id = 37, ownerUserId = USER, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠 不觉晓", commentHtml = "

网页写的

" }, + } + local claimed = { drawer = "lighten", text = "春眠\n不觉晓", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local ok_claim, _err_claim, data_claim = run("pushNotesAsync", volume, { claimed }) + Assert.is_true(ok_claim) + Assert.eq(claimed.kavita_id, 37, "同键多条取 id 最小") + Assert.is_nil(claimed.kavita_note, "远端备注不当基线:本地 note 还是空的,等 pull 采纳") + Assert.eq(data_claim.pushed, 0) + Assert.eq(data_claim.adopted, 1, "只认领 id、没写远端 → adopted") + Assert.len(created, 0) + Assert.len(updated, 0, "首次认领不覆盖远端非空备注") + + -- 认领过的那条再推(本地 note 仍空、pull 还没跑)→ 零写请求。 + -- 基线若被写成远端文本,这里就会被判成「用户清空了备注」,一次 update 抹掉网页作者的内容。 + local ok_again, _err_again, data_again = run("pushNotesAsync", volume, { claimed }) + Assert.is_true(ok_again) + Assert.eq(data_again.pushed, 0) + Assert.len(updated, 0, "认领后不能反手把远端的备注覆盖成空") + + -- 认领后、pull 之前用户补了备注 → 这是真实编辑,直接 update(没有基线不等于冲突)。 + local later = { drawer = "lighten", text = "春眠\n不觉晓", note = "补的备注", kavita_id = 37, + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + Assert.is_true(run("pushNotesAsync", volume, { later })) + Assert.eq(updated[#updated].id, 37) + Assert.eq(JSON.decode(updated[#updated].comment).ops[1].insert, "补的备注\n") + Assert.eq(later.kavita_note, "补的备注") + + -- 首次认领时本地备注非空且不同 → 认到 id 后 update 那一条(设备侧确实改了备注)。 + local named = { drawer = "lighten", text = "春眠\n不觉晓", note = "我的备注", + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + Assert.is_true(run("pushNotesAsync", volume, { named })) + Assert.eq(named.kavita_id, 37) + Assert.eq(updated[#updated].id, 37, "首次认领不新建") + Assert.eq(JSON.decode(updated[#updated].comment).ops[1].insert, "我的备注\n") + Assert.eq(named.kavita_note, "我的备注") + + -- 有 id、远端已无该 id(网页端删了)→ 不重建、不复活(交给 pull 的 dropped 通道)。 + local ghost = { drawer = "lighten", text = "春眠\n不觉晓", note = "改过", kavita_id = 99, kavita_note = "旧", + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local writes_before = #created + #updated + Assert.is_true(run("pushNotesAsync", volume, { ghost })) + Assert.eq(#created + #updated, writes_before, "远端删了不重建") + Assert.eq(ghost.kavita_id, 99) + Assert.is_nil(ghost.kavita_local_note) + + -- 本批墓碑的 id 先剔出对账列表:删了又原地划一条同键的,不能认领到「即将删除」的那条。 + -- 先写后删:新建成功后一次 bulk-delete 删掉旧 id,远端最终只剩新建的那条。 + remote[2002] = { { id = 37, ownerUserId = USER, chapterId = 2002, xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠\n不觉晓", commentHtml = "

旧

" } } + local tomb = { kavita_id = 37, kavita_deleted = true, datetime = "2026-10-01" } + local redo = { drawer = "lighten", text = "春眠\n不觉晓", note = "新的", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local redo_batch = { tomb, redo } + Assert.is_true(run("pushNotesAsync", volume, redo_batch)) + Assert.is_true(redo.kavita_id ~= 37, "墓碑那条不在认领范围内") + Assert.eq(redo.kavita_id, 101, "同键的划线重建一条") + Assert.eq(#deleted, 1) + Assert.eq(deleted[1][1], 37, "body 是裸 id 数组") + Assert.eq(#redo_batch, 1, "删除成功后墓碑从 payload 出列") + Assert.eq(redo_batch[1], redo) + Assert.eq(#remote[2002], 1, "删一条 + 原地划一条同键:远端只剩新建的那条") + Assert.eq(remote[2002][1].id, 101) + + -- 删除高亮:墓碑单独一批也能推(没有 create/update),200 即出列、远端少一条; + -- 墓碑出列后再推一轮是零请求。 + resetPush() + remote[2002] = { { id = 51, ownerUserId = USER, chapterId = 2002, selectedText = "旧划线", + commentHtml = "", comment = "" } } + local only_tomb = { { kavita_id = 51, kavita_deleted = true, datetime = "2026-10-01" } } + local ok_del, _err_del, data_del = run("pushNotesAsync", volume, only_tomb) + Assert.is_true(ok_del) + Assert.eq(data_del.pushed, 0) + Assert.eq(data_del.deleted, 1, "deleted 如实计数") + Assert.eq(deleted[1][1], 51) + Assert.len(only_tomb, 0, "墓碑出列") + Assert.len(remote[2002], 0, "远端确实少一条") + local quiet_before = #calls + local ok_quiet, _err_quiet, data_quiet = run("pushNotesAsync", volume, only_tomb) + Assert.is_true(ok_quiet) + Assert.eq(data_quiet.deleted, 0) + Assert.eq(#calls, quiet_before, "墓碑已出列,再推零请求") + + -- 远端早就没有这个 id(别处删过 / 从没推成功):bulk-delete 回 200 一样出列,不报错。 + resetPush() + local ghost_tomb = { { kavita_id = 999, kavita_deleted = true, datetime = "d" } } + local ok_idem, _err_idem, data_idem = run("pushNotesAsync", volume, ghost_tomb) + Assert.is_true(ok_idem) + Assert.eq(data_idem.deleted, 1) + Assert.len(ghost_tomb, 0, "远端已删的墓碑幂等出列") + + -- 删除失败(非 400):整批 cb(nil),墓碑留在 payload 里;下轮重试成功才出列。 + resetPush() + remote[2002] = { { id = 52, ownerUserId = USER, chapterId = 2002, selectedText = "旧", + commentHtml = "", comment = "" } } + local retry_tomb = { { kavita_id = 52, kavita_deleted = true, datetime = "d" } } + fail_delete = true + local ok_retry, err_retry = run("pushNotesAsync", volume, retry_tomb) + Assert.is_nil(ok_retry) + Assert.matches(err_retry, "500") + Assert.len(retry_tomb, 1, "失败时墓碑保留,快照留脏") + Assert.len(remote[2002], 1) + fail_delete = false + local ok_again_del, _err_again_del, data_again_del = run("pushNotesAsync", volume, retry_tomb) + Assert.is_true(ok_again_del) + Assert.eq(data_again_del.deleted, 1, "重试成功") + Assert.len(retry_tomb, 0) + Assert.len(remote[2002], 0) + + -- 写失败时一个删除都不发:先写后删,写入不留半成品删除。 + resetPush() + remote[2002] = { { id = 53, ownerUserId = USER, chapterId = 2002, selectedText = "旧", + commentHtml = "", comment = "" } } + fail_create = true + local write_fail_batch = { + { kavita_id = 53, kavita_deleted = true, datetime = "d" }, + { drawer = "lighten", text = "春眠\n不觉晓", note = "a", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" }, + } + local ok_wf, err_wf = run("pushNotesAsync", volume, write_fail_batch) + Assert.is_nil(ok_wf) + Assert.matches(err_wf, "500") + Assert.len(deleted, 0, "create 失败就不发删除") + Assert.len(write_fail_batch, 2, "墓碑保留") + + -- 400(服务端拒绝 / 不是你的)→ 重拉一次该章列表,仍在那里的丢弃墓碑并记日志,不无限重试。 + resetPush() + remote[2002] = { { id = 54, ownerUserId = USER, chapterId = 2002, selectedText = "删不掉", + commentHtml = "", comment = "" } } + reject_delete = true + local rejected_tomb = { { kavita_id = 54, kavita_deleted = true, datetime = "d" } } + local ok_rej, _err_rej, data_rej = run("pushNotesAsync", volume, rejected_tomb) + Assert.is_true(ok_rej, "400 按对账结果收尾,不让整批反复失败") + Assert.eq(data_rej.deleted, 0, "远端还在,不算删成功") + Assert.len(rejected_tomb, 0, "仍在列表里的墓碑丢弃,下轮不再重试") + Assert.is_true(warned("delete rejected"), "丢弃要有日志") + Assert.eq(list_calls, 2, "400 后重拉一次该章列表") + Assert.len(remote[2002], 1, "远端那条原样保留") + local after_rej = #calls + Assert.is_true(run("pushNotesAsync", volume, rejected_tomb)) + Assert.eq(#calls, after_rej, "不再有墓碑就零请求") + + -- 400 且 id 已不在列表里 → 目标态已达成,墓碑出列并计入 deleted。 + resetPush() + reject_delete = true + local gone_tomb = { { kavita_id = 55, kavita_deleted = true, datetime = "d" } } + local ok_gone, _err_gone, data_gone = run("pushNotesAsync", volume, gone_tomb) + Assert.is_true(ok_gone) + Assert.eq(data_gone.deleted, 1, "不在列表里 = 已经删掉") + Assert.len(gone_tomb, 0) + + -- create 回空体(反代吞了 DTO):§8.3 的补偿只查**同一轮**对账列表(一批一次 GET), + -- 那份列表是创建前取的、里面没有刚建的这条 → 无法确认,该条失败留脏,不为它再补发一次 GET。 + resetPush() + blank_create = true + local lone = { drawer = "lighten", text = "春眠\n不觉晓", note = "n", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local ok_blank, err_blank = run("pushNotesAsync", volume, { lone }) + Assert.is_nil(ok_blank, "无 id 的 2xx 不算成功") + Assert.not_nil(err_blank) + Assert.is_nil(lone.kavita_id, "没确认到 id 就不回填") + Assert.eq(list_calls, 1, "一批只对一次账:回空体不再补发 GET") + -- 下一轮对账就能看到服务端其实落了那条:按 key 认领,不重复建。 + blank_create = false + created = {} + Assert.is_true(run("pushNotesAsync", volume, { lone })) + Assert.eq(lone.kavita_id, 101, "下轮对账按 key 认领,回填 id") + Assert.len(created, 0, "认到同键就不新建") + Assert.len(remote[2002], 1, "远端最终只有一条") + + -- 回查也找不到(服务端真没落库)→ 该条失败、整批 cb(nil) 留脏,绝不当成功。 + resetPush() + drop_create = true + local dropped_ann = { drawer = "lighten", text = "春眠\n不觉晓", note = "n", + pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local ok_drop, err_drop = run("pushNotesAsync", volume, { dropped_ann }) + Assert.is_nil(ok_drop) + Assert.not_nil(err_drop) + Assert.is_nil(dropped_ann.kavita_id) + + -- 全有或全无:一条写失败 → 整批 cb(nil);已建成的条目下轮由对账认领,不会重复。 + resetPush() + local first = { drawer = "lighten", text = "春眠\n不觉晓", note = "a", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local second = { drawer = "lighten", text = "处处闻啼鸟", note = "b", pos0 = "/body/DocFragment[1]/body/p[2]/text().0" } + create_fail_at = 2 + local ok_fail, err_fail = run("pushNotesAsync", volume, { first, second }) + Assert.is_nil(ok_fail) + Assert.matches(err_fail, "500") + Assert.eq(first.kavita_id, 101) + Assert.is_nil(second.kavita_id) + first.kavita_id = nil -- cb(nil) 后核心不落库,这条 id 就丢了 + create_fail_at = nil + created, updated = {}, {} + Assert.is_true(run("pushNotesAsync", volume, { first, second })) + Assert.eq(first.kavita_id, 101, "上轮已建成的条目由对账按 key 认领") + Assert.len(created, 1, "只补建真正缺的那条") + Assert.eq(second.kavita_id, 102) + + -- 锚点失败(找不回段落):不带空 xPath 发出去(会跟别的空锚点挤成同键),整批不发送、留脏重试。 + resetPush() + local good = { drawer = "lighten", text = "春眠\n不觉晓", note = "a", pos0 = "/body/DocFragment[1]/body/p[1]/text().0" } + local lost = { drawer = "lighten", text = "𠀀找不到", pos0 = "/body/DocFragment[3]/body/p/text().0" } + local ok_lost, err_lost = run("pushNotesAsync", volume, { good, lost }) + Assert.is_nil(ok_lost) + Assert.not_nil(err_lost) + Assert.len(created, 0, "锚点不齐就一个都不发") + Assert.len(updated, 0) + + -- 书签(没有 drawer)不推,也不算失败。 + resetPush() + local ok_mark, _err_mark, data_mark = run("pushNotesAsync", volume, + { { text = "书签", pos0 = "/body/DocFragment[1]/body/p" } }) + Assert.is_true(ok_mark) + Assert.eq(data_mark.pushed, 0) + Assert.len(created, 0) + + -- 快照:清洗保留 Kavita 全字段(白名单漏一个就静默消失),保存时按 pos0 从上一版接过 id。 + local clean = source:cleanAnnotations({ + { datetime = "d", page = 1, drawer = "lighten", text = "x", pos0 = "p", kavita_id = 71, kavita_note = "n", junk = 1, + pageNumber = 3, + kavita_comment = "{}", kavita_comment_html = "", kavita_slot = 0, kavita_spoiler = false, + kavita_modified = "m", kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[1]", + kavita_unlocated = true, kavita_local_note = "被远端覆盖的旧文本" }, + { text = "没有时间的丢掉" }, + }, 10) + Assert.len(clean, 1) + Assert.eq(clean[1].kavita_id, 71) + Assert.eq(clean[1].pageNumber, 3, "pageNumber 不是 kavita_ 前缀,但也必须过白名单(定位提示)") + Assert.eq(clean[1].kavita_note, "n") + Assert.eq(clean[1].kavita_comment, "{}") + Assert.eq(clean[1].kavita_comment_html, "") + Assert.eq(clean[1].kavita_slot, 0) + Assert.eq(clean[1].kavita_spoiler, false) + Assert.eq(clean[1].kavita_modified, "m") + Assert.eq(clean[1].kavita_xpath, "//body/p[1]") + Assert.eq(clean[1].kavita_ending_xpath, "//body/p[1]") + Assert.is_true(clean[1].kavita_unlocated) + Assert.eq(clean[1].kavita_local_note, "被远端覆盖的旧文本") + Assert.eq(clean[1].total_pages, 10) + Assert.is_nil(clean[1].junk, "白名单外的字段仍丢弃") + + -- 无 page 的两类条目必须放行:未定位(只有 xPath)、墓碑(只有 kavita_deleted)。 + -- 靠「构造期用 xPath / 墓碑标记当占位」过 Normalize.clean,清洗后把占位清空。 + local unlocated = source:cleanAnnotations({ + { datetime = "d", text = "云端条", note = "", kavita_id = 72, kavita_xpath = "//body/p[9]" }, + { datetime = "d", kavita_id = 73, kavita_deleted = true }, + { datetime = "d", text = "没有任何坐标" }, + }, 10) + Assert.len(unlocated, 2, "无时间 / 无坐标的条目仍然丢掉") + Assert.eq(unlocated[1].kavita_id, 72) + Assert.eq(unlocated[1].kavita_xpath, "//body/p[9]", "未定位条目保留全部 kavita_* 字段") + Assert.is_nil(unlocated[1].page, "占位只在构造期用,清洗后清空") + Assert.eq(unlocated[1].total_pages, 10) + Assert.eq(unlocated[2].kavita_id, 73) + Assert.is_true(unlocated[2].kavita_deleted) + Assert.is_nil(unlocated[2].page) + + -- 保存时:pos0 对得上的接过 id;没有 pos0 的未定位条目原样搬进新快照, + -- 否则一次普通保存就把「数据在、画不出」的云端条目洗掉。 + local previous = { + { pos0 = "p", kavita_id = 71, kavita_note = "n" }, + { pos0 = "gone", kavita_id = 9, datetime = "d-gone" }, + { datetime = "d", text = "云端条", kavita_id = 72, kavita_note = "", kavita_xpath = "//body/p[9]" }, + } + local current = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "新" }, { pos0 = "q" } }) + Assert.eq(current[1].kavita_id, 71) + Assert.eq(current[1].kavita_note, "n", "备注差异留给推送时比对") + Assert.is_nil(current[2].kavita_id) + Assert.eq(#current, 3, "未定位条目搬进新快照") + Assert.eq(current[3].kavita_id, 72) + Assert.eq(current[3].kavita_xpath, "//body/p[9]") + Assert.is_nil(current[3].pos0) + local deduped = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "新" }, { kavita_id = 72, text = "已经在快照里" } }) + Assert.eq(#deduped, 2, "快照里已有的 id 不重复搬") + + -- 本地删除(spec §9.1):被删条目按 pos0 在上一版里找到、且那条有 id → 追加墓碑。 + -- 墓碑不带 pos/page(画不出来),但带 id 与基线备注;阅读器与 doc_settings 都不画它。 + local with_id = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "新" } }, { pos0 = "gone", text = "删了" }) + Assert.eq(#with_id, 3, "剩余条目 + 未定位条目 + 墓碑") + local tomb = with_id[3] + Assert.is_true(tomb.kavita_deleted) + Assert.eq(tomb.kavita_id, 9, "墓碑按 pos0 取上一版那条的 id") + Assert.is_nil(tomb.pos0, "墓碑没有坐标") + Assert.eq(tomb.datetime, "d-gone") + + -- 被删的是划线转笔记 / 只删备注:条目还在,删除事件判据不成立(changed 传 nil)→ 无墓碑。 + local note_change = source:prepareLocalAnnotations(previous, + { { pos0 = "p", note = "改成笔记" }, { pos0 = "gone", note = "还在" } }) + Assert.eq(#note_change, 3, "条目仍在快照里,不产生墓碑") + for _idx, item in ipairs(note_change) do Assert.is_nil(item.kavita_deleted) end + + -- 没 id 的本地划线被删:本来就没推到远端 → 不产生墓碑;pos0 对不上 / 没 pos0 同理(只漏删不误删)。 + local no_id_previous = { { pos0 = "local", text = "纯本地", datetime = "d" } } + local no_id = source:prepareLocalAnnotations(no_id_previous, {}, + { pos0 = "local", text = "纯本地" }) + Assert.len(no_id, 0, "无 id 的删除不生成墓碑") + local no_pos = source:prepareLocalAnnotations(previous, {}, { text = "没有坐标" }) + Assert.len(no_pos, 1, "没有 pos0:只剩未定位条目,不生成墓碑") + local miss = source:prepareLocalAnnotations(previous, {}, { pos0 = "other", text = "对不上" }) + Assert.len(miss, 1, "pos0 在上一版找不到就不生成墓碑") + + -- 后续保存从上一版重新接上墓碑,直到推送成功把它清掉;已有 id 的不重复搬。 + local with_tomb_previous = { + { pos0 = "p", kavita_id = 71, kavita_note = "n" }, + { datetime = "d", kavita_id = 9, kavita_deleted = true }, + } + local reattached = source:prepareLocalAnnotations(with_tomb_previous, + { { pos0 = "p", note = "新" } }) + Assert.eq(#reattached, 2) + Assert.is_true(reattached[2].kavita_deleted) + Assert.eq(reattached[2].kavita_id, 9) +end + +-- 远端删除回流(spec §9.2):seen 按远端**全量** id 建,未定位条目仍占位; +-- 输出只画可渲染的远端条目;本地带 id 但远端没有 → 丢弃并计入 dropped。 +do + local remote = { + { datetime = "d1", page = "/body/p[1].0", pos0 = "/body/p[1].0", pos1 = "/body/p[1].5", + drawer = "lighten", text = "远端还在", kavita_id = 1 }, + { datetime = "d2", kavita_id = 2, kavita_xpath = "//body/p[2]", kavita_unlocated = true }, + } + local current = { + { datetime = "d1", page = "/body/p[1].0", pos0 = "/body/p[1].0", pos1 = "/body/p[1].5", + drawer = "lighten", text = "远端还在", kavita_id = 1 }, + { datetime = "d2", page = "/body/p[2].0", pos0 = "/body/p[2].0", pos1 = "/body/p[2].5", + drawer = "lighten", text = "本地定位过", kavita_id = 2 }, + { datetime = "d3", page = "/body/p[3].0", pos0 = "/body/p[3].0", pos1 = "/body/p[3].5", + drawer = "lighten", text = "远端删了", kavita_id = 3 }, + { datetime = "d4", page = "/body/p[4].0", pos0 = "/body/p[4].0", pos1 = "/body/p[4].5", + drawer = "lighten", text = "纯本地" }, + } + local merged, dropped = source:mergeAnnotations(remote, current, nil, false) + Assert.eq(#merged, 3, "远端已定位 1 条 + 未定位的本地副本 + 纯本地 1 条") + Assert.eq(merged[1].kavita_id, 1) + Assert.eq(merged[2].kavita_id, 2, "未定位远端不画,但本地已定位的那条保留") + Assert.is_nil(merged[3].kavita_id) + Assert.eq(dropped, 1, "只有远端确实没有的 id 算 dropped") + for _idx, item in ipairs(merged) do Assert.is_true(item.kavita_id ~= 3) end + + -- 远端条目与本地同 id 只画远端那份(本地被替换),不算删除。 + local replaced, replaced_dropped = source:mergeAnnotations( + { remote[1] }, { { datetime = "d1", page = "old", pos0 = "old", pos1 = "old", + drawer = "lighten", text = "本地旧坐标", kavita_id = 1 } }, nil, false) + Assert.eq(#replaced, 1) + Assert.eq(replaced[1].page, "/body/p[1].0") + Assert.eq(replaced_dropped, 0) + + -- 离线 / 未定位全败:远端列表为空但本地都没有 id 时一条都不丢。 + local kept, kept_dropped = source:mergeAnnotations({}, { + { datetime = "d4", page = "/body/p[4].0", pos0 = "/body/p[4].0", pos1 = "/body/p[4].5", + drawer = "lighten", text = "纯本地" }, + }, nil, false) + Assert.eq(#kept, 1) + Assert.eq(kept_dropped, 0, "离线没有 id 集合时不判删除") +end + +-- 远端同键重复(历史推送窗口的产物:真书 7460:11285 的 id 37 / 43 同 xPath 同文本, +-- spec §6「同键多条取 id 最小」/ §13.1 B):只画 id 最小那条,其余不渲染、也不当远端已删。 +do + local XPATH = "//body/DocFragment[24]/body/div[3]/p[2]" + local function remoteAnn(id, over) + local item = { + datetime = "d", page = "/body/p[24].0", pos0 = "/body/p[24].0", pos1 = "/body/p[24].5", + drawer = "lighten", text = "既替余以蕙纕兮", kavita_id = id, + kavita_xpath = XPATH, kavita_ending_xpath = XPATH, + } + for key, value in pairs(over or {}) do item[key] = value end + return item + end + local a37, a43 = remoteAnn(37), remoteAnn(43) + + local one, one_dropped, one_deduped = source:mergeAnnotations({ a37, a43 }, {}, nil, false) + Assert.eq(#one, 1, "同键两条只画一条") + Assert.eq(one[1].kavita_id, 37, "同键取 id 最小") + Assert.eq(one_dropped, 0, "去重不是远端删除") + Assert.eq(one_deduped, 1, "被抑制的远端条数走第三返回值") + + local reversed, r_dropped, r_deduped = source:mergeAnnotations({ a43, a37 }, {}, nil, false) + Assert.eq(#reversed, 1) + Assert.eq(reversed[1].kavita_id, 37, "倒序输入仍取 id 最小") + Assert.eq(r_dropped, 0) + Assert.eq(r_deduped, 1) + + -- 不同键的两条都保留(去重键不能退化成「一章一条」)。 + local other = remoteAnn(44, { + kavita_xpath = "//body/DocFragment[24]/body/div[3]/p[3]", + kavita_ending_xpath = "//body/DocFragment[24]/body/div[3]/p[3]", + text = "另一段划线", + }) + local both, both_dropped, both_deduped = source:mergeAnnotations({ a37, other }, {}, nil, false) + Assert.eq(#both, 2) + Assert.eq(both_dropped, 0) + Assert.eq(both_deduped, 0) + + -- 旧 doc_settings 里还留着一条带 43 的本地副本:远端 43 被抑制(id 仍在全量集合里), + -- 本地那份不能再画一遍,也不能算 dropped —— 否则合法去重会被条数保护当成远端删除。 + local local43 = { + datetime = "d", page = "/body/old.0", pos0 = "/body/old.0", pos1 = "/body/old.5", + drawer = "lighten", text = "既替余以蕙纕兮", kavita_id = 43, + } + local single, s_dropped, s_deduped = source:mergeAnnotations({ a37, a43 }, { local43 }, nil, false) + Assert.eq(#single, 1, "本地 43 不重复渲染") + Assert.eq(single[1].kavita_id, 37, "画的是 id 最小那条") + Assert.eq(s_dropped, 0, "远端 43 只是被抑制,不算远端已删") + Assert.eq(s_deduped, 1) +end + +-- 拉取:开书时把云端 epub 注解落库(入库不定位)。每章一次 GET,按 ownerUserId 收窄; +-- authoritative 恒 false(远端为空不代表本地该清空),失败就 cb(nil, err),快照不动。 +local ann_calls = {} +local remote_anns = { + { -- 网页端写的:Delta + HTML + 纯文本都有;颜色槽 2 = blue。 + id = 501, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "春眠不觉晓", + comment = '{"ops":[{"insert":"记一笔\\n"}]}', + commentHtml = "

记一笔

", commentPlainText = "记一笔", + selectedSlotIndex = 2, containsSpoiler = true, + createdUtc = os.date("!%Y-%m-%dT%H:%M:%S", 1790000000) .. ".789", + lastModifiedUtc = "2026-10-04T05:06:07.890", + pageNumber = 17, + }, + { -- 别人的注解:账号开了「查看他人注解」时接口会混进来,拉取必须按 owner 过滤。 + id = 502, ownerUserId = 9, chapterId = 2002, + xPath = "//body/p[2]", endingXPath = "//body/p[2]", selectedText = "别人的划线", + comment = "", commentHtml = "", selectedSlotIndex = 0, + createdUtc = "2026-10-03T05:00:00", + }, + { -- 裸高亮:没有备注,槽位越界 → yellow。 + id = 503, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[2]", endingXPath = "//body/p[3]", + selectedText = "处处闻啼鸟", + comment = "", commentHtml = "", commentPlainText = "", + selectedSlotIndex = 9, containsSpoiler = false, + createdUtc = "2026-10-03T05:00:00", + }, +} +routes["GET /api/Users/me"] = json({ id = 5, username = "me" }) +routes["GET /api/Annotation/all"] = function(opts) + ann_calls[#ann_calls + 1] = opts + return json(remote_anns) +end +local pulled, perr, pmeta = run("pullNotesAsync", volume) +Assert.eq(#ann_calls, 1, "每章一次 GET") +Assert.eq(query(ann_calls[1], "chapterId"), "2002") +Assert.eq(#pulled, 2, "只留自己的注解") +Assert.is_nil(perr) +Assert.is_false(pmeta.authoritative, "authoritative 恒 false:远端为空不清本地") + +local web = pulled[1] +Assert.eq(web.kavita_id, 501) +Assert.eq(web.text, "春眠不觉晓") +Assert.eq(web.note, "记一笔") +Assert.eq(web.kavita_note, web.note, "kavita_note 与 note 必须字节相同,否则每轮判改过") +Assert.eq(web.datetime, os.date("%Y-%m-%d %H:%M:%S", 1790000000), "createdUtc → 本地墙钟") +Assert.eq(web.color, "blue", "槽位 2 → blue") +Assert.eq(web.drawer, "lighten") +Assert.eq(web.kavita_comment, remote_anns[1].comment) +Assert.eq(web.kavita_comment_html, "

记一笔

") +Assert.eq(web.kavita_slot, 2) +Assert.eq(web.kavita_spoiler, true) +Assert.eq(web.kavita_modified, "2026-10-04T05:06:07.890") +Assert.eq(web.kavita_xpath, "//body/p[1]") +Assert.eq(web.kavita_ending_xpath, "//body/p[1]") +-- spine 提示必须落库:开书定位只按 pageNumber(+1)挑 DocFragment,丢了它多 spine epub 全定位失败。 +Assert.eq(web.pageNumber, 17, "DTO pageNumber 原样进 payload(0-based spine 提示)") +Assert.is_nil(web.pos0, "pull 不写坐标") +Assert.is_nil(web.pos1) +Assert.is_nil(web.page, "page 是定位阶段产物") +Assert.is_nil(web.pageno) +Assert.is_nil(web.chapter_idx, "整本桶") + +local bare = pulled[2] +-- KOReader 的 getBookmarkType 用 `if bookmark.note then return "note"`:Lua 里 "" 为真, +-- 默认 bookmarks_items_text_type = "note" 就会把空备注写成「高亮与笔记」列表里的空行。 +Assert.is_nil(bare.note, "空备注落 nil(不是空串),否则被当成 note 类型渲染空行") +Assert.is_nil(bare.kavita_note, "基线与 note 同源:空备注也是 nil(sameNote(nil, \"\") 仍判等)") +Assert.eq(bare.color, "yellow", "槽位越界回落 yellow") +Assert.eq(bare.pageNumber, 0, "DTO 缺 pageNumber 回落 0(只会试前两个 DocFragment)") + +-- 清洗(保存快照前的白名单)不能把空备注的 nil 变回空串。 +local cleaned_bare = source:cleanAnnotations(pulled, 10) +Assert.is_nil(cleaned_bare[2].note, "cleanAnnotations 后仍为 nil") +Assert.is_nil(cleaned_bare[2].kavita_note) +Assert.eq(cleaned_bare[1].note, "记一笔", "非空备注不受影响") + +-- createdUtc 解析不出(Kavita 的 0001 占位)就用当前时间,仍然要落库。 +routes["GET /api/Annotation/all"] = json({ { + id = 504, ownerUserId = 5, xPath = "//body/p[4]", endingXPath = "//body/p[4]", + selectedText = "无时间", comment = "", selectedSlotIndex = 0, createdUtc = "0001-01-01T00:00:00", +} }) +local fallback = run("pullNotesAsync", volume) +Assert.eq(#fallback, 1) +local wall = fallback[1].datetime +local wy, wmo, wd, wh, wmi, ws = wall:match("^(%d+)-(%d+)-(%d+) (%d+):(%d+):(%d+)$") +Assert.not_nil(wy, "datetime 必须是可读墙钟:YYYY-MM-DD HH:MM:SS") +Assert.is_true(math.abs(os.time({ year = tonumber(wy), month = tonumber(wmo), day = tonumber(wd), + hour = tonumber(wh), min = tonumber(wmi), sec = tonumber(ws) }) - os.time()) <= 2, + "解析失败回退当前时间") + +-- 同章重复拉取幂等:payload 逐字段稳定(owner 已缓存,不再请求 /Users/me)。 +routes["GET /api/Annotation/all"] = function(opts) + ann_calls[#ann_calls + 1] = opts + return json(remote_anns) +end +local function flatten(list) + local out = {} + for _idx, item in ipairs(list) do + local keys = {} + for key in pairs(item) do keys[#keys + 1] = key end + table.sort(keys) + local parts = {} + for _j, key in ipairs(keys) do parts[#parts + 1] = key .. "=" .. tostring(item[key]) end + out[#out + 1] = table.concat(parts, "&") + end + return table.concat(out, "||") +end +ann_calls = {} +local again = run("pullNotesAsync", volume) +Assert.eq(#ann_calls, 1, "owner 已缓存,不再请求 /Users/me") +Assert.eq(flatten(again), flatten(pulled), "重复拉取 payload 稳定") + +-- 空文本的远端条目画不出来,但它的 id 必须进远端全量集合(spec §7 unlocated / §9.2): +-- 丢在 annotationPayload 里,mergeAnnotations 就看不到这个 id,会把本地带该 id 的那条当成 +-- 「远端已删」抹掉(反之远端还在,本地却消失)。 +routes["GET /api/Annotation/all"] = json({ { + id = 7, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[7]", endingXPath = "//body/p[7]", + selectedText = " ", comment = "", selectedSlotIndex = 0, + createdUtc = "2026-10-03T05:00:00", +} }) +local blank_pulled = run("pullNotesAsync", volume) +Assert.eq(#blank_pulled, 1, "有 id 就保留占位(只有没 id 才真丢)") +Assert.eq(tonumber(blank_pulled[1].kavita_id), 7) +Assert.is_true(blank_pulled[1].kavita_unlocated, "空文本定位不出来:标记未定位") +Assert.is_nil(blank_pulled[1].drawer, "未定位占位不画、不进列表") +local local_seven = { datetime = "d7", page = "/body/p[7].0", pos0 = "/body/p[7].0", + pos1 = "/body/p[7].5", drawer = "lighten", text = "本地定位过", kavita_id = 7 } +local merged_seven, dropped_seven = source:mergeAnnotations(blank_pulled, { local_seven }, nil, false) +Assert.eq(dropped_seven, 0, "空文本的远端条目仍占 id:本地那条不算远端已删") +Assert.eq(#merged_seven, 1, "远端不画,本地那份保留") +Assert.eq(merged_seven[1], local_seven) +-- 恢复后续用例用的三条 fixture。 +routes["GET /api/Annotation/all"] = function(opts) + ann_calls[#ann_calls + 1] = opts + return json(remote_anns) +end + +-- 取不到当前用户(/api/Users/me 不可用)→ 不过滤 + 记日志,不能因此不落库。 +routes["GET /api/Users/me"] = { code = 404, body = "" } +local fresh = require("moonsource_kavita.source").new() +local warned = {} +local log = require("utils.log") +local real_warn = log.warn +log.warn = function(...) warned[#warned + 1] = table.concat({ ... }, " ") end +local unfiltered, ferr +fresh:pullNotesAsync(volume, function(a, e) unfiltered, ferr = a, e end) +Stubs.flush() +log.warn = real_warn +Assert.is_nil(ferr) +Assert.eq(#unfiltered, 3, "拿不到 owner 就不做属主过滤") +Assert.is_true(#warned >= 1, "降级要留一条日志") + +-- GET 失败 → cb(nil, err);核心拿到 nil 直接收尾(note.lua 的 finish(nil, err)),不会写桶, +-- 本地快照(含 sync_status=0 的脏行)保持原样。脏行保护在 NoteDB.upsertRemote +-- (`WHERE notes.sync_status=1`)与 note_sync_spec 里已覆盖,源侧不碰 notes 表。 +routes["GET /api/Annotation/all"] = { code = 500, body = "" } +local fail_list, fail_err = run("pullNotesAsync", volume) +Assert.is_nil(fail_list) +Assert.matches(fail_err, "500") +routes["GET /api/Annotation/all"] = nil + +-- 非 epub(PDF / 漫画)没有 Kavita 注解:空数组 + authoritative=false,一个请求都不发。 +local before_pull = #calls +local none_pulled, none_err, none_meta = run("pullNotesAsync", pdf) +Assert.eq(#none_pulled, 0) +Assert.is_nil(none_err) +Assert.is_false(none_meta.authoritative) +Assert.eq(#calls, before_pull, "非 epub 零请求") + +-- 详情:卷行取所属 series 的 metadata,写回这一行。 +routes["GET /api/Series/metadata"] = function(opts) + Assert.eq(query(opts, "seriesId"), "20") + return json({ summary = "卷简介", writers = { { name = "丁" } } }) +end +local detail = run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }) +Assert.eq(detail.intro, "第二卷简介", "详情补简介不能把卷摘要盖成整部简介") +Assert.eq(remembered["20:2002"].authors, "丁") +-- 目录里没有这一卷 / 这一卷没有摘要:保留行里已有的简介,最后才退回系列简介。 +tocs["20"][2].summary = nil +books["20:2002"] = { intro = "已有卷简介" } +Assert.eq(run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }).intro, "已有卷简介", + "没有卷摘要时不清空已有简介") +books["20:2002"] = nil +Assert.eq(run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }).intro, "卷简介", + "确认没有卷摘要才退回系列简介") +-- 旧目录缓存不认识卷摘要(升级前拉的目录):问一次单章接口,几 KB。 +routes["GET /api/Series/chapter"] = function(opts) + Assert.eq(query(opts, "chapterId"), "2002") + return json({ id = 2002, summary = "单章摘要" }) +end +Assert.eq(run("getDetailAsync", { source_id = "kavita", stable_id = "20:2002" }).intro, "单章摘要", + "目录没带卷摘要时用单章接口补") +routes["GET /api/Series/chapter"] = nil + +-- 漫画打开路径:判定 / 起始页 / 离线全归 kamare cache(03 A1/A2/A6),moon 只做路由与兜底。 +-- 关查看器写卷行 + 容器聚合(06 A1/A2),章末续读按回调 id 回目录(03 A7)。 +do + routes["GET /api/Series/metadata"] = metadata_route + routes["GET /api/Series/60"] = json({ id = 60, name = "漫画", libraryId = 3 }) + local volumes_route = routes["GET /api/Series/volumes"] + routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") ~= "60" then return volumes_route(opts) end + return json({ + { id = 600, chapters = { { id = 6000, titleName = "第1话", format = 1, pages = 30 } } }, + { id = 601, chapters = { { id = 6001, titleName = "第2话", format = 1, pages = 20 } } }, + }) + end + + -- 增强版:open 由 spec 控制返回;register_server 只用于镜像,不参与断言。 + local Cache = require("moonsource_kavita.cache") + local opened, reply = {}, nil + package.loaded["kamarecache"] = { + api_version = 1, + capabilities = { open = true, server = true }, + register_server = function() return "kav", nil end, + open = function(opts) + opened[#opened + 1] = opts + return reply(opts) + end, + } + Cache.reset() + + local toc = { + { idx = 6000, uid = 6000, title = "第1话", chapterId = 6000, volumeId = 600, libraryId = 3, + seriesId = 60, format = "cbz", pages = 30, pagesRead = 0 }, + { idx = 6001, uid = 6001, title = "第2话", chapterId = 6001, volumeId = 601, libraryId = 3, + seriesId = 60, format = "cbz", pages = 20, pagesRead = 0 }, + } + tocs["60"] = toc + books["60"] = { stable_id = "60", title = "漫画", authors = "甲", intro = "简介", category = "漫画" } + local ref = { source_id = "kavita", stable_id = "60:6001", book = books["60"] } + + -- 阅读统计只由 core 落库:源这一路碰都不该碰。 + local stats_read = false + package.loaded["book.stats_db"] = setmetatable({}, { + __index = function() + stats_read = true + return function() end + end, + }) + + --- 直接走一卷:同步回调不泵队列;返回实际发出的请求数。 + ---@return table { path, err, meta, http } + local NO_TOC = {} + local function open(entry, toc_arg, ref_arg) + local got + local list = toc_arg == NO_TOC and nil or (toc_arg or toc) + local before = #calls + source:openEntry(ref_arg or ref, entry, list, "漫画", function(path, err, meta) + got = { path = path, err = err, meta = meta } + end) + Stubs.flush() + got = got or {} + got.http = #calls - before + return got + end + + -- 成功:同步回调 handled;开书先问一次云端进度,把「另一台设备读到哪」直接当起始页。 + reply = function() return { kind = "viewer" } end + routes["GET /api/Reader/get-progress"] = json({ pageNum = 12 }) + local ok = open(toc[2]) + Assert.is_nil(ok.path) + Assert.is_nil(ok.err) + Assert.is_true(ok.meta and ok.meta.handled, "可见查看器:起始页 GET 回来后才回调 handled") + Assert.eq(ok.http, 1, "增强版开书只多问一次云端进度(起始页)") + Assert.len(opened, 1) + Assert.eq(opened[1].entry, toc[2]) + Assert.eq(opened[1].title, "漫画") + Assert.eq(opened[1].base_url, "http://kav", "地址去尾斜杠") + Assert.eq(opened[1].api_key, "k", "Key 去空白") + Assert.eq(opened[1].start_page, 13, "云端 pageNum 12 → 第 13 页:第一帧就落在云端位置") + + -- on_close:卷行写物理页 / 物理总数 / 现在;容器行写聚合 fraction + 最近阅读时间。 + written, remembered = {}, {} + -- 缺行不等于未读:卷行齐全(哪怕值是 0)才算得出聚合。 + progress["60:6000"] = { fraction = 0 } + opened[1].on_close(10, 20) + local volume = written["60:6001"] + Assert.eq(volume.page, 10, "卷行是唯一真实位置:物理页") + Assert.eq(volume.total_pages, 20, "物理总数来自 kamare 回调") + Assert.eq(volume.fraction, 0.5) + Assert.is_true((volume.updated_at or 0) > 0, "卷行用当前时间,进最近阅读") + local container = written["60"] + Assert.eq(container.fraction, 0.25, "聚合 = (0 个读完卷 + 本卷 0.5) / 2 卷") + Assert.is_true((container.updated_at or 0) > 0, "容器行带最近阅读时间:读完一卷系列行立刻浮上来") + Assert.eq(written_opts["60"] and written_opts["60"].reset_updated_at, true, + "容器行允许回落时间戳:旧版本存的未来时间要能被纠正") + Assert.is_nil(written_opts["60:6001"], "卷行走 MAX,修订号单调") + Assert.is_nil(container.page, "容器行只写聚合 fraction") + Assert.is_nil(container.total_pages) + Assert.eq(remembered["60:6001"].title, "漫画 · 第2话", "卷行缺书时用目录卷名补元数据") + Assert.eq(remembered["60:6001"].authors, "甲", "卷行继承容器作者") + Assert.eq(#dirty, 0, "不产生 dirty 行(sync_status=0 才进推送队列)") + Assert.eq(#require("book.progress_db").unsynced("kavita"), 0, "身份不在 unsynced 里") + Assert.is_false(stats_read, "不产生 reading_stats 行") + + -- 读完当前卷也只按卷数聚合:全卷读完才 100%。 + written = {} + progress["60:6000"] = { fraction = 1 } + opened[1].on_close(20, 20) + Assert.eq(written["60"].fraction, 1, "两卷都读完 = 100%") + progress["60:6000"] = nil + + -- 目录拿不到 / 本地缺卷行:算不出聚合就不动容器(缺行 ≠ 未读,低报比不更新更糟)。 + written, opened = {}, {} + progress["60"] = nil + reply = function() return {} end + local solo = open(toc[2], NO_TOC) + Assert.is_true(solo.meta and solo.meta.handled) + opened[1].on_close(10, 20) + Assert.is_nil(written["60"], "聚合算不出来时不写容器行(保留原值)") + progress["60"] = { fraction = 0.4 } + opened[1].on_close(10, 20) + Assert.eq(written["60"].fraction, 0.4, "有旧聚合就只刷新时间,不低报") + progress["60"] = nil + + -- 已有卷行:不重写元数据。 + books["60:6001"] = { stable_id = "60:6001", title = "已有" } + remembered, written = {}, {} + reply = function() return {} end + open(toc[2]) + opened[#opened].on_close(10, 20) + Assert.is_nil(remembered["60:6001"], "已有卷行不重复补元数据") + + -- on_next:只按回调 id 在 toc 找卷,再走同一条 Cache.open;找不到提示。 + written, opened = {}, {} + reply = function() return {} end + open(toc[2]) + local first = opened[1] + first.on_next(6000) + Assert.len(opened, 2, "按回调 id 打开下一卷") + Assert.eq(opened[2].entry.chapterId, 6000) + opened[2].on_close(30, 30) + Assert.eq(written["60:6000"].page, 30, "下一卷进度写下一卷行") + Assert.is_nil(written["60:6001"], "进度不串到上一卷") + local toasts = #Themed.all("toast") + first.on_next(9999) + Assert.len(opened, 2, "目录里没有的 id 不另开查看器") + Assert.eq(#Themed.all("toast"), toasts + 1) + Assert.eq(Themed.last("toast").text, "下一卷不在目录里") + + -- 单卷漫画:从书架行(stable_id = seriesId)打开,卷身份仍是 seriesId:chapterId。 + -- 关查看器写「卷行真实位置 + 带时间的容器行」,卷行元数据补齐(US 22 / 06 A2)。 + local single_toc, single_two = { toc[1] }, tocs["60"] + tocs["60"] = single_toc + books["60:6000"] = nil + written, remembered, opened = {}, {}, {} + reply = function() return { kind = "viewer" } end + local single_path, single_err, single_meta + source:openBookAsync({ source_id = "kavita", stable_id = "60", book = books["60"] }, nil, + function(p, e, m) single_path, single_err, single_meta = p, e, m end) + Stubs.flush() + Assert.is_nil(single_path) + Assert.is_nil(single_err) + Assert.is_true(single_meta and single_meta.handled, "单卷直接进查看器,不弹选卷") + Assert.eq(opened[1].entry.chapterId, 6000) + opened[1].on_close(5, 30) + Assert.eq(written["60:6000"].page, 5, "单卷也把真实位置写进卷行") + Assert.is_true((written["60:6000"].updated_at or 0) > 0, "卷行带时间戳,最近阅读能看到") + Assert.is_true((written["60"].updated_at or 0) > 0, "容器行带最近阅读时间") + Assert.eq(written["60"].fraction, 5 / 30, "容器行聚合百分比,书架有量级") + Assert.not_nil(remembered["60:6000"], "卷行元数据补齐:ProgressDB.recent 的 EXISTS books 过得去") + Assert.eq(remembered["60:6000"].title, "漫画 · 第1话") + tocs["60"] = single_two + + -- offline_not_cached + 无旧 cbz:提示,不落到下载。 + books["60:6001"] = nil + reply = function() return nil, "offline_not_cached", "这一卷还没缓存,联网后可下载" end + local offline = open(toc[2]) + Assert.is_nil(offline.path) + Assert.eq(offline.err, "这一卷还没缓存,联网后可下载") + Assert.eq(offline.http, 1, "未缓存离线:只问过一次起始页") + + -- 旧 cbz:kamare 缓存优先;offline_not_cached 时回退到本地文件。 + os.execute("mkdir -p '" .. WORK .. "/60:6001'") + local old_cbz = WORK .. "/60:6001/6001.cbz" + local old_file = assert(io.open(old_cbz, "wb")) + old_file:write("PK\3\4cbz") + old_file:close() + books["60:6001"] = { stable_id = "60:6001", path = old_cbz } + local comic = { source_id = "kavita", stable_id = "60", book = books["60"] } + + opened = {} + reply = function() return {} end + local before_book = #calls + local cpath, cerr, cmeta + source:openBookAsync(comic, nil, function(p, e, m) cpath, cerr, cmeta = p, e, m end) + Stubs.flush() + Themed.choose(Themed.last("list"), 2) + Stubs.flush() + Assert.is_nil(cpath) + Assert.is_nil(cerr) + Assert.is_true(cmeta and cmeta.handled, "kamare 缓存优先于旧 cbz") + Assert.eq(opened[1].entry.chapterId, 6001) + -- 目录命中缓存也照样拉一次「最新进度」(点开系列 = 想看服务器上的已读状态): + -- 只问 series(libraryId)+ volumes(各卷 pagesRead),不重拉 metadata。 + Assert.eq(#calls, before_book + 3, "开书:目录刷新 2 次 + 起始页 1 次") + Assert.matches(calls[before_book + 1].url, "^http://kav/api/Series/60$") + Assert.matches(calls[before_book + 2].url, "^http://kav/api/Series/volumes%?seriesId=60") + Assert.matches(calls[before_book + 3].url, "^http://kav/api/Reader/get%-progress") + Assert.not_nil(io.open(old_cbz), "旧 cbz 静默保留,不删用户数据") + + reply = function() return nil, "offline_not_cached", "这一卷还没缓存,联网后可下载" end + local offline_path, offline_err = run("openBookAsync", + { source_id = "kavita", stable_id = "60:6001", book = books["60"] }, nil) + Assert.eq(offline_path, old_cbz, "未缓存离线:先用盘上的旧 cbz") + Assert.is_nil(offline_err) + + -- viewer_running:绝不回退(旧 cbz 在盘上也不开,不下载)。 + reply = function() return nil, "viewer_running", "漫画阅读器已在运行" end + local running = open(toc[2]) + Assert.is_nil(running.path) + Assert.eq(running.err, "漫画阅读器已在运行") + Assert.eq(running.http, 1, "查看器已在运行:不下载(起始页那一次 GET 早已发出)") + + -- 未知失败 / 流式失败:在线 cbz 回退下载;image 报错。 + os.remove(old_cbz) + books["60:6001"] = nil + download.body, download.code = "PK\3\4cbz", 200 + reply = function() return nil, "open_failed", "打开漫画阅读器失败" end + local fallback + source:openEntry(ref, toc[2], toc, "漫画", function(p, e, m) fallback = { path = p, err = e, meta = m } end) + Stubs.flush() + Assert.eq(fallback.path, old_cbz, "kamare 失败:cbz 退回下载") + Assert.is_nil(fallback.err) + + local image = { chapterId = 6001, volumeId = 601, libraryId = 3, seriesId = 60, format = "image", pages = 20 } + local img_before = #calls + local img = open(image) + Assert.is_nil(img.path) + Assert.not_nil(img.err, "image 下载不了:报错") + Assert.eq(#calls, img_before + 1, "image 失败不回退下载(只有起始页那一次 GET)") + + reply = function() return nil, "no_pages", "这一卷没有可显示的页面" end + local empty = open(toc[2]) + Assert.is_nil(empty.path) + Assert.eq(empty.err, "这一卷没有可显示的页面") + Assert.eq(empty.http, 1) + + reply = function() return nil, "settings_write_failed", "无法写入 kamare 配置" end + local bad_settings = open(toc[2]) + Assert.is_nil(bad_settings.path) + Assert.eq(bad_settings.err, "无法写入 kamare 配置") + Assert.eq(bad_settings.http, 1) + + -- journal 与云端谁更靠后:起始页取 journal 更靠后的那一个;关书落库以 journal 为准。 + -- (journal 自己已经做过「服务端更靠后 → 抬升」的合并,moon 复用它落库就不会出现 + -- 「书架 50%、打开 30%」这种两份事实打架。) + local kamare = package.loaded["kamarecache"] + kamare.capabilities.resume = true + local resume_reply = { page = 15, source = "journal" } + kamare.resume_page = function() return resume_reply end + Cache.reset() + routes["GET /api/Reader/get-progress"] = json({ pageNum = 5 }) + opened = {} + reply = function() return { kind = "viewer" } end + local ahead = open(toc[2]) + Assert.is_true(ahead.meta and ahead.meta.handled) + Assert.eq(opened[#opened].start_page, 6, "把云端位置当提示传给 kamare(journal 合并在那边做)") + written = {} + opened[#opened].on_close(9, 20) + Assert.eq(written["60:6001"].page, 15, "关书落库以 journal 为准(不写回调的瞬时页)") + -- snapshot 是下载时的服务端快照,可能已经很旧:不许它覆盖关书写回的位置。 + resume_reply = { page = 3, source = "snapshot" } + written = {} + opened[#opened].on_close(9, 20) + Assert.eq(written["60:6001"].page, 9, "snapshot 不覆盖关书回调页") + kamare.capabilities.resume = nil + kamare.resume_page = nil + Cache.reset() + + -- 没有增强版(未装 / 官方版):旧回退照旧,图片目录仍是「需要安装 kamare」。 + package.loaded["kamarecache"] = nil + package.loaded["kamareimageviewer"] = nil + Cache.reset() + local degraded, degraded_before = nil, #calls + source:openEntry(ref, image, toc, "漫画", function(path, err) degraded = { path = path, err = err } end) + Stubs.flush() + Assert.is_nil(degraded.path) + Assert.eq(degraded.err, "图片目录格式需要安装 kamare 插件在线阅读") + Assert.eq(#calls, degraded_before, "没有缓存接口时图片目录不下载") + + -- 恢复增强版桩:后续段只用到 HTTP / 进度,不依赖缓存路径,但别把状态留给别的用例。 + package.loaded["kamarecache"] = { + api_version = 1, + capabilities = { open = true, server = true }, + register_server = function() return "kav", nil end, + open = function() return {} end, + } + Cache.reset() + package.loaded["book.stats_db"] = nil +end + +-- 官方 / 旧版 kamare(无 kamarecache):没有 journal,起始页由 moon 补: +-- 本地卷行(关查看器时写的真实页)优先,本机没读过才问 Kavita(03 A2 降级通道)。 +do + local Cache = require("moonsource_kavita.cache") + local legacy_shown = {} + package.loaded["kamarecache"] = nil + package.loaded["kamareimageviewer"] = { new = function(_self, spec) return spec end } + package.loaded["kavitaclient"] = { streamChapter = function() return { { pageNumber = 1 } } end } + local UIManager = require("ui/uimanager") + local real_show = UIManager.show + UIManager.show = function(_, widget) legacy_shown[#legacy_shown + 1] = widget end + Cache.reset() + + local entry = { chapterId = 6001, volumeId = 601, libraryId = 3, seriesId = 60, + format = "cbz", pages = 20, title = "第2话" } + local legacy_ref = { source_id = "kavita", stable_id = "60:6001" } + + ---@return table got, table|nil job, table|nil viewer + local function openLegacy() + local got + local job = source:openEntry(legacy_ref, entry, { entry }, "漫画", function(path, err, meta) + got = { path = path, err = err, meta = meta } + end) + Stubs.flush() + return got or {}, job, legacy_shown[#legacy_shown] + end + + -- 云端有进度:跟云端(跨设备读到哪就从哪续)。 + progress["60:6001"] = { page = 7, total_pages = 20 } + routes["GET /api/Reader/get-progress"] = json({ pageNum = 9 }) + local before = #calls + local got, _, viewer = openLegacy() + Assert.is_true(got.meta and got.meta.handled) + Assert.eq(#calls, before + 1, "官方通道开书先问一次云端进度") + Assert.eq(viewer.metadata.startPage, 10, "云端 pageNum 0-based → 第 10 页(比本地新就跟云端)") + + -- 本机没读过(换设备 / 重装):同样用云端 pageNum + 1。 + progress["60:6001"] = nil + routes["GET /api/Reader/get-progress"] = json({ pageNum = 3 }) + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 4, "没有本地进度:云端 pageNum + 1") + + -- 本机比云端靠后(云端进度被别处改旧了 / 刚在本地读了几页):用本机,不往回拽。 + progress["60:6001"] = { page = 7, total_pages = 20 } + routes["GET /api/Reader/get-progress"] = json({ pageNum = 3 }) + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 7, "本机更靠后:起始页用本机") + progress["60:6001"] = nil + + -- 云端也没读过:不给起始页,查看器从第 1 页开始。 + routes["GET /api/Reader/get-progress"] = json({ pageNum = 0 }) + viewer = select(3, openLegacy()) + Assert.is_nil(viewer.metadata.startPage, "云端无进度:不硬塞页码") + + -- 云端请求失败:本机关书写的卷行兜底,不把人丢回第 1 页。 + progress["60:6001"] = { page = 7, total_pages = 20 } + routes["GET /api/Reader/get-progress"] = { code = 500, body = "" } + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 7, "云端失败:用本地卷行续读") + + -- 云端页码超过当前总页数(服务器重排过):夹到总页数。 + routes["GET /api/Reader/get-progress"] = json({ pageNum = 30 }) + viewer = select(3, openLegacy()) + Assert.eq(viewer.metadata.startPage, 20, "页码夹到总页数") + + -- 离线:不问网络,直接用本地卷行;没有就第 1 页。 + online = false + before = #calls + viewer = select(3, openLegacy()) + Assert.eq(#calls, before, "离线不请求") + Assert.eq(viewer.metadata.startPage, 7, "离线用本地卷行续读") + progress["60:6001"] = nil + viewer = select(3, openLegacy()) + Assert.is_nil(viewer.metadata.startPage, "离线且本机没读过:第 1 页") + online = true + + -- 恢复增强版桩,别把状态留给后面的用例。 + progress["60:6001"] = nil + package.loaded["kamareimageviewer"] = nil + UIManager.show = real_show + package.loaded["kamarecache"] = { + api_version = 1, + capabilities = { open = true, server = true }, + register_server = function() return "kav", nil end, + open = function() return {} end, + } + Cache.reset() +end + +-- 漫画 cbz 用内置阅读器时进度同样上报:页级 0-based,读完发 pages(Kavita 据此标已读)。 +sent = nil +local cbz = { source_id = "kavita", stable_id = "60:6000" } +Assert.is_true(run("putProgressAsync", cbz, { fraction = 0.1, page = 4, total_pages = 30 })) +Assert.eq(sent.pageNum, 3, "cbz 页码 1-based → Kavita 0-based") +Assert.eq(sent.chapterId, 6000) +Assert.eq(sent.volumeId, 600) +Assert.eq(sent.libraryId, 3) +Assert.eq(sent.seriesId, 60) +Assert.is_nil(sent.bookScrollId, "非 epub 不带锚点") +run("putProgressAsync", cbz, { fraction = 1, page = 30, total_pages = 30 }) +Assert.eq(sent.pageNum, 30, "读完发 pages") +run("putProgressAsync", cbz, { fraction = 0, page = 1, total_pages = 30 }) +Assert.eq(sent.pageNum, 0, "第一页是 0(Kavita 页号 0-based)") +os.remove(require("datastorage"):getSettingsDir() .. "/moonsource_kavita_meta.lua") + +-- 服务端已读回填:网页端 / 别的设备读过的 epub 也要进「最近阅读」并可能标已读。 +-- series 级 pagesRead/pages 对 epub 只是 spine 比例,只补本地没有进度的书,绝不覆盖精确位置。 +local shelf_route = routes["POST /api/Series/all-v2"] +local read_route = json({ + { id = 700, name = "读过一半", libraryName = "书籍", format = 3, pages = 200, pagesRead = 50, + -- Kavita 同时给本地与 UTC 两个口径:差值 = 服务器时区(这里 UTC+8)。 + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 701, name = "读完了", libraryName = "书籍", format = 3, pages = 10, pagesRead = 10, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 710, name = "多卷书", libraryName = "书籍", format = 3, pages = 300, pagesRead = 90, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, +}) +-- 多卷 series:卷行上已经有进度 → 容器行改写服务端 series 级 fraction + 最近阅读时间, +-- 不 drop(06 A1)。图书馆「最近阅读」列系列行(点开再选卷),首页「当前阅读」取卷行。 +tocs["710"] = { { chapterId = 7101, title = "上" }, { chapterId = 7102, title = "下" } } +progress["710:7101"] = { fraction = 0.3, updated_at = os.time() - 3600 } +progress["710"] = { fraction = 0.5, updated_at = os.time() - 3600 } +books["710"] = { title = "多卷书", authors = "甲", intro = "简介", category = "书籍" } +routes["POST /api/Series/all-v2"] = read_route +written = {} +local vol_result = run("syncBooksAsync", { force = true }) +Assert.eq(written["700"].fraction, 0.25) +Assert.is_nil(written["700"].page, "epub 不写页码:Kavita 的页是 spine") +-- latestReadDate 是服务器本地时间(04:05 CST = 20:05Z 前一天),不是 UTC; +-- 按 UTC 解析会存成 1770091506(8 小时后的未来),刚读完的书就会被它压在下面。 +Assert.eq(written["700"].updated_at, 1770062706, "latestReadDate 按服务器时区换成真 epoch") +Assert.eq(written["701"].fraction, 1, "读完的写满比例,进步进「已读」") +Assert.eq(written["710"].fraction, 0.3, + "本地缺「下」卷行 → 退回服务端 pagesRead/pages(缺行不等于未读,宁可两套口径也不低报)") +Assert.eq(written["710"].updated_at, 1770062706, "容器行带最近阅读时间,图书馆按系列行排序") +Assert.eq(written_opts["710"] and written_opts["710"].reset_updated_at, true, + "回填聚合要能回落时间戳(旧版本存过未来时间 / 0)") +Assert.is_nil(written["710"].page, "容器行只写聚合 fraction") +Assert.eq(remembered["710:7101"].authors, "甲", "读过的卷行继承容器作者,不再显示未知作者") +Assert.eq(remembered["710:7101"].title, "多卷书 · 上") +Assert.eq(remembered["710:7101"].category, "书籍") +-- 对齐必须算进同步变更:pulled 全 0 时桌面不发 shelf_changed,首页「当前阅读」不重画, +-- 卡片会一直停在未知作者(对账 3 本 + 回填 700/701 各 1 + 卷行对齐 1 + 容器聚合 1)。 +Assert.eq(vol_result.pulled, 7, "卷行元数据对齐算一次变更,首页才会重画") +-- 卷行按真实书库落库后(rememberMany 会写库),重复同步不再是变更,否则每次同步都白刷首页。 +books["710:7101"] = remembered["710:7101"] +local vol_again = run("syncBooksAsync", { force = true }) +Assert.eq(vol_result.pulled - vol_again.pulled, 1, "已对齐的卷行不再重复计入变更") +-- 卷行齐全时容器行按卷级聚合(不是服务端页比):(0 读完 + 在读卷 0.3) / 2 卷 = 0.15 +progress["710:7102"] = { fraction = 0 } +written = {} +run("syncBooksAsync", { force = true }) +Assert.eq(written["710"].fraction, 0.15, "卷行齐全 → 容器行按卷级聚合") +progress["710:7102"] = nil + +-- 目录缓存过期不能让身份翻回容器行:过期目录照样算数,否则容器行会重新拿到 +-- 单书位置(整部书当成一卷)而不是聚合。 +toc_fresh, written = false, {} +run("syncBooksAsync", { force = true }) +Assert.eq(written["710"].updated_at, 1770062706, "过期目录也认卷身份:容器行仍写系列级时间") +Assert.eq(written["710"].fraction, 0.3, "目录过期时同样退回服务端比例(仍缺「下」卷行)") +Assert.is_nil(written["710"].page, "容器行只写聚合 fraction") +toc_fresh = true +written = {} +progress["700"] = { fraction = 0.4 } +run("syncBooksAsync", { force = true }) +Assert.is_nil(written["700"], "本地有进度就不回填,不覆盖精确位置") + +-- 旧版已经写进库的未来时间:同步时拉回真实时间(只降不升)。 +written, fixed = {}, {} +progress["700"] = { fraction = 0.4, updated_at = os.time() + 8 * 3600 } +run("syncBooksAsync", { force = true }) +Assert.eq(fixed["700"], 1770062706, "库里的未来时间被拉回 Kavita 的真实阅读时间") +progress["700"] = nil +routes["POST /api/Series/all-v2"] = shelf_route + +-- 另一台设备读的新卷:series 级只有聚合(pagesRead),本机没有那一卷的卷行, +-- 首页「当前阅读」会停在旧卷。continue-point 才知道「当前读的是哪一章 / 哪一卷」。 +do + routes["POST /api/Series/all-v2"] = json({ + { id = 8901, name = "系列甲", libraryName = "漫画", format = 1, pages = 400, pagesRead = 207, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 8902, name = "系列乙", libraryName = "漫画", format = 1, pages = 200, pagesRead = 200, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1", + latestReadDate = "2026-02-03T04:05:06.123" }, + { id = 8903, name = "系列丙", libraryName = "漫画", format = 1, pages = 200, pagesRead = 0, + lastChapterAdded = "2026-02-03T11:05:06.1", lastChapterAddedUtc = "2026-02-03T03:05:06.1" }, + }) + local asked = {} + routes["GET /api/Reader/continue-point"] = function(opts) + local sid = query(opts, "seriesId") + asked[#asked + 1] = sid + if sid == "8901" then + -- 第 2 卷读到第 7 页:这就是「正在读」的那一卷。 + return json({ id = 89010, volumeId = 9901, title = "-100000", titleName = "第2卷", + pages = 200, pagesRead = 7, summary = "第2卷摘要", + lastReadingProgressUtc = "2026-02-02T20:05:06.1" }) + end + -- 读完一卷后给的是「下一章」,pagesRead = 0:那不是正在读。 + return json({ id = 89020, volumeId = 9902, titleName = "第1卷", pages = 200, pagesRead = 0 }) + end + books["8901"] = { title = "系列甲", authors = "甲", category = "漫画" } + books["8902"] = { title = "系列乙", authors = "乙", category = "漫画" } + books["8903"] = { title = "系列丙", authors = "丙", category = "漫画" } + written, remembered = {}, {} + run("syncBooksAsync", { force = true }) + -- 只问「读过、还没读完」的漫画:读完的(8902)和没读过的(8903)都不需要当前卷。 + Assert.eq(table.concat(asked, ","), "8901") + local row = written["8901:89010"] + Assert.not_nil(row, "服务器说在读的那一卷补成本地卷行") + Assert.eq(row.page, 8, "Kavita pageNum 是 0-based:本地 page 要 +1") + Assert.eq(row.fraction, 8 / 200, "fraction 与 page 同口径(1-based)") + Assert.eq(row.total_pages, 200) + Assert.eq(row.updated_at, 1770062706, "用章节的 UTC 阅读时间(换算成本地 epoch)") + Assert.eq(remembered["8901:89010"].title, "系列甲 · 第2卷", "卷行继承容器元数据,标题带卷名") + Assert.eq(remembered["8901:89010"].intro, "第2卷摘要", "卷简介用这一卷的摘要,不用整部简介") + Assert.is_nil(written["8902:89020"], "读完的卷不补:continue-point 给的是下一章") + -- 同一份服务端进度不重复写:每 5 分钟重写同一行会白刷首页。 + progress["8901:89010"] = { page = 8, fraction = 8 / 200, updated_at = 1770062706 } + written = {} + run("syncBooksAsync", { force = true }) + Assert.is_nil(written["8901:89010"], "服务端没更新就不重写") + -- 另一台设备接着读了:服务器时间更新 → 采纳服务器的位置(服务器优先)。 + routes["GET /api/Reader/continue-point"] = json({ id = 89010, volumeId = 9901, + titleName = "第2卷", pages = 200, pagesRead = 120, + lastReadingProgressUtc = "2026-02-03T01:05:06.1" }) + written = {} + run("syncBooksAsync", { force = true }) + Assert.eq(written["8901:89010"].page, 121, "服务器更靠后:121 页(pageNum 120 + 1)") + Assert.eq(written["8901:89010"].fraction, 121 / 200, "百分比跟着页走,不和服务端差一页") + progress["8901:89010"] = nil + routes["POST /api/Series/all-v2"] = shelf_route +end + +-- 阅读期进度心跳:Kavita 的阅读会话时长按相邻两次进度写入的间隔算,只在关书推一次, +-- Kavita 那边就是一个 StartTime == EndTime 的 0 秒会话。翻页 / 切章 / 唤醒起心跳:位置一变 +-- 就补推(节流合并密集翻页),另有兜底定时拍照顾慢读;离线或上一拍未回就跳过这一拍; +-- 关书 / 休眠 / 关源即停。 +do + local UIManager = require("ui/uimanager") + local real_in, real_un, real_time = UIManager.scheduleIn, UIManager.unschedule, os.time + local scheduled = {} + UIManager.scheduleIn = function(_self, delay, fn) scheduled[#scheduled + 1] = { delay = delay, fn = fn } end + UIManager.unschedule = function(_self, fn) + for i = #scheduled, 1, -1 do + if scheduled[i].fn == fn then table.remove(scheduled, i) end + end + end + local now = 1800000000 + os.time = function(t) return t and real_time(t) or now end + local function advance(seconds) now = now + seconds end + local function fire() table.remove(scheduled, 1).fn(); Stubs.flush() end + + sent = nil + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.4, locator = "/body/DocFragment[5]/body/div/p[1]/text().0" }, + }) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.5, locator = "/body/DocFragment[6]/body/div/p[2]/text().0" }, + }) + Assert.len(scheduled, 1, "同一本书只有一个心跳") + Assert.eq(scheduled[1].delay, 30, "拍间隔就是设置的心跳间隔(默认 30 秒)") + Assert.is_nil(sent, "起心跳不当场发请求(避开开书拉取)") + + local Progress = require("book.progress") + local decision = Progress.decision(volume) + decision.phase = "choosing" + advance(31) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.54, locator = "/body/DocFragment[6]/body/div/p[2]/text().0" }, + }) + Assert.is_nil(sent, "未决议时心跳不能绕过门禁") + decision.phase = "ready" + fire() + Assert.eq(sent.pageNum, 5, "解锁后下一拍补推保留的位置") + Assert.eq(sent.bookScrollId, "//body/div[1]/p[2]") + + -- 位置一变就补推:Kavita 认的是两次写入之间的跨度,必须真的把新位置写上去。 + advance(31) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.55, locator = "/body/DocFragment[6]/body/div/p[3]/text().0" }, + }) + Stubs.flush() + Assert.eq(sent.pageNum, 5, "翻页后推新位置(spine)") + Assert.eq(sent.bookScrollId, "//body/div[1]/p[3]") + Assert.len(scheduled, 1, "补推不另起定时器") + + -- 距上次不足 MIN_PUSH_GAP 的翻页:合并,交给下一拍,不每页一发。 + sent = nil + advance(10) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.6, locator = "/body/DocFragment[7]/body/p[1]/text().0" }, + }) + Assert.is_nil(sent, "翻页密集时合并") + + -- 兜底定时拍到点:推最近一次的位置。 + advance(120) + fire() + Assert.eq(sent.pageNum, 6, "定时拍推最近位置") + Assert.len(scheduled, 1, "一拍结束后重排下一拍") + + -- 位置没变的兜底拍:跳过,别白推(Kavita 对同位置也会 early-return)。 + sent = nil + advance(200) + fire() + Assert.is_nil(sent, "位置没变不推") + Assert.len(scheduled, 1) + + -- 离线只跳过这一拍,不补报,但心跳继续(重排已经发生)。 + online, sent = false, nil + advance(200) + fire() + Assert.is_nil(sent, "离线不发") + Assert.len(scheduled, 1) + online = true + + -- 上一拍回包还没落地:busy 未清,本拍跳过,不重复发也不丢位置。 + local before = #calls + advance(61) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.7, locator = "/body/DocFragment[8]/body/p[1]/text().0" }, + }) + Assert.is_true(source._heartbeat.busy, "第一拍在飞") + sent = nil + advance(61) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.8, locator = "/body/DocFragment[9]/body/p[1]/text().0" }, + }) + Stubs.flush() + Assert.eq(#calls, before + 1, "上一拍未回,本拍不发") + Assert.eq(sent.pageNum, 7, "推的是飞出去那一拍的位置") + Assert.is_true(not source._heartbeat.busy, "回包落地后 busy 复位") + + -- 换书:停旧心跳,为新书重排。 + local other = { source_id = "kavita", stable_id = "20:2001" } + source:onEvent("page_changed", { identity = other, position = { fraction = 0.1 } }) + Assert.len(scheduled, 1, "换书只留一个心跳") + Assert.eq(source._heartbeat.identity.stable_id, "20:2001") + + -- 关书 / 休眠停掉,不再有调度。 + source:onEvent("reading_stopped", { identity = other }) + Assert.len(scheduled, 0, "关书 / 休眠停心跳") + Assert.is_nil(source._heartbeat) + + -- 关源也要停(换源时旧实例可能还挂着)。 + source:onEvent("chapter_changed", { identity = volume, position = { fraction = 0.2 } }) + Assert.len(scheduled, 1) + source:close() + Assert.len(scheduled, 0, "关源停心跳") + + -- 心跳间隔可配置:调大后按新间隔节流,兜底拍跟着放大;0 = 关闭阅读期心跳。 + cfg.heartbeat_interval = 120 + source:onEvent("page_changed", { identity = volume, position = { fraction = 0.9 } }) + Assert.len(scheduled, 1, "改间隔后起心跳") + Assert.eq(scheduled[1].delay, 120, "兜底拍跟到新间隔,不白醒") + sent = nil + advance(31) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.91, locator = "/body/DocFragment[6]/body/p[9]/text().0" }, + }) + Stubs.flush() + Assert.is_nil(sent, "120s 间隔内不推") + advance(100) + source:onEvent("page_changed", { + identity = volume, + position = { fraction = 0.92, locator = "/body/DocFragment[6]/body/p[10]/text().0" }, + }) + Stubs.flush() + Assert.is_true(sent ~= nil, "超过 120s 后补推") + + cfg.heartbeat_interval = 0 + source:onEvent("page_changed", { identity = volume, position = { fraction = 0.93 } }) + Assert.len(scheduled, 0, "0 = 关闭心跳,不再调度") + Assert.is_nil(source._heartbeat) + cfg.heartbeat_interval = nil + + UIManager.scheduleIn, UIManager.unschedule, os.time = real_in, real_un, real_time +end + +-- 统计钩子:能力申报 + 推送 = 纯本地确认。Kavita 侧的阅读历史由服务端自己记录(会话 × 系列, +-- 带章节明细),本机没有对应的上报接口;确认后这些行不再是脏行,展示仍按 +-- 「云端快照 + 拉取后本地新读」合并。 +do + local SourceCapabilities = require("source.base").SourceCapabilities + Assert.is_true(source:capabilities().stats_pull, "申报可拉取统计") + Assert.is_true(SourceCapabilities.supportsStatsPull(source), "框架入口据此调 pullStatsAsync") + + local confirmed, returned + local before_calls = #calls + returned = source:pushStatsAsync({ { id = 7 }, { id = 8 } }, function(data) confirmed = data end) + Assert.is_nil(confirmed, "当场能回的结果也下一帧回调(源契约:defer,cancel 句柄先于回调成立)") + Assert.not_nil(returned and returned.cancel, "返回可取消句柄(在飞取消是契约的一部分)") + Stubs.flush() + Assert.eq(confirmed.synced_ids[1], 7, "确认回本批行 id(框架据此标 sync_status=1)") + Assert.eq(confirmed.synced_ids[2], 8) + Assert.eq(#calls, before_calls, "本地确认不发请求") + confirmed = nil + source:pushStatsAsync(nil, function(data) confirmed = data end) + Stubs.flush() + Assert.eq(#confirmed.synced_ids, 0, "空批次也回空表,不报错") + + -- 取消:下一帧之前取消,回调不再到达。 + local reached = false + returned = source:pushStatsAsync({ { id = 9 } }, function() reached = true end) + returned:cancel() + Stubs.flush() + Assert.is_false(reached, "取消后不回调") +end + +-- 拉取全量阅读历史:按分页头展开两页;参数形态(Libraries 重复键 / TimeZoneId / PageSize=200 / +-- 不带日期范围);身份判定命中目录缓存(4 章 = 多卷 → 逐卷身份);替换指令与核心对账基线一致。 +local warnings = {} +do + local log = require("utils.log") + log.warn = function(...) warnings[#warnings + 1] = table.concat({ ... }, " ") end +end +--- 记录某次拉取里出现过「跳过系列」的警告(按 seriesId 找)。 +local function warnedAbout(series_id) + for _idx, text in ipairs(warnings) do + if text:find(series_id, 1, true) then return true end + end + return false +end +local function readFile(path) + local file = io.open(path, "r") + if not file then return nil end + local content = file:read("*a") + file:close() + return content +end +local history = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_7453.lua") +local history_pages = { {}, {} } +for _idx, entry in ipairs(history) do + local page = #history_pages[1] < 50 and 1 or 2 + history_pages[page][#history_pages[page] + 1] = entry +end +local history_calls = {} +--- 分页头与响应体同一套往返桩:client 读到的就是「JSON 串 → 表」这条路。 +local function pagination_header(page, pages) + return JSON.encode({ currentPage = page, itemsPerPage = 50, totalItems = 64, totalPages = pages }) +end +routes["GET /api/Stats/reading-history"] = function(opts) + local page = tonumber(query(opts, "PageNumber")) + history_calls[#history_calls + 1] = opts.url + return json(history_pages[page], { Pagination = pagination_header(page, 2) }) +end +tocs["7453"] = { { chapterId = 11270 }, { chapterId = 11271 }, { chapterId = 11272 }, { chapterId = 11273 } } +-- 未选书库:与书架同步同类的配置错误,零请求(配置好了自然会重拉)。 +cfg.libraries = {} +local nolibs_before = #calls +local nolibs, nolibs_err = run("pullStatsAsync") +Assert.is_nil(nolibs) +Assert.matches(nolibs_err, "选择书库") +Assert.eq(#calls, nolibs_before, "未配置不发请求") +cfg.libraries = { ["2"] = true, ["1"] = true } +local pulled = run("pullStatsAsync") +Assert.len(history_calls, 2, "分页头说两页就拉两页") +Assert.matches(history_calls[1], "Libraries=1&Libraries=2", "库集合是重复键") +Assert.matches(history_calls[1], "TimeZoneId=Asia%%2FShanghai", "设备时钟 POSIX → IANA") +Assert.matches(history_calls[1], "PageSize=200") +Assert.matches(history_calls[1], "PageNumber=1&", "从第 1 页开始") +Assert.is_nil(history_calls[1]:match("StartDate"), "全量重拉不带日期范围") +Assert.matches(history_calls[2], "PageNumber=2&") +local pulled_total +for _idx, row in ipairs(pulled.rows) do + if row.record_type == "total" then pulled_total = row end +end +Assert.eq(pulled_total.duration, 14237, "两页合并后与样本书基线一致") +Assert.eq(pulled_total.source_id, "kavita") +Assert.eq(pulled.replace.mode, "ranges") +Assert.len(pulled.replace.books, 2, "本次身份(7453 的 4 章里读过两卷)") +Assert.contains(pulled.replace.books, "7453:11273") +Assert.not_nil(pulled.commit, "落库成功后由核心回调 commit") +Assert.len(history_calls, 2, "目录命中缓存,不为身份判定多请求") + +-- 设备时钟的 POSIX 串映射不出 IANA 时区(自定义 / 未知)时回退 UTC:服务端只认 IANA, +-- 宁可与设备差一天,不静默用错时区。 +setTZ("NOPE-1") +history_calls = {} +Assert.not_nil(run("pullStatsAsync")) +Assert.matches(history_calls[1], "TimeZoneId=UTC", "无法识别的时区回退 UTC") +setTZ("CST-8") + +-- 身份判定:目录缓存里没有的系列走 Source:toc(在线拉目录)后逐卷记;目录拿不到的系列整条跳过 +-- (不猜单卷 / 多卷),不中断其它系列。判定结果随 commit 记进状态文件,下一轮不再请求目录。 +do + local stats_history = { + { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 600, pagesRead = 3 } } }, + { seriesId = 10560, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 16493, durationSeconds = 300, pagesRead = 0 } } }, + { seriesId = 999, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 5, durationSeconds = 111, pagesRead = 0 } } }, + } + routes["GET /api/Stats/reading-history"] = function() + return json(stats_history, { Pagination = pagination_header(1, 1) }) + end + local volumes_route = routes["GET /api/Series/volumes"] + routes["GET /api/Series/8661"] = json({ id = 8661, name = "人类简史", libraryId = 1 }) + routes["GET /api/Series/10560"] = json({ id = 10560, name = "镖人", libraryId = 1 }) + routes["GET /api/Series/999"] = { code = 404, body = "" } + routes["GET /api/Series/volumes"] = function(opts) + if query(opts, "seriesId") == "8661" then + return json({ { id = 86610, chapters = { { id = 12763, titleName = "全", format = 3, pages = 10 } } } }) + end + if query(opts, "seriesId") == "10560" then + return json({ + { id = 105600, chapters = { { id = 16493, titleName = "一", format = 1, pages = 20 } } }, + { id = 105601, chapters = { { id = 16494, titleName = "二", format = 1, pages = 20 } } }, + { id = 105602, chapters = { { id = 16495, titleName = "三", format = 1, pages = 20 } } }, + }) + end + return volumes_route(opts) + end + tocs["8661"] = { { chapterId = 12763 } } + + local before = #calls + local pulled = run("pullStatsAsync") + local day = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) + local function findBook(rows, record_type, stable_id, start_time) + for _idx, row in ipairs(rows) do + if row.record_type == record_type and row.stable_id == stable_id + and (not start_time or row.start_time == start_time) then return row end + end + end + Assert.eq(findBook(pulled.rows, "book_day", "8661", day).duration, 600, "1 章 = 单卷,读在 series 行") + Assert.eq(findBook(pulled.rows, "book_day", "10560:16493", day).duration, 300, "3 章 = 多卷,读在卷行") + Assert.eq(findBook(pulled.rows, "total", "__kv:total").duration, 900, "判不出身份的系列不进总量") + for _idx, row in ipairs(pulled.rows) do + Assert.is_nil(row.stable_id:match("^999"), "目录拿不到的系列不猜身份") + end + local series_calls = {} + for idx = before + 1, #calls do + local sid = calls[idx].url:match("^http://kav/api/Series/(%d+)$") + if sid then series_calls[#series_calls + 1] = sid end + end + Assert.eq(table.concat(series_calls, ","), "10560,999", "缓存里有 8661,只判 10560 与 999") + Assert.is_true(warnedAbout("999"), "跳过的系列要能被日志定位") + + pulled.commit() + local state = require("luasettings"):open(STATS_STATE) + Assert.eq(state:readSetting("volumes")["8661"], 1, "单卷判定入状态文件") + Assert.eq(state:readSetting("volumes")["10560"], 3, "多卷判定入状态文件") + Assert.is_nil(state:readSetting("volumes")["999"], "判不出的系列不落状态,下轮还会再试") + local identities = state:readSetting("identities") + Assert.len(identities, 2) + Assert.contains(identities, "8661") + Assert.contains(identities, "10560:16493") + + -- 第二轮:目录缓存清空(再走判定就得发请求),但状态文件里有章数 → 一行请求都不发。 + tocs["8661"], tocs["10560"] = nil, nil + routes["GET /api/Series/10560"] = { code = 404, body = "" } + routes["GET /api/Series/volumes"] = function() return { code = 404, body = "" } end + before = #calls + local again = run("pullStatsAsync") + Assert.eq(findBook(again.rows, "book_day", "8661", day).duration, 600, "身份判定走状态文件,结果不变") + Assert.eq(findBook(again.rows, "book_day", "10560:16493", day).duration, 300) + series_calls = {} + for idx = before + 1, #calls do + local sid = calls[idx].url:match("^http://kav/api/Series/(%d+)$") + if sid then series_calls[#series_calls + 1] = sid end + end + Assert.eq(table.concat(series_calls, ","), "999", "已判定的系列不再请求目录") + Assert.len(again.replace.books, 2, "上次身份 ∪ 本次身份,旧身份的孤儿行照样清") + again.commit() + routes["GET /api/Series/volumes"] = volumes_route +end + +-- 缺行卷物化:云端读过、本机没有书行的卷(seriesId:chapterId)补一条轻量身份行 —— 标题 +-- 「系列 · 卷名」、继承容器行的作者 / 简介 / 分类 / 系列,不写封面。洞察「当日书单」、单书详情、 +-- 锁屏账单才有书名而不是裸 ID。隐藏身份行(库里落成 deleted=1 + sync_status=1)不上架、 +-- 不触发书架对账、不进书架同步结果,写库只由本次统计同步的 stats_changed 带走; +-- 容器行缺失时跳过物化(统计行照写)。 +do + local day = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) + local function findRow(rows, record_type, stable_id) + for _idx, row in ipairs(rows) do + if row.record_type == record_type and row.stable_id == stable_id then return row end + end + end + routes["GET /api/Stats/reading-history"] = function() + return json({ + { seriesId = 8801, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88010, durationSeconds = 600, pagesRead = 1 } } }, + { seriesId = 8802, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88020, durationSeconds = 300, pagesRead = 0 } } }, + { seriesId = 8803, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88030, durationSeconds = 120, pagesRead = 0 } } }, + { seriesId = 8804, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 88040, durationSeconds = 60, pagesRead = 0 } } }, + }, { Pagination = pagination_header(1, 1) }) + end + tocs["8801"] = { { chapterId = 88010, title = "第二卷" }, { chapterId = 88011, title = "第三卷" } } + tocs["8802"] = { { chapterId = 88020, title = "上" }, { chapterId = 88021, title = "下" } } + tocs["8803"] = { { chapterId = 88030, title = "全" } } + -- 卷名拿不到的老目录(只剩 chapterId):物化标题的卷名退容器名,不留裸 ID / 空标题。 + tocs["8804"] = { { chapterId = 88040 }, { chapterId = 88041 } } + books["8801"] = { title = "合集", authors = "甲", intro = "简介", category = "书籍" } + books["8803"] = { title = "单卷书", authors = "乙", category = "书籍" } + books["8804"] = { title = "太空漫游", authors = "丙", category = "书籍" } + + reconciled, remembered = nil, {} + local pulled = run("pullStatsAsync") + local material = remembered["8801:88010"] + Assert.eq(material and material.title, "合集 · 第二卷", "标题 = 系列 · 卷名(卷名取目录条目)") + Assert.eq(material and material.authors, "甲", "作者继承容器行") + Assert.eq(material and material.intro, "简介", "简介继承容器行") + Assert.eq(material and material.category, "书籍", "分类继承容器行") + Assert.eq(material and material.series, "合集", "系列列继承容器行") + Assert.is_nil(material and material.cover, "封面不写:卷封面走源既有取图链路") + Assert.is_nil(material and material.path, "不是下载行") + Assert.is_nil(material and material.deleted, "不带书架成员标记 → 落库即隐藏身份行,不上架") + Assert.is_nil(remembered["8801:88011"], "本次没读到的卷不物化") + Assert.is_nil(remembered["8802:88020"], "容器行缺失 → 跳过物化") + Assert.eq(findRow(pulled.rows, "book_day", "8802:88020").duration, 300, "容器缺失不影响统计行(照写)") + Assert.is_nil(remembered["8803"], "单卷系列读在容器行上,不另补行") + Assert.eq(remembered["8804:88040"] and remembered["8804:88040"].title, "太空漫游 · 太空漫游", + "目录条目没有卷名时退容器名(fetchToc 给不出时也别留裸 ID)") + Assert.is_nil(reconciled, "物化不触发书架对账") + Assert.is_nil(pulled.pulled, "物化不进书架同步结果(只由 stats_changed 刷新展示)") + + -- 物化后卷行真实入库(rememberMany 会落库):下一轮已存在且无变更 → 不重写(幂等)。 + -- 第二轮必须让核心调 commit 推进状态(真实链路:入库成功才 commit)。状态不前进的话 + -- 章数判定不落盘、目录每轮重读,测不出「第二轮拿不到卷名」的标题回退(旧用例的盲区)。 + books["8801:88010"] = remembered["8801:88010"] + local state_before_commit = readFile(STATS_STATE) + Assert.not_nil(state_before_commit, "前一段已经写过状态文件") + pulled.commit() + + -- 第二轮起目录缓存全清(目录接口也不可用):卷名只能来自状态文件里的持久化卷名。 + tocs["8801"], tocs["8802"], tocs["8803"], tocs["8804"] = nil, nil, nil, nil + local history_route = routes["GET /api/Stats/reading-history"] + routes["GET /api/Stats/reading-history"] = function() + return json({ + { seriesId = 8801, localDate = "2026-10-10T00:00:00", + chapters = { + { chapterId = 88010, durationSeconds = 600, pagesRead = 1 }, + -- 本轮新读到的卷:本机还没有书行,标题只能靠持久化卷名 + { chapterId = 88011, durationSeconds = 300, pagesRead = 0 }, + } }, + }, { Pagination = pagination_header(1, 1) }) + end + remembered = {} + run("pullStatsAsync") + Assert.is_nil(remembered["8801:88010"], "已存在的卷行不重写") + Assert.eq(remembered["8801:88011"] and remembered["8801:88011"].title, "合集 · 第三卷", + "第二轮物化标题取状态文件里的持久化卷名,不退容器名") + local committed = require("luasettings"):open(STATS_STATE) + local committed_titles = committed:readSetting("titles") + Assert.eq(committed_titles and committed_titles["8801"] and committed_titles["8801"]["88011"], "第三卷", + "身份判定时顺带记下的卷名落进状态文件(下次不用再读目录)") + routes["GET /api/Stats/reading-history"] = history_route + + -- 本地脏行(sync_status=0,本地改过):物化不动它(沿用卷行先例的 untouched 守卫)。 + books["8801:88010"] = { title = "本地改名", authors = "本地作者", sync_status = 0 } + remembered = {} + run("pullStatsAsync") + Assert.is_nil(remembered["8801:88010"], "本地脏行不重写") + Assert.eq(books["8801:88010"].title, "本地改名", "本地改的标题留着") + + -- 干净行但字段缺(容器后补的作者还没对齐):按容器补齐 —— 已存在且**有**变更照写, + -- 否则首次物化之后容器才补上的作者永远传不到卷行上。 + books["8801:88010"] = { title = "合集 · 第二卷", sync_status = 1 } + remembered = {} + run("pullStatsAsync") + Assert.eq(remembered["8801:88010"] and remembered["8801:88010"].authors, "甲", + "字段与容器不一致的行对齐一次") + + -- 兜底标题只用于新行:目录 / 状态都给不出卷名时,不能拿容器名盖既有行的真实标题 + -- (升级路径:老状态文件只有章数、没有卷名)。 + books["8804:88040"] = { title = "太空漫游 · 1001", sync_status = 1 } + remembered = {} + run("pullStatsAsync") + Assert.is_nil(remembered["8804:88040"], "无卷名时兜底标题不改写既有标题") + Assert.eq(books["8804:88040"].title, "太空漫游 · 1001", "既有真实标题保留") + + books["8801"], books["8801:88010"], books["8804:88040"] = nil, nil, nil + tocs["8801"], tocs["8802"], tocs["8803"], tocs["8804"] = nil, nil, nil, nil + books["8803"], books["8804"] = nil, nil + -- 状态恢复成这次 commit 之前的样子:后面的用例(落库时序 / 失败 / 取消)断言的是上段状态。 + local restore = assert(io.open(STATS_STATE, "w")) + restore:write(state_before_commit) + restore:close() + routes["GET /api/Stats/reading-history"] = function() + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 60, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 1) }) + end +end + +-- 落库时序 / 失败 / 取消 / 页数上限:状态只由 commit 推进,失败与取消都不动它。 +do + local day = os.time({ year = 2026, month = 10, day = 10, hour = 0 }) + local before_state = readFile(STATS_STATE) + Assert.not_nil(before_state, "前一段已经写过状态文件") + + -- 结果交回核心时还没落库:状态先一动不动,等核心入库成功调 commit 才前进。 + routes["GET /api/Stats/reading-history"] = function() + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 600, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 1) }) + end + local pulled = run("pullStatsAsync") + Assert.eq(readFile(STATS_STATE), before_state, "落库前不改状态(失败时身份不前进,孤儿行下次还能清)") + Assert.len(pulled.replace.books, 2, "replace.books = 上次身份 ∪ 本次身份") + Assert.contains(pulled.replace.books, "10560:16493") + Assert.contains(pulled.replace.books, "8661") + pulled.commit() + Assert.is_true(readFile(STATS_STATE) ~= before_state, "commit 之后才写状态") + + -- 失败:cb(nil, err),状态不前进、不建重试队列;本地统计不受影响(核心只记日志)。 + before_state = readFile(STATS_STATE) + routes["GET /api/Stats/reading-history"] = function() return { code = 500, body = "" } end + local failed, ferr = run("pullStatsAsync") + Assert.is_nil(failed) + Assert.matches(ferr, "500") + Assert.eq(readFile(STATS_STATE), before_state, "失败不前进状态") + + -- 取消也一样:第二页在飞时取消,迟到的回包不回调、不写状态。 + routes["GET /api/Stats/reading-history"] = function(opts) + if query(opts, "PageNumber") == "2" then + return { hold = true, reply = json({}, { Pagination = pagination_header(2, 2) }) } + end + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 60, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 2) }) + end + local called = false + local job = source:pullStatsAsync(function() called = true end) + Stubs.flush() + Assert.len(held, 1, "第二页在飞") + job:cancel() + held[#held]() + Stubs.flush() + Assert.is_false(called, "取消后不回调") + Assert.eq(readFile(STATS_STATE), before_state, "取消也不写状态") + + -- 分页头乱报(说 999 页):页数上限兜底,不无限循环,已经拿到的条目照常入库。 + local capped = 0 + routes["GET /api/Stats/reading-history"] = function() + capped = capped + 1 + return json({ { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 60, pagesRead = 0 } } } }, + { Pagination = pagination_header(1, 999) }) + end + local result = run("pullStatsAsync") + Assert.eq(capped, 50, "页数上限兜底") + Assert.not_nil(result, "上限只是停止续拉,不是失败") + Assert.eq(result.rows[1].start_time, day, "已经拉到的页照常入库") +end + +-- 框架集成:一次统计同步 = 先本地确认(push)再拉取(pull)落库;dirty_only(推脏)只推不拉。 +do + local pending_stats = { { + id = 21, source_id = "kavita", stable_id = "8661", record_type = "page", page = 3, + start_time = 1000, duration = 30, total_pages = 10, + } } + local events, marked, replaced = {}, nil, nil + package.loaded["book.stats_db"] = { + unsyncedBySource = function() return pending_stats end, + markSynced = function(ids) + marked = ids + events[#events + 1] = "mark" + pending_stats = {} + return true + end, + replaceSynced = function(source_id, replace, rows) + events[#events + 1] = "replace" + replaced = { source_id = source_id, replace = replace, rows = rows } + return { imported = #rows, skipped = 0 } + end, + compactSynced = function() return 0 end, + } + routes["GET /api/Stats/reading-history"] = function() + events[#events + 1] = "http" + return json({ + { seriesId = 8661, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 12763, durationSeconds = 120, pagesRead = 0 } } }, + -- 云端读过、本机没有书行的卷:同一次同步的拉取照常物化补身份行(12 号票语义)。 + { seriesId = 10560, localDate = "2026-10-10T00:00:00", + chapters = { { chapterId = 16493, durationSeconds = 60, pagesRead = 0 } } }, + }, { Pagination = pagination_header(1, 1) }) + end + books["10560"] = { title = "镖人", authors = "丰" } + remembered = {} + + local result = run("syncStatsAsync", nil) + Assert.eq(marked[1], 21, "先本地确认本地待同步行") + Assert.eq(replaced.source_id, "kavita") + local pulled_8661 = false + for _idx, row in ipairs(replaced.rows) do + if row.stable_id == "8661" then pulled_8661 = true end + end + Assert.is_true(pulled_8661, "拉取的行按云端快照入库") + Assert.not_nil(replaced.replace, "替换指令一并交给核心") + Assert.eq(events[1], "mark", "先推后拉:确认落在拉取之前") + Assert.eq(events[#events], "replace", "最后是落库") + Assert.eq(result.pushed, 1) + Assert.eq(result.pulled, #replaced.rows) + Assert.eq(remembered["10560:16493"] and remembered["10560:16493"].title, "镖人 · 一", + "物化标题取状态文件里的持久化卷名") + + -- dirty_only(推脏队列):只做本地确认,不发请求——拉取挂在打开 / 切换与手动刷新上。 + pending_stats = { { + id = 22, source_id = "kavita", stable_id = "8661", record_type = "page", page = 4, + start_time = 1100, duration = 30, total_pages = 10, + } } + marked, replaced, events = nil, nil, {} + local before_calls = #calls + run("syncStatsAsync", { dirty_only = true }) + Assert.eq(marked[1], 22, "推脏照样确认本地行") + Assert.is_nil(replaced, "dirty_only 不拉取、不覆盖") + Assert.eq(table.concat(events, ","), "mark", "dirty_only 只做本地确认") + Assert.eq(#calls, before_calls, "dirty_only 零请求") +end + +-- 状态文件被写坏(volumes / identities 不是表):当作没判过,本轮重新判定并从空表重建, +-- 不让存档损坏把整次拉取打断。 +do + local state = require("luasettings"):open(STATS_STATE) + state:saveSetting("volumes", 42) + state:saveSetting("identities", "坏") + state:flush() + + local before_calls = #calls + local recovered = run("pullStatsAsync") + Assert.not_nil(recovered, "损坏的状态文件不影响拉取") + local series_calls = 0 + for idx = before_calls + 1, #calls do + if calls[idx].url:match("^http://kav/api/Series/8661$") then series_calls = series_calls + 1 end + end + Assert.eq(series_calls, 1, "坏档当没判过:重新请求目录判定身份") + Assert.len(recovered.replace.books, 1, "坏档的 identities 不参与替换范围") + Assert.contains(recovered.replace.books, "8661") + recovered.commit() + state = require("luasettings"):open(STATS_STATE) + Assert.eq(state:readSetting("volumes")["8661"], 1, "判定结果从空表重建后写回") +end + +-- 定位:pull 只落数据,开书时按 DocumentFragment 滑窗把 cloud 划线变成 crengine xpointer。 +-- 假文档只实现定位用到的四个接口,语义按真机:`text()[k]` 逐个枚举、偏移按 codepoint 计。 +do + local function cp_len(s) + local n = 0 + for ch in s:gmatch("[%z\1-\127\194-\244][\128-\191]*") do n = n + 1 end + return n + end + + local function cp_sub(s, from, to) + local function byte_pos(count) + local seen, i = 0, 1 + while seen < count and i <= #s do + local b = s:byte(i) + i = i + (b < 0x80 and 1 or b < 0xE0 and 2 or b < 0xF0 and 3 or 4) + seen = seen + 1 + end + return i - 1 + end + return s:sub(byte_pos(from - 1) + 1, byte_pos(to)) + end + + ---@param fragments table[] 每项是一页(DocFragment)的段落列表;段落是字符串或文本节点数组。 + ---@param file string|nil + local function fakeDocument(fragments, file) + local elements, nodes, pages = {}, {}, {} + local order, fragment_text, node_offset = {}, {}, {} + for f, paragraphs in ipairs(fragments) do + local prefix = "/body/DocFragment[" .. f .. "]/body" + order[f] = order[f] or {} + for p, item in ipairs(paragraphs) do + local elem = prefix .. "/p[" .. p .. "]" + local texts = type(item) == "table" and item or { item } + elements[elem] = table.concat(texts) + for k, text in ipairs(texts) do + local path = elem .. "/text()[" .. k .. "]" + nodes[path] = text + order[f][#order[f] + 1] = path + end + pages[elem] = f * 10 + end + end + for f, paths in pairs(order) do + local acc, offsets, parts = 0, {}, {} + for _idx, path in ipairs(paths) do + offsets[path] = acc + acc = acc + cp_len(nodes[path]) + parts[#parts + 1] = nodes[path] + end + fragment_text[f] = table.concat(parts) + node_offset[f] = offsets + end + + local document = { file = file } + function document:getTextFromXPointer(xp) + local path = xp:gsub("%.%d+$", "") + return nodes[path] or elements[path] + end + function document:isXPointerInDocument(xp) + local path, off = xp:match("^(.*)%.(%d+)$") + path = path or xp + local text = nodes[path] + if text then + return off == nil or tonumber(off) <= cp_len(text) + end + return off == nil and elements[path] ~= nil + end + function document:getNormalizedXPointer(xp) + return self:isXPointerInDocument(xp) and xp or false + end + -- 真机语义:pos1 是「选区后第一个字符」的偏移(不含),跨文本节点时按片段拼接。 + function document:getTextFromXPointers(pos0, pos1) + local path0, off0 = pos0:match("^(.*)%.(%d+)$") + local path1, off1 = pos1:match("^(.*)%.(%d+)$") + if not path0 or not path1 then return nil end + local f = tonumber(path0:match("DocFragment%[(%d+)%]")) + if not f or not node_offset[f] or not node_offset[f][path0] or not node_offset[f][path1] then + return nil + end + return cp_sub(fragment_text[f], node_offset[f][path0] + tonumber(off0) + 1, + node_offset[f][path1] + tonumber(off1)) + end + function document:getPageFromXPointer(xp) + local elem = xp:match("^(.*)/text%(%)%[%d+%]%.%d+$") + return pages[elem] or pages[xp] or 1 + end + return document + end + + os.execute("mkdir -p '" .. WORK .. "'") + local book_path = WORK .. "/15-localize.epub" + local fh = assert(io.open(book_path, "wb")) + fh:write("PK\3\4epub") + fh:close() + + local document = fakeDocument({ + { + "春眠不觉晓,处处闻啼鸟。", + "夜来风雨声,花落知多少。", + { "春眠", "不觉晓" }, + { "第一段。", "第二段在同一 p 里。" }, + "去空白\194\160重试", + }, + { + "另一个 DocFragment 的正文。", + "滑窗命中的句子。", + }, + -- 多 spine 书(本票的真实形态):第 5 个片段里这句只在 pageNumber = 4 的提示下才找得到。 + { "第三个片段的噪音。" }, + { "第四个片段的噪音。" }, + { "第五个片段里才有的一句。", "第五个片段的第二段。" }, + }, book_path) + + local anns = { + { -- 普通命中:段内偏移按 codepoint 算,page 与 reader 一致填 pos0 字符串。 + kavita_id = 601, datetime = "2026-10-01 00:00:00", text = "处处闻啼鸟", note = "好诗", + kavita_note = "好诗", kavita_xpath = "//body/p[1]", kavita_ending_xpath = "//body/p[1]", + pageNumber = 0, + }, + { -- 多文本节点:Kavita 的 text() 下标只当提示,按 crengine 的节点枚举重新映射。 + kavita_id = 602, text = "不觉晓", kavita_xpath = "//body/p[3]", + kavita_ending_xpath = "//body/p[3]", pageNumber = 0, + }, + { -- pageNumber 差一位(旧推送窗口):spine 提示失败,靠 +1 滑窗命中。 + kavita_id = 603, text = "滑窗命中的句子", kavita_xpath = "//body/p[2]", + kavita_ending_xpath = "//body/p[2]", pageNumber = 0, + }, + { -- 跨段:起点取贴段尾的最长前缀,终点取贴段首的最长后缀。 + kavita_id = 604, text = "啼鸟。夜来", kavita_xpath = "//body/p[1]", + kavita_ending_xpath = "//body/p[2]", pageNumber = 0, + }, + { -- 元素下标失配(Kavita 的 p 数与 crengine 不同):同片段同级回扫。 + kavita_id = 605, text = "第二段在同一 p 里。", kavita_xpath = "//body/p[9]", + kavita_ending_xpath = "//body/p[9]", pageNumber = 0, + }, + { -- 单条失败不能拖累同书其它条:标 unlocated,不写占位坐标。 + kavita_id = 606, text = "这句话不在书里", kavita_xpath = "//body/p[2]", + kavita_ending_xpath = "//body/p[2]", pageNumber = 0, + }, + { -- 同一 kavita_id 已有通过校验的坐标:直接复用,避免每次开书重算。 + kavita_id = 607, text = "这句也找不到", kavita_xpath = "//body/p[1]", + kavita_ending_xpath = "//body/p[1]", pageNumber = 0, + }, + { -- 旧坐标已失效(偏移越界):不复用,重算失败照常标 unlocated。 + kavita_id = 608, text = "哪里都没有", kavita_xpath = "//body/p[1]", + kavita_ending_xpath = "//body/p[1]", pageNumber = 0, + }, + { -- 空白折叠差异(crengine 保留 NBSP,Kavita 存普通空格):去空白重试后回算偏移。 + kavita_id = 609, text = "去空白 重试", kavita_xpath = "//body/p[5]", + kavita_ending_xpath = "//body/p[5]", pageNumber = 0, + }, + } + local current = { + { kavita_id = 607, pos0 = "/body/DocFragment[1]/body/p[1]/text()[1].0", + pos1 = "/body/DocFragment[1]/body/p[1]/text()[1].2", page = "旧", pageno = 9 }, + { kavita_id = 608, pos0 = "/body/DocFragment[1]/body/p[1]/text()[1].999", + pos1 = "/body/DocFragment[1]/body/p[1]/text()[1].1000", page = "越界" }, + } + + local localized = source:localizeAnnotations(document, anns, book_path, current) + Assert.len(localized, #anns, "返回全量:定位失败的也在列表里") + Assert.eq(localized[1].kavita_id, 601) + Assert.eq(localized[1].pos0, "/body/DocFragment[1]/body/p[1]/text()[1].6") + Assert.eq(localized[1].pos1, "/body/DocFragment[1]/body/p[1]/text()[1].11") + Assert.eq(localized[1].page, localized[1].pos0, "page 填 pos0 字符串,不能填数字") + Assert.eq(localized[1].pageno, 10) + Assert.eq(localized[1].note, "好诗", "定位只补坐标,不动 pull 落的字段") + Assert.eq(localized[1].kavita_note, "好诗") + Assert.is_nil(localized[1].kavita_unlocated) + + Assert.eq(localized[2].pos0, "/body/DocFragment[1]/body/p[3]/text()[2].0", + "span 内文本按 crengine 的 text()[k] 重新编号") + Assert.eq(localized[2].pos1, "/body/DocFragment[1]/body/p[3]/text()[2].3") + + Assert.eq(localized[3].pos0, "/body/DocFragment[2]/body/p[2]/text()[1].0", "pageNumber 只当提示,+1 滑窗命中") + Assert.eq(localized[3].pageno, 20) + + Assert.eq(localized[4].pos0, "/body/DocFragment[1]/body/p[1]/text()[1].9", "跨段起点贴段尾") + Assert.eq(localized[4].pos1, "/body/DocFragment[1]/body/p[2]/text()[1].2", "跨段终点贴段首") + + Assert.eq(localized[5].pos0, "/body/DocFragment[1]/body/p[4]/text()[2].0", "p[9] 不存在时回扫同级") + + Assert.is_true(localized[6].kavita_unlocated, "文本匹配不到就标未定位") + Assert.is_nil(localized[6].pos0, "未定位不写占位坐标") + Assert.is_nil(localized[6].pos1) + Assert.is_nil(localized[6].page) + + Assert.eq(localized[7].pos0, "/body/DocFragment[1]/body/p[1]/text()[1].0", "复用 current 的有效坐标") + Assert.eq(localized[7].pos1, "/body/DocFragment[1]/body/p[1]/text()[1].2") + Assert.is_nil(localized[7].kavita_unlocated) + + Assert.is_true(localized[8].kavita_unlocated, "旧坐标越界不能复用") + Assert.is_nil(localized[8].pos0) + + Assert.eq(localized[9].pos0, "/body/DocFragment[1]/body/p[5]/text()[1].0", "NBSP 与普通空格差异靠去空白重试") + Assert.eq(localized[9].pos1, "/body/DocFragment[1]/body/p[5]/text()[1].6") + Assert.is_nil(localized[9].kavita_unlocated) + + -- 本票的链路回归(pull → cleanAnnotations → localize):三国演义这种多 spine epub 的注解在 + -- pageNumber 17/23/24(0-based),没有这个提示就只试 DocFragment[1]/[2], + -- 第 3 个片段之后全部 text-not-found → kavita_unlocated,一条都不画。 + routes["GET /api/Annotation/all"] = json({ { + id = 701, ownerUserId = 5, chapterId = 2002, + xPath = "//body/p[1]", endingXPath = "//body/p[1]", + selectedText = "第五个片段里才有的一句", + comment = "", commentHtml = "", commentPlainText = "", + selectedSlotIndex = 0, createdUtc = "2026-10-03T05:00:00", + pageNumber = 4, + } }) + local chain_pulled = run("pullNotesAsync", volume) + Assert.eq(chain_pulled[1].pageNumber, 4, "pull 保留 DTO 的 spine 提示") + local chain_clean = source:cleanAnnotations(chain_pulled, 0) + Assert.eq(chain_clean[1].pageNumber, 4, "cleanAnnotations 不能把提示洗掉") + local chain_located = source:localizeAnnotations(document, chain_clean, book_path, nil) + Assert.eq(chain_located[1].pos0, "/body/DocFragment[5]/body/p[1]/text()[1].0", + "pageNumber = 4 → 先试 DocFragment[5] 命中") + Assert.eq(chain_located[1].pos1, "/body/DocFragment[5]/body/p[1]/text()[1].11") + Assert.is_nil(chain_located[1].kavita_unlocated) + + -- 回归锁:同一份条目抹掉 pageNumber → 只试前两个片段 → 定位失败(真实 bug 的形态)。 + local no_hint = {} + for key, value in pairs(chain_clean[1]) do no_hint[key] = value end + no_hint.pageNumber = nil + local orphan = source:localizeAnnotations(document, { no_hint }, book_path, nil) + Assert.is_true(orphan[1].kavita_unlocated, "没有 spine 提示时第 3 个片段之后的文本定位不到") + Assert.is_nil(orphan[1].pos0) + Assert.is_nil(orphan[1].page) + + -- 无文档 / html_path 缺失 / 文件不存在 / 文档不是这本书 → nil(core 据此放弃应用,不覆盖 doc_settings)。 + Assert.is_nil(source:localizeAnnotations(nil, anns, book_path, current)) + Assert.is_nil(source:localizeAnnotations(document, anns, nil, current)) + Assert.is_nil(source:localizeAnnotations(document, anns, "", current)) + Assert.is_nil(source:localizeAnnotations(document, anns, WORK .. "/missing.epub", current)) + local other = fakeDocument({ { "别的书" } }, WORK .. "/other.epub") + Assert.is_nil(source:localizeAnnotations(other, anns, book_path, current), "document.file 与 html_path 不一致") +end + +---------------------------------------------------------------------- +-- 已删除的「多设备统计合并」开关:旧配置残留的键在源实例化时清掉。 +---------------------------------------------------------------------- +do + local Cache = require("moonsource_kavita.cache") + local original = { + probe = Cache.probe, queueState = Cache.queueState, + chapters = Cache.chapters, resumePage = Cache.resumePage, + } + Cache.probe = function() return { ok = true, capabilities = { chapters = true, queue = true } } end + Cache.queueState = function() return { state = "idle", entries = {} } end + local chapter_calls = 0 + Cache.chapters = function() + chapter_calls = chapter_calls + 1 + return { { chapterId = 9901, pages = 100, read = true, bytes = 1024 } } + end + Cache.resumePage = function() end + local series = { source_id = "kavita", stable_id = "9900", title = "续读测试", authors = "作者" } + local toc = { + { chapterId = 9901, title = "卷一", pages = 100, pagesRead = 1 }, + { chapterId = 9902, title = "卷二", pages = 100, pagesRead = 0 }, + } + tocs["9900"], toc_fresh = toc, true + progress["9900:9901"] = { fraction = 0.01, page = 1, total_pages = 100 } + local meta = source:readingTarget(series, { meta_only = true }) + Assert.eq(meta.select_text, "选择卷") + Assert.eq(chapter_calls, 0, "meta_only 不扫缓存") + local before = #calls + local target = source:readingTarget(series) + Assert.is_true(chapter_calls > 0, "完整目标才读 kamare 缓存") + local list_target = require("moonsource_kavita.volume_list").continueTarget(series, toc) + Assert.eq(target.book.stable_id, "9900:" .. list_target.entry.chapterId, + "详情目标与列表同源;kamare 完成事实优先于本机回顾进度") + Assert.eq(target.book.stable_id, "9900:9902") + Assert.eq(target.book.authors, "作者", "目标卷继承容器元数据") + Assert.eq(target.text, "继续阅读 · 卷二") + Assert.eq(target.select_text, "选择卷") + Assert.eq(#calls, before, "读取续读目标不发网络请求") + Assert.is_nil(source:readingTarget(target.book), "单卷不重新计算容器续读目标") + Assert.is_nil(source:readingTarget({ source_id = "kavita", stable_id = "9909" }), + "没有本地目录就保留原开书流程") + for name, method in pairs(original) do Cache[name] = method end +end + +cfg.merge_local_stats = true +require("moonsource_kavita.source").new() +Assert.is_nil(cfg.merge_local_stats, "旧开关残留键不能让核心继续按开启合并") + +os.execute("rm -rf '" .. WORK .. "'") diff --git a/tests/kavita/stats_spec.lua b/tests/kavita/stats_spec.lua new file mode 100644 index 0000000..a068cfa --- /dev/null +++ b/tests/kavita/stats_spec.lua @@ -0,0 +1,664 @@ +--[[-- +moonsource_kavita.stats:reading-history 条目 → reading_stats 行 / 替换指令 / 身份与时区映射。 + +对账基线 = research-kavita-stats-pull.md §3(样本 series 7453:64 条会话 / 14,237s)。 + +@module tests.moonsource_kavita.stats_spec +--]] + +local Assert = require("support.assert") +local Config = require("support.config") + +-- 日 / 时归属按进程时区(POSIX TZ)计算:钉死 CST-8,与 fixture 拉取时用的 Asia/Shanghai 对齐, +-- 断言就不会随宿主机时区漂移。 +local ffi = require("ffi") +ffi.cdef[[ int setenv(const char*, const char*, int); void tzset(void); ]] +ffi.C.setenv("TZ", "CST-8", 1) +ffi.C.tzset() + +local warnings = {} +package.preload["utils.log"] = function() + return { + dbg = function() end, + info = function() end, + warn = function(...) warnings[#warnings + 1] = table.concat({ ... }, " ") end, + error = function() end, + } +end + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +package.preload["moonsource_kavita.stats"] = function() + return dofile(PLUGIN .. "/stats.lua") +end +local Stats = require("moonsource_kavita.stats") + +-- 固定拉取时刻(2026-10-16T12:00:00Z,晚于样本最后一天):last_time / book_total.start_time 都对它断言 +local FETCHED = 1792152000 + +--- 当天设备本地零点。日期本身来自服务端;期望时差另有 research §3 表兜底。 +local function dayTs(y, m, d) + return os.time({ year = y, month = m, day = d, hour = 0 }) +end + +--- 当天设备本地整点(时段桶键)。 +local function hourTs(y, m, d, h) + return os.time({ year = y, month = m, day = d, hour = h }) +end + +--- 按记录身份找行(不依赖 rows 顺序)。 +local function find(rows, record_type, stable_id, start_time) + for _idx, row in ipairs(rows) do + if row.record_type == record_type and row.stable_id == stable_id + and (start_time == nil or row.start_time == start_time) then + return row + end + end +end + +--- 需要跨日断言时看日归属是否真是「服务端那一天」。 +local function ymd(ts) + return os.date("%Y-%m-%d", ts) +end + +do + -- 对账:样本《太空漫游 · 2010》64 条会话。逐日时长 / 页数为 research §3 的已知值。 + local history = dofile((debug.getinfo(1, "S").source:match("^@(.*)/")) .. "/fixtures/history_7453.lua") + local result = Stats.fromHistory(history, { + source_id = "kavita", + fetched_at = FETCHED, + volumes = { [7453] = 4 }, + seen = { "7453:11270" }, + }) + + local total = find(result.rows, "total", "__kv:total", 0) + Assert.not_nil(total, "账户累计行必须存在") + Assert.eq(total.duration, 14237, "样本全量时长") + Assert.eq(total.last_time, FETCHED, "累计行 last_time = 拉取时刻") + + local days = { + { 2026, 9, 29, 316, 2 }, + { 2026, 10, 5, 195, 0 }, + { 2026, 10, 7, 503, 0 }, + { 2026, 10, 8, 2036, 0 }, + { 2026, 10, 11, 512, 0 }, + { 2026, 10, 13, 979, 0 }, + { 2026, 10, 14, 6734, 0 }, -- 当天 +1 / -1 分属两条会话:先求和再钳制,相抵为净 0 页 + { 2026, 10, 15, 2962, 16 }, + } + local day_rows = 0 + local day_sum = 0 + local day_ts = {} + for _idx, d in ipairs(days) do + local ts = dayTs(d[1], d[2], d[3]) + day_ts[ts] = true + local row = find(result.rows, "day", "__kv:day:" .. ts, ts) + Assert.not_nil(row, "缺少日桶 " .. d[1] .. "-" .. d[2] .. "-" .. d[3]) + Assert.eq(row.duration, d[4], "日桶时长 " .. ymd(ts)) + Assert.eq(row.event_count, d[5], "日桶页数增量 " .. ymd(ts)) + Assert.eq(row.last_time, FETCHED, "日桶 last_time = 拉取时刻") + day_rows = day_rows + 1 + day_sum = day_sum + row.duration + end + Assert.eq(day_rows, 8, "只有有有效时长的日子落桶") + Assert.eq(day_sum, 14237, "账户累计 = 各日之和") + + -- 时段桶:每条活动行按自己的本地起始小时归档(跨零点的活动行取小时、仍记在条目那天)。 + local hour_rows, hour_total = 0, 0 + local hour_by_day = {} + for _idx, row in ipairs(result.rows) do + if row.record_type == "hour" then + hour_rows = hour_rows + 1 + hour_total = hour_total + row.duration + Assert.eq(row.stable_id, "__kv:hour:" .. row.start_time, "时段桶按整点做身份") + Assert.eq(row.last_time, FETCHED, "时段桶 last_time = 拉取时刻") + local d = os.date("%Y-%m-%d", row.start_time) + hour_by_day[d] = (hour_by_day[d] or 0) + row.duration + end + end + Assert.eq(hour_rows, 27, "样本 27 个整点有阅读") + Assert.eq(hour_total, 14237, "时段之和 = 账户累计") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 14, 11)).duration, 1352, "10-14 11 点") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 14, 14)).duration, 1812, "10-14 14 点") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 9, 29, 18)).duration, 316, "9-29 18 点") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 15, 21)).duration, 845, "10-15 21 点") + -- 日页面「标题时长 = 时段图逐格之和」:逐日必须对得上 + for _idx, d in ipairs(days) do + Assert.eq(hour_by_day[ymd(dayTs(d[1], d[2], d[3]))], d[4], + "时段逐日之和 = 日桶 " .. d[1] .. "-" .. d[2] .. "-" .. d[3]) + end + -- 零时长会话(10-06 的 4 条等)整条丢弃,不留日桶 + for _idx, d in ipairs({ { 2026, 10, 6 }, { 2026, 10, 9 }, { 2026, 10, 10 }, { 2026, 10, 12 } }) do + local ts = dayTs(d[1], d[2], d[3]) + Assert.is_nil(find(result.rows, "day", "__kv:day:" .. ts, ts), "零时长日不留桶") + end + + -- 多卷系列:章节 4 卷 → 逐卷身份;11271 只在 9-29 读过,11273 是其余各日。 + local book_total = find(result.rows, "book_total", "7453:11273", FETCHED) + Assert.not_nil(book_total, "卷累计行") + Assert.eq(book_total.duration, 13921) + Assert.eq(find(result.rows, "book_total", "7453:11271", FETCHED).duration, 316) + + Assert.eq(find(result.rows, "book_day", "7453:11271", dayTs(2026, 9, 29)).duration, 316) + local book_days, book_totals = 0, 0 + for _idx, row in ipairs(result.rows) do + if row.record_type == "book_day" then + book_days = book_days + 1 + Assert.is_true(row.duration > 0, "单书日行也必须正时长") + Assert.is_true(day_ts[row.start_time] == true, "单书日行 start_time = 服务端那天的本地零点") + elseif row.record_type == "book_total" then + book_totals = book_totals + 1 + Assert.eq(row.start_time, FETCHED, "单书累计行的 start_time = 拉取时刻") + end + -- 云端快照没有页坐标,所有行 page / total_pages 恒为 0 + Assert.eq(row.page, 0, "云端行 page=0") + Assert.eq(row.total_pages, 0, "云端行 total_pages=0") + Assert.eq(row.source_id, "kavita") + end + Assert.eq(book_days, 8, "11271 一天 + 11273 七天") + Assert.eq(book_totals, 2, "每卷一条累计快照") + + -- 本次身份:持久化后下次当「上次身份」用于清孤儿行。 + Assert.eq(#result.identities, 2) + Assert.contains(result.identities, "7453:11271") + Assert.contains(result.identities, "7453:11273") + + -- 替换:账户桶按前缀 + 覆盖全量重拉窗口的时间窗;单书按上次 ∪ 本次身份精确清。 + Assert.eq(result.replace.mode, "ranges") + Assert.eq(#result.replace.ranges, 3) + local ranges = {} + for _idx, range in ipairs(result.replace.ranges) do ranges[range.stable_prefix] = range end + local day_range, hour_range, total_range = + ranges["__kv:day:"], ranges["__kv:hour:"], ranges["__kv:total"] + Assert.not_nil(day_range, "日桶清理范围") + Assert.not_nil(hour_range, "时段桶清理范围") + Assert.not_nil(total_range, "总量行清理范围") + Assert.eq(day_range.from_ts, 0) + Assert.eq(day_range.to_ts, FETCHED) + Assert.eq(hour_range.from_ts, 0) + Assert.eq(hour_range.to_ts, FETCHED) + Assert.eq(total_range.from_ts, 0) + Assert.eq(total_range.to_ts, 0) + -- 全量重拉的清理窗口必须盖住本次写出的每个桶,否则消失的桶会残留 + for _idx, row in ipairs(result.rows) do + if row.record_type == "day" then + Assert.is_true(row.start_time <= day_range.to_ts, "日桶落在清理窗口内") + elseif row.record_type == "hour" then + Assert.is_true(row.start_time <= hour_range.to_ts, "时段桶落在清理窗口内") + end + end + Assert.eq(#result.replace.books, 3, "上次身份 ∪ 本次身份(含漂移孤儿)") + Assert.contains(result.replace.books, "7453:11270") + Assert.contains(result.replace.books, "7453:11271") + Assert.contains(result.replace.books, "7453:11273") +end + +do + -- 多章会话(跨卷)按章拆到各卷;单卷系列读在 series 行(research §5 的身份约定)。 + local result = Stats.fromHistory({ + { seriesId = 55, localDate = "2026-10-10T00:00:00", chapters = { + { chapterId = 11, durationSeconds = 100, pagesRead = 2 }, + { chapterId = 12, durationSeconds = 50, pagesRead = -1 }, + } }, + { seriesId = 66, localDate = "2026-10-10T00:00:00", chapters = { + { chapterId = 21, durationSeconds = 70, pagesRead = 0 }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [55] = 2, [66] = 1 } }) + local day = dayTs(2026, 10, 10) + Assert.eq(find(result.rows, "book_day", "55:11", day).duration, 100) + Assert.eq(find(result.rows, "book_day", "55:12", day).duration, 50) + Assert.eq(find(result.rows, "book_day", "66", day).duration, 70, "单卷记 series 身份") + Assert.eq(find(result.rows, "book_total", "55:11", 2000).duration, 100) + Assert.eq(find(result.rows, "book_total", "66", 2000).duration, 70) + local day_row = find(result.rows, "day", "__kv:day:" .. day, day) + Assert.eq(day_row.duration, 220, "账户日是各章之和") + Assert.eq(day_row.event_count, 1, "当天页数先求和:2 + (-1) + 0") + Assert.eq(find(result.rows, "total", "__kv:total", 0).duration, 220) + -- 没有 startTimeUtc 的条目退回 localDate 分日;造不出小时就不造,绝不凭空补一个整点。 + for _idx, row in ipairs(result.rows) do + Assert.is_true(row.record_type ~= "hour", "缺 startTimeUtc 不造时段桶") + end + Assert.len(result.identities, 3) + Assert.contains(result.identities, "55:11") + Assert.contains(result.identities, "55:12") + Assert.contains(result.identities, "66") +end + +do + -- 分日 / 分时按服务端 UTC 时刻在设备本地(CST-8)换算,不信服务端按请求时区给的 localDate。 + local result = Stats.fromHistory({ + -- 本地 10-16 07:59(UTC 10-15 23:59):服务端若按 UTC 算 localDate 会给 10-15,差一天。 + { seriesId = 31, startTimeUtc = "2026-10-15T23:59:00.1", localDate = "2026-10-15T00:00:00", + chapters = { { chapterId = 1, startTimeUtc = "2026-10-15T23:59:00.1", durationSeconds = 60, pagesRead = 1 } } }, + -- 本地 10-17 00:30 起、23:50 又读了一段:日桶在 10-17,两个时段格也都算 10-17 这天。 + { seriesId = 32, startTimeUtc = "2026-10-16T16:30:00", localDate = "2026-10-17T00:00:00", + chapters = { + { chapterId = 1, startTimeUtc = "2026-10-16T16:30:00", durationSeconds = 40, pagesRead = 0 }, + { chapterId = 1, startTimeUtc = "2026-10-17T15:50:00", durationSeconds = 60, pagesRead = 0 }, + } }, + }, { source_id = "kavita", fetched_at = FETCHED, volumes = { [31] = 2, [32] = 2, [33] = 2 } }) + local d16, d17 = dayTs(2026, 10, 16), dayTs(2026, 10, 17) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d16, d16).duration, 60, "本地 07:59 落本地当天") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 16, 7)).duration, 60, "本地 7 点格") + Assert.eq(find(result.rows, "day", "__kv:day:" .. d17, d17).duration, 100, "本地 0:30 起的那条落 10-17") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 17, 0)).duration, 40, "0 点格") + Assert.eq(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 17, 23)).duration, 60, "23 点格") + Assert.is_nil(find(result.rows, "hour", "__kv:hour:" .. hourTs(2026, 10, 18, 0)), + "跨零点前的活动行不另起一天") +end + +do + -- 负页数:按天先求和再钳制。逐条钳制会让 +5 / -5 相抵的日子凭空多出 5 页。 + local d1, d2 = dayTs(2026, 10, 1), dayTs(2026, 10, 2) + local result = Stats.fromHistory({ + { seriesId = 7, localDate = "2026-10-01T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 10, pagesRead = 5 } } }, + { seriesId = 7, localDate = "2026-10-01T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 10, pagesRead = -5 } } }, + { seriesId = 7, localDate = "2026-10-02T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 10, pagesRead = -3 }, + { chapterId = 1, durationSeconds = 10, pagesRead = -4 } } }, + }, { source_id = "kavita", fetched_at = 3000, volumes = { [7] = 2 } }) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d1, d1).event_count, 0, "正负相抵为净 0") + Assert.eq(find(result.rows, "day", "__kv:day:" .. d2, d2).event_count, 0, "负和钳制到 0") + Assert.eq(find(result.rows, "day", "__kv:day:" .. d1, d1).duration, 20) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d2, d2).duration, 20) +end + +do + -- 时区回退(UTC)下服务端的「日」可能晚于设备本地的拉取时刻(设备为负偏移): + -- 日桶清理窗口的上界要盖到最后观测日的日终,否则当天桶清不掉,会残留到下一轮。 + local last_day = dayTs(2026, 10, 16) + local fetched = last_day - 600 -- 设备本地 23:50,比最后观测日的零点还早 + local result = Stats.fromHistory({ + { seriesId = 21, localDate = "2026-10-16T00:00:00", + chapters = { { chapterId = 1, durationSeconds = 300, pagesRead = 1 } } }, + }, { source_id = "kavita", fetched_at = fetched, volumes = { [21] = 2 } }) + local day_range + for _idx, range in ipairs(result.replace.ranges) do + if range.stable_prefix == "__kv:day:" then day_range = range end + end + Assert.not_nil(day_range) + Assert.eq(day_range.from_ts, 0, "窗口下界仍是 0(全量重拉)") + Assert.eq(day_range.to_ts, last_day + 86399, "上界盖到最后观测日的日终") + for _idx, row in ipairs(result.rows) do + if row.record_type == "day" then + Assert.is_true(row.start_time <= day_range.to_ts, "日桶落在清理窗口内") + end + end + Assert.eq(day_range.stable_prefix:sub(1, 5), "__kv:", "范围只匹配本源的合成行,本地记录不受影响") +end + +do + -- 零时长条目整条丢弃(连页数一起):Kavita 会给「打开没读」建 0 时长会话。 + -- 本次身份照交回,好让 replace.books 清掉它上次留下的行。 + local d = dayTs(2026, 10, 3) + local before = #warnings + local result = Stats.fromHistory({ + { seriesId = 8, localDate = "2026-10-03T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 0, pagesRead = 9 } } }, + { seriesId = 8, localDate = "2026-10-03T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 0 } } }, + -- 目录拿不到章数的系列判不出身份:整体跳过,不猜单卷 / 多卷 + { seriesId = 999, localDate = "2026-10-03T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 100, pagesRead = 1 } } }, + }, { source_id = "kavita", fetched_at = 4000, volumes = { [8] = 2 }, seen = { "8:1" } }) + Assert.eq(find(result.rows, "book_day", "8:1", d).duration, 60) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 0, "零时长条目的页数不算") + Assert.eq(find(result.rows, "total", "__kv:total", 0).duration, 60, "跳过的系列不进总量") + Assert.eq(#result.identities, 1) + Assert.contains(result.identities, "8:1") + Assert.eq(#result.replace.books, 1) + Assert.contains(result.replace.books, "8:1") + local mentioned = false + for i = before + 1, #warnings do + if warnings[i]:find("999", 1, true) then mentioned = true end + end + Assert.is_true(mentioned, "跳过的系列要能被日志定位") + + -- 空回包不炸:仍给出完整的替换指令(全量重拉窗口照旧清) + local empty = Stats.fromHistory(nil, { source_id = "kavita", fetched_at = 4000 }) + Assert.len(empty.rows, 0) + Assert.len(empty.identities, 0) + Assert.len(empty.replace.books, 0) + Assert.eq(#empty.replace.ranges, 3) +end + +do + -- seen 的重复 / 空串不进 books;并集按 stable_id 精确去重(4 / 42 互为前缀,不能用 LIKE) + local result = Stats.fromHistory({ + { seriesId = 9, localDate = "2026-10-04T00:00:00", chapters = { + { chapterId = 1, durationSeconds = 5, pagesRead = 0 } } }, + }, { source_id = "kavita", fetched_at = 5000, volumes = { [9] = 2 }, + seen = { "9:1", "", "9:1", "stale" } }) + Assert.eq(#result.replace.books, 2) + Assert.contains(result.replace.books, "9:1") + Assert.contains(result.replace.books, "stale") +end + +do + -- 时区映射全表:设备时钟的 19 项 POSIX 串 → IANA(Kavita 的 TimeZoneId) + local expected = { + ["HST10"] = "Pacific/Honolulu", + ["AKST9AKDT,M3.2.0,M11.1.0"] = "America/Anchorage", + ["PST8PDT,M3.2.0,M11.1.0"] = "America/Los_Angeles", + ["MST7MDT,M3.2.0,M11.1.0"] = "America/Denver", + ["CST6CDT,M3.2.0,M11.1.0"] = "America/Chicago", + ["EST5EDT,M3.2.0,M11.1.0"] = "America/New_York", + ["<-03>3"] = "America/Sao_Paulo", + ["UTC0"] = "UTC", + ["GMT0BST,M3.5.0/1,M10.5.0"] = "Europe/London", + ["CET-1CEST,M3.5.0,M10.5.0/3"] = "Europe/Berlin", + ["EET-2EEST,M3.5.0/3,M10.5.0/4"] = "Europe/Athens", + ["MSK-3"] = "Europe/Moscow", + ["<+04>-4"] = "Asia/Dubai", + ["IST-5:30"] = "Asia/Kolkata", + ["<+07>-7"] = "Asia/Bangkok", + ["CST-8"] = "Asia/Shanghai", + ["JST-9"] = "Asia/Tokyo", + ["AEST-10AEDT,M10.1.0,M4.1.0/3"] = "Australia/Sydney", + ["NZST-12NZDT,M9.5.0,M4.1.0/3"] = "Pacific/Auckland", + } + local n = 0 + for posix, iana in pairs(expected) do + n = n + 1 + Assert.eq(Stats.ianaTimezone(posix), iana, posix) + end + Assert.eq(n, 19) + + -- 与设置页的时区表保持同步(读源码不 require UI 依赖):时钟加项时必须同步映射 + local file = assert(io.open(Config.root() .. "/book.koplugin/features/clock/init.lua", "r")) + local source = file:read("*a") + file:close() + local in_block, covered = false, 0 + for line in source:gmatch("[^\n]+") do + if line:match("Clock%.TIMEZONES%s*=") then + in_block = true + elseif in_block then + if line:match("^}") then break end + local posix = line:match('tz%s*=%s*"([^"]*)"') + if posix and posix ~= "" then + covered = covered + 1 + Assert.not_nil(expected[posix], "时钟时区缺少 IANA 映射:" .. posix) + end + end + end + Assert.eq(covered, 19, "时钟时区表全部覆盖") + + -- 未知 / 空串(跟随系统)回退 UTC 并 warn,不做地区默认 + local before = #warnings + Assert.eq(Stats.ianaTimezone(""), "UTC") + Assert.eq(Stats.ianaTimezone("NOPE-1"), "UTC") + Assert.eq(Stats.ianaTimezone(nil), "UTC") + Assert.eq(#warnings, before + 3, "每次回退都记一条日志") +end + +do + -- 阅读会话行:每个「会话 × 章」切片的真实起始时刻 / 时长 / 页数,供详情「阅读记录」列出时段。 + -- 它只进列表,不参与日 / 时段 / 总量汇总。 + local day = dayTs(2026, 10, 10) + local result = Stats.fromHistory({ + { seriesId = 66, startTimeUtc = "2026-10-10T09:00:00.0000000", chapters = { + { chapterId = 1, durationSeconds = 600, pagesRead = 12, + startTimeUtc = "2026-10-10T09:00:00.0000000" }, + { chapterId = 2, durationSeconds = 300, pagesRead = 3, + startTimeUtc = "2026-10-10T09:20:00.0000000" }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [66] = 1 } }) + + local first = find(result.rows, "cloud_session", "66", hourTs(2026, 10, 10, 17)) + Assert.not_nil(first, "会话行按章切片的本地起始时刻落行") + Assert.eq(first.duration, 600) + Assert.eq(first.event_count, 12, "页数记在 event_count") + Assert.eq(first.last_time, 2000, "会话行 last_time = 拉取时刻") + local second = find(result.rows, "cloud_session", "66", hourTs(2026, 10, 10, 17) + 20 * 60) + Assert.not_nil(second) + Assert.eq(second.duration, 300) + Assert.eq(second.event_count, 3) + + -- 会话行不影响任何汇总桶:日桶 / 总量仍是 900,且不会多出 hour 之外的重复 + Assert.eq(find(result.rows, "day", "__kv:day:" .. day, day).duration, 900) + Assert.eq(find(result.rows, "total", "__kv:total", 0).duration, 900) + Assert.eq(find(result.rows, "book_day", "66", day).duration, 900) + + -- 零时长会话不落会话行 + local zero = Stats.fromHistory({ + { seriesId = 66, startTimeUtc = "2026-10-10T10:00:00.0000000", chapters = { + { chapterId = 1, durationSeconds = 0, pagesRead = 0, + startTimeUtc = "2026-10-10T10:00:00.0000000" }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [66] = 1 } }) + Assert.is_nil(find(zero.rows, "cloud_session", "66"), "打开没读的会话不落行") +end + +do + -- 漫画(seriesFormat 0 Image / 1 Archive)的会话行补真实页坐标:page = endPage(读到哪)、 + -- total_pages = chapter.totalPages(卷级,汇总处继续 MAX);event_count 是**本次新推进的页数** + -- (不是 pagesRead —— 重读会重复计入,见下方进度用例)。pagesRead = 0 是合法值,不是缺数据。 + local result = Stats.fromHistory({ + { seriesId = 70, seriesFormat = 0, startTimeUtc = "2026-10-10T09:00:00.0000000", chapters = { + { chapterId = 1, durationSeconds = 300, pagesRead = 12, startPage = 3, endPage = 15, + totalPages = 194, startTimeUtc = "2026-10-10T09:00:00.0000000" }, + } }, + -- Archive 同样算漫画;同一系列两卷各自的卷级总页数不同,不能被条目级 totalPages 抹平。 + { seriesId = 71, seriesFormat = 1, startTimeUtc = "2026-10-10T10:00:00.0000000", chapters = { + { chapterId = 2, durationSeconds = 60, pagesRead = 0, startPage = 1, endPage = 1, + totalPages = 40, startTimeUtc = "2026-10-10T10:00:00.0000000" }, + { chapterId = 3, durationSeconds = 90, pagesRead = 7, startPage = 20, endPage = 30, + totalPages = 52, startTimeUtc = "2026-10-10T10:30:00.0000000" }, + } }, + -- epub 的 Chapter.Pages 是 spine 数、与渲染页无关:页坐标保持 0,不因带 endPage 就填。 + { seriesId = 72, seriesFormat = 3, startTimeUtc = "2026-10-10T11:00:00.0000000", chapters = { + { chapterId = 4, durationSeconds = 600, pagesRead = 7, startPage = 15, endPage = 15, + totalPages = 22, startTimeUtc = "2026-10-10T11:00:00.0000000" }, + } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [70] = 1, [71] = 1, [72] = 1 } }) + + local image = find(result.rows, "cloud_session", "70", hourTs(2026, 10, 10, 17)) + Assert.not_nil(image, "Image 漫画的会话行") + Assert.eq(image.page, 15, "page = chapter.endPage") + Assert.eq(image.total_pages, 194, "total_pages = chapter.totalPages") + Assert.eq(image.event_count, 15, "event_count = 本次新推进的页数(0 → 15)") + + local archive_zero = find(result.rows, "cloud_session", "71", hourTs(2026, 10, 10, 18)) + Assert.not_nil(archive_zero, "Archive 漫画的会话行") + Assert.eq(archive_zero.page, 1, "page = endPage(未翻页也合法)") + Assert.eq(archive_zero.total_pages, 40, "卷级总页数") + Assert.eq(archive_zero.event_count, 1, "推进到第 1 页即 1 页,与 pagesRead = 0 无关") + local archive_more = find(result.rows, "cloud_session", "71", hourTs(2026, 10, 10, 18) + 30 * 60) + Assert.not_nil(archive_more, "同一条目里的第二卷") + Assert.eq(archive_more.page, 30) + Assert.eq(archive_more.total_pages, 52, "逐章取自己的卷级总页数") + Assert.eq(archive_more.event_count, 29, "1 → 30 只推进 29 页(不是 pagesRead 7)") + + local epub = find(result.rows, "cloud_session", "72", hourTs(2026, 10, 10, 19)) + Assert.not_nil(epub, "epub 的会话行照旧落") + Assert.eq(epub.page, 0, "epub 不填 page") + Assert.eq(epub.total_pages, 0, "epub 不填 total_pages") + Assert.eq(epub.event_count, 7, "epub 仍用 pagesRead") + + -- 页坐标只加在会话行上:日 / 单书桶维持「云端快照没有页坐标」的语义(汇总另算)。 + local day = dayTs(2026, 10, 10) + for _idx, row in ipairs(result.rows) do + if row.record_type ~= "cloud_session" then + Assert.eq(row.page, 0, row.record_type .. " 行 page 仍为 0") + Assert.eq(row.total_pages, 0, row.record_type .. " 行 total_pages 仍为 0") + end + end + -- 当天页数 = 15(70)+ 1(71 卷 2)+ 29(71 卷 3)+ 7(epub 仍是 pagesRead) + Assert.eq(find(result.rows, "day", "__kv:day:" .. day, day).event_count, 52) + Assert.eq(find(result.rows, "book_day", "70", day).duration, 300) +end + +do + -- 漫画的已读页数按「最远进度」算,不按页次累加:pagesRead 是「这次翻了多少页」, + -- 重读会重复计入(实测 194 页的卷 6 条会话 pagesRead 合计 284,已读页数超过了总页数)。 + -- 样本:大剑 Vol.10,总 194 页;依次读到 3 → 91 → 42(重读)→ 94 → 126 → 194。 + local sessions = { + { end_page = 3, pages_read = 3 }, + { end_page = 91, pages_read = 87 }, + { end_page = 42, pages_read = 42 }, + { end_page = 94, pages_read = 48 }, + { end_page = 126, pages_read = 34 }, + { end_page = 194, pages_read = 70 }, + } + local expected = { 3, 88, 0, 3, 32, 68 } -- 每次都只是「比此前更远」的那一段;合计 194 + + local function history() + local entries = {} + for i, s in ipairs(sessions) do + -- UTC 01..06 点 → 本地(CST-8)09..14 点,同一本地的天。 + local utc = string.format("2026-10-10T%02d:00:00", i) + entries[#entries + 1] = { seriesId = 100, seriesFormat = 0, startTimeUtc = utc, chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = s.pages_read, startPage = 0, + endPage = s.end_page, totalPages = 194, startTimeUtc = utc } } } + end + return entries + end + + local day = dayTs(2026, 10, 10) + local function check(entries, label) + local result = Stats.fromHistory(entries, + { source_id = "kavita", fetched_at = 2000, volumes = { [100] = 1 } }) + local sum = 0 + local session_rows = 0 + for _idx, row in ipairs(result.rows) do + if row.record_type == "cloud_session" and row.stable_id == "100" then + session_rows = session_rows + 1 + end + end + Assert.eq(session_rows, #sessions, label .. ":每条有时长的会话各落一行,不多不少") + for i, want in ipairs(expected) do + local row = find(result.rows, "cloud_session", "100", hourTs(2026, 10, 10, 8 + i)) + Assert.not_nil(row, label .. ":第 " .. i .. " 条会话行") + Assert.eq(row.event_count, want, label .. ":第 " .. i .. " 条只算新推进的页数") + -- 重读(第 3 条 endPage 42 < 已到达 91)页数为 0,但 page 仍如实记 42。 + Assert.eq(row.page, sessions[i].end_page, label .. ":第 " .. i .. " 条 page 仍记 endPage") + Assert.eq(row.total_pages, 194, label .. ":第 " .. i .. " 条卷级总页数") + sum = sum + row.event_count + end + Assert.eq(sum, 194, label .. ":合计 = 读到的最远页码 = 总页数") + Assert.eq(find(result.rows, "day", "__kv:day:" .. day, day).event_count, 194, + label .. ":当天页数也是进度而不是页次") + end + + check(history(), "正序") + -- 回包可能是新→旧:按章起始时刻排序,结果不受遍历顺序影响。 + local reversed = {} + local forward = history() + for i = #forward, 1, -1 do reversed[#reversed + 1] = forward[i] end + check(reversed, "倒序") +end + +do + -- durationSeconds = 0 但有推进的章行照样发行:Kavita 的会话是「两次进度写入之间」, + -- 只写一次就是 0 秒,可推进的页数是真的(详情页「已读页数 / 上次阅读」靠它)。 + -- 它同时要参与进度序列与当天页数,否则这段跳读会从当天页面消失、 + -- 而后续会话又因为 reached 更高而少算,合计就对不上读到的最远页码。 + local d = dayTs(2026, 10, 11) + local result = Stats.fromHistory({ + { seriesId = 101, seriesFormat = 0, startTimeUtc = "2026-10-11T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 0, pagesRead = 20, startPage = 5, endPage = 60, + totalPages = 100, startTimeUtc = "2026-10-11T02:00:00" } } }, + { seriesId = 101, seriesFormat = 0, startTimeUtc = "2026-10-11T03:00:00", chapters = { + { chapterId = 1, durationSeconds = 120, pagesRead = 5, startPage = 60, endPage = 70, + totalPages = 100, startTimeUtc = "2026-10-11T03:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [101] = 1 } }) + + local jump = find(result.rows, "cloud_session", "101", hourTs(2026, 10, 11, 10)) + Assert.not_nil(jump, "零时长但有推进的章行也发行(页数是真推进)") + Assert.eq(jump.duration, 0) + Assert.eq(jump.event_count, 60) + local read = find(result.rows, "cloud_session", "101", hourTs(2026, 10, 11, 11)) + Assert.not_nil(read) + Assert.eq(read.event_count, 10, "跳读已把进度推到 60,本次只推进 10 页") + Assert.eq(read.page, 70) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 70, + "当天页数 = 最远页码(含零时长跳读推进的 60)") + + -- 登记身份用于清孤儿行:零时长条目照旧算见过(它上次可能留下过行)。 + Assert.contains(result.identities, "101") +end + +do + -- endPage 超过总页数(不同版本页数不一致)时钳到总页数:已读页数不可能超过总页数。 + local d = dayTs(2026, 10, 12) + local result = Stats.fromHistory({ + { seriesId = 102, seriesFormat = 1, startTimeUtc = "2026-10-12T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 40, startPage = 0, endPage = 250, + totalPages = 194, startTimeUtc = "2026-10-12T02:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [102] = 1 } }) + local row = find(result.rows, "cloud_session", "102", hourTs(2026, 10, 12, 10)) + Assert.not_nil(row) + Assert.eq(row.event_count, 194, "推进钳到总页数") + Assert.eq(row.total_pages, 194) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 194, "当天页数也被钳") + + -- 拿不到总页数(totalPages = 0 / 缺字段)时不假设上界:按 endPage 原样算。 + local unknown = Stats.fromHistory({ + { seriesId = 103, seriesFormat = 0, startTimeUtc = "2026-10-12T05:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 9, endPage = 77, + startTimeUtc = "2026-10-12T05:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [103] = 1 } }) + local no_total = find(unknown.rows, "cloud_session", "103", hourTs(2026, 10, 12, 13)) + Assert.not_nil(no_total) + Assert.eq(no_total.event_count, 77, "缺总页数就照 endPage 算") + Assert.eq(no_total.total_pages, 0) +end + +do + -- 多卷:每卷(stable_id = seriesId:chapterId)各自从 0 起算进度,互不影响; + -- 合计 = 各卷进度之和(≤ 各卷总页数之和)。 + local d = dayTs(2026, 10, 13) + local result = Stats.fromHistory({ + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 10, endPage = 10, totalPages = 40, + startTimeUtc = "2026-10-13T02:00:00" } } }, + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T03:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 20, endPage = 30, totalPages = 40, + startTimeUtc = "2026-10-13T03:00:00" } } }, + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T04:00:00", chapters = { + { chapterId = 2, durationSeconds = 60, pagesRead = 5, endPage = 5, totalPages = 60, + startTimeUtc = "2026-10-13T04:00:00" } } }, + { seriesId = 80, seriesFormat = 0, startTimeUtc = "2026-10-13T05:00:00", chapters = { + { chapterId = 2, durationSeconds = 60, pagesRead = 45, endPage = 50, totalPages = 60, + startTimeUtc = "2026-10-13T05:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [80] = 2 } }) + + Assert.eq(find(result.rows, "cloud_session", "80:1", hourTs(2026, 10, 13, 10)).event_count, 10) + Assert.eq(find(result.rows, "cloud_session", "80:1", hourTs(2026, 10, 13, 11)).event_count, 20) + Assert.eq(find(result.rows, "cloud_session", "80:2", hourTs(2026, 10, 13, 12)).event_count, 5) + Assert.eq(find(result.rows, "cloud_session", "80:2", hourTs(2026, 10, 13, 13)).event_count, 45) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 80, "10 + 20 + 5 + 45") + Assert.eq(find(result.rows, "cloud_session", "80:1", hourTs(2026, 10, 13, 10)).total_pages, 40) + Assert.eq(find(result.rows, "cloud_session", "80:2", hourTs(2026, 10, 13, 13)).total_pages, 60) +end + +do + -- epub / PDF 不受进度口径影响:pagesRead 照旧累加(重读同一页也算,这是「翻页数」语义), + -- 页坐标仍为 0。 + local d = dayTs(2026, 10, 14) + local result = Stats.fromHistory({ + { seriesId = 202, seriesFormat = 3, startTimeUtc = "2026-10-14T02:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 7, startPage = 15, endPage = 15, + totalPages = 22, startTimeUtc = "2026-10-14T02:00:00" } } }, + { seriesId = 202, seriesFormat = 3, startTimeUtc = "2026-10-14T03:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 7, startPage = 15, endPage = 15, + totalPages = 22, startTimeUtc = "2026-10-14T03:00:00" } } }, + -- PDF(4)同样不是渲染页,口径与 epub 一致。 + { seriesId = 203, seriesFormat = 4, startTimeUtc = "2026-10-14T04:00:00", chapters = { + { chapterId = 1, durationSeconds = 60, pagesRead = 4, endPage = 99, + totalPages = 120, startTimeUtc = "2026-10-14T04:00:00" } } }, + }, { source_id = "kavita", fetched_at = 2000, volumes = { [202] = 1, [203] = 1 } }) + + local first = find(result.rows, "cloud_session", "202", hourTs(2026, 10, 14, 10)) + local again = find(result.rows, "cloud_session", "202", hourTs(2026, 10, 14, 11)) + Assert.eq(first.event_count, 7, "epub 仍是 pagesRead") + Assert.eq(again.event_count, 7, "epub 重读不折成 0(不是进度口径)") + Assert.eq(first.page, 0) + Assert.eq(first.total_pages, 0) + local pdf = find(result.rows, "cloud_session", "203", hourTs(2026, 10, 14, 12)) + Assert.eq(pdf.event_count, 4, "PDF 仍是 pagesRead") + Assert.eq(pdf.page, 0) + Assert.eq(pdf.total_pages, 0) + Assert.eq(find(result.rows, "day", "__kv:day:" .. d, d).event_count, 18, "7 + 7 + 4") +end diff --git a/tests/kavita/tasks_e2e_spec.lua b/tests/kavita/tasks_e2e_spec.lua new file mode 100644 index 0000000..00ba240 --- /dev/null +++ b/tests/kavita/tasks_e2e_spec.lua @@ -0,0 +1,282 @@ +--[[-- +端到端:卷列表里「缓存整部」→ 真实缓存适配层 → 真实后台任务队列 → 顶栏读到的任务 → 收尾提示。 + +用假的 kamare 模块(真缓存适配层 + 真队列 + 真卷列表 + 真轮询),只把「下载」外包出去, +其余全走产品代码:这是跨仓 E2E 在离线环境里能做到的最大范围(模拟器 / 真机另做手工冒烟)。 + +@module tests.moonsource_kavita.tasks_e2e_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field, redundant-parameter + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") +local Themed = require("support.theme_stubs") +Themed.install() +-- 真实的卷列表与二级菜单:Themed 的 list 桩会把 item.widget 丢掉,也就点不了行。 +package.preload["ui.themes.widgets.list"] = nil +package.loaded["ui.themes.widgets.list"] = nil + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") + +-- 源配置:真 cache.lua 只读 base_url / api_key;其余键仍走 Kit 的主题设置桩。 +local cfg = { base_url = "http://kavita.local", api_key = "key" } +package.preload["utils.settings"] = function() + return { + get = function(owner) + local name = owner:match("[^.]+$") + if name == "ui" then return Kit.display end + return Kit.sections[name] + end, + getSource = function() return cfg end, + saveSource = function() end, + } +end +package.preload["utils.log"] = function() + return { info = function() end, warn = function() end, err = function() end, dbg = function() end } +end +package.preload["ui/network/manager"] = function() + return { isConnected = function() return true end } +end +package.preload["ui.guard"] = function() + return { + call = function(_label, fn, ...) return fn(...) end, + wrap = function(_label, fn) return fn end, + } +end + +-- 假 kamare:队列与章状态都在内存里,由用例推进。 +local statuses, queue = {}, {} +--- 重置假 kamare 的队列与章状态。 +local function resetKamare() + statuses, queue = {}, {} + queue = { state = "idle", entries = {} } +end +local kamare = { + api_version = 1, + capabilities = { + status = true, resume_page = true, queue = true, queue_control = true, + index = true, enqueue = true, delete = true, estimate = true, server = true, + }, +} +function kamare.register_server() return "server-key" end +function kamare.status(_base_url, chapter_id) return statuses[tostring(chapter_id)] end +function kamare.queue_state() return queue end +function kamare.estimate(_base_url, entries) + return { ok = true, chapters = #entries, bytes = #entries * 1024 * 1024, + available = 4096 * 1024 * 1024 } +end +function kamare.enqueue(_base_url, entries) + for _idx, entry in ipairs(entries) do + queue.entries[tostring(entry.chapterId)] = { chapterId = entry.chapterId, state = "queued" } + end + queue.state = "downloading" + return true, nil, { chapters = #entries } +end +package.loaded["kamarecache"] = kamare + +--- kamare 开始下某一卷。 +local function startChapter(id) + queue.entries[tostring(id)] = { chapterId = id, state = "downloading" } + queue.current_chapter_id = id + queue.state = "downloading" +end + +--- kamare 下完某一卷:章状态变 complete,队列项消失。 +local function finishChapter(id) + statuses[tostring(id)] = { state = "complete", bytes = 1024 * 1024 } + queue.entries[tostring(id)] = nil + queue.current_chapter_id = nil + if next(queue.entries) == nil then queue.state = "idle" end +end + +package.preload["moonsource_kavita.cache"] = function() + return dofile(PLUGIN .. "/cache.lua") +end +package.preload["moonsource_kavita.cache_task"] = function() + return dofile(PLUGIN .. "/cache_task.lua") +end +package.preload["moonsource_kavita.volume_list"] = function() + return dofile(PLUGIN .. "/volume_list.lua") +end + +local Cache = require("moonsource_kavita.cache") +local Tasks = require("workers.tasks") +local VolumeList = require("moonsource_kavita.volume_list") + +local series = { stable_id = "900", title = "测试系列" } +local function entry(id, title, pages_read) + return { chapterId = id, volumeId = id, seriesId = 900, libraryId = 1, format = 1, + title = title, pages = 100, pagesRead = pages_read or 0 } +end +local toc = { entry(601, "第 1 卷", 100), entry(602, "第 2 卷", 40), entry(603, "第 3 卷", 0) } + +--- Kit 的 unschedule 只记录、不从已排列表里删;真实 UIManager 会删,这里按记录过滤。 +---@param item table +---@return boolean +local function alive(item) + for _idx, fn in ipairs(Kit.unscheduled) do + if fn == item.fn then return false end + end + return true +end + +--- 结清队列的变更拍(pause_auto_suspend)。 +local function changes() + while true do + local fired = false + for index, item in ipairs(Kit.scheduled) do + if item.delay < 1 and alive(item) then + table.remove(Kit.scheduled, index) + item.fn() + fired = true + break + end + end + if not fired then return end + end +end + +--- 跑一拍所有 1 秒以上的定时器(页面轮询 + 后台任务轮询各一拍)。 +local function round() + local now, rest = {}, {} + for _idx, item in ipairs(Kit.scheduled) do + if item.delay >= 1 and alive(item) then now[#now + 1] = item else rest[#rest + 1] = item end + end + Kit.scheduled = rest + for _idx, item in ipairs(now) do item.fn() end +end + +--- 顶栏「后台任务」的读数(与 desktop/topbar 同一口径:running / 未结束总数)。 +local function topbarText() + local list = Tasks.tasks() + if #list == 0 then return "空闲" end + local running = 0 + for _idx, task in ipairs(list) do + if task.state == "running" then running = running + 1 end + end + return running .. "/" .. #list +end + +---@param list table +---@param widget table +local function tap(list, widget) + local size = widget.dimen + local ges = Kit.tap(size.x + math.floor(size.w / 2), size.y + math.floor(size.h / 2)) + ges.ges = "tap" + list:handleEvent(require("ui/event"):new("Gesture", ges)) +end + +--- 打开卷列表并走「缓存整部」(菜单第一项)。第 1 卷已缓存,本批只下 2 卷。 +local function openAndCacheAll() + statuses["601"] = { state = "complete", bytes = 1024 } + local list = assert(VolumeList.pick(series, toc, function() end)) + list:show() + list:paintTo(Kit.canvas(), 0, 0) + list.left_callback() + local menu = Kit.shown[#Kit.shown] + menu:paintTo(Kit.canvas(), 0, 0) + local rows = Kit.taps(menu) + Assert.is_true(#rows >= 1, "有「缓存整部」") + tap(menu, rows[1]) + local confirm = Themed.last("confirm") + Assert.not_nil(confirm, "确认框") + confirm.ok_callback() + return list +end + +local function cleanup() + for _idx, item in ipairs(Tasks.tasks()) do + local live = Tasks.get(item.key) + if live then live.cancel() end + end + changes() + Kit.scheduled, Kit.unscheduled = {}, {} + Themed.made = {} + Cache.reset() + resetKamare() +end + +-- 页面开着:入队 → 顶栏看得到 → 进度跟着 kamare 走 → 页面自己的进度框收尾(只提示一次)。 +do + cleanup() + local list = openAndCacheAll() + + local tracked = Tasks.tasks() + Assert.len(tracked, 1, "缓存进了后台任务队列") + Assert.eq(tracked[1].kind, "cache") + Assert.eq(tracked[1].title, "测试系列") + Assert.eq(topbarText(), "1/1", "顶栏读到「1/1」") + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "缓存期间不自动休眠") + + startChapter(602) + round() + Assert.eq(Tasks.tasks()[1].text, "第 2 卷", "任务说明行跟 kamare 的当前卷") + Assert.eq(Tasks.tasks()[1].total, 2, "只数本批(601 已缓存)") + + finishChapter(602) + startChapter(603) + round() + Assert.eq(Tasks.tasks()[1].count, 1, "下完一卷进度 +1") + + finishChapter(603) + round() + Assert.len(Tasks.tasks(), 0, "全部落地后离开队列") + Assert.eq(topbarText(), "空闲") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "结束放行自动休眠") + local toasts = Themed.all("toast") + Assert.eq(#toasts, 1, "页面进度框收尾,只提示一次") + Assert.eq(toasts[1].text, "已缓存 2 卷") + list:close() +end + +-- 页面提前关掉:后台任务继续跑,完成时由任务提示(不再有页面轮询)。 +do + cleanup() + local list = openAndCacheAll() + startChapter(602) + round() + list:close() + Assert.is_true(#Kit.unscheduled > 0, "关页撤掉页面轮询") + + finishChapter(602) + startChapter(603) + round() + Assert.eq(Tasks.tasks()[1].count, 1, "关页后任务仍在推进") + + finishChapter(603) + round() + Assert.len(Tasks.tasks(), 0) + local toasts = Themed.all("toast") + Assert.eq(#toasts, 1, "关页后由任务报完成") + Assert.eq(toasts[1].text, "已缓存 2 卷") + Assert.eq(topbarText(), "空闲") +end + +-- 队列因空间不足暂停:任务留在列表里、报暂停原因、不再压制自动休眠;恢复后继续。 +do + cleanup() + local list = openAndCacheAll() + startChapter(602) + round() + queue.state = "paused" + queue.pause_reason = "low_space" + round() + Assert.eq(Tasks.tasks()[1].text, "空间不足,已暂停") + changes() + Assert.is_false(require("pluginshare").pause_auto_suspend, "暂停时允许自动休眠") + + queue.state = "downloading" + queue.pause_reason = nil + round() + changes() + Assert.is_true(require("pluginshare").pause_auto_suspend, "恢复后继续撑住") + finishChapter(602) + finishChapter(603) + round() + Assert.len(Tasks.tasks(), 0, "恢复后照常收尾") + list:close() +end diff --git a/tests/kavita/volume_list_spec.lua b/tests/kavita/volume_list_spec.lua new file mode 100644 index 0000000..53845f9 --- /dev/null +++ b/tests/kavita/volume_list_spec.lua @@ -0,0 +1,1213 @@ +--[[-- +Kavita 卷列表:真实 list 的行尾控件命中(04 A9)、状态字优先级、批量预设 +(整部 / 从当前进度 / 后 N 卷,默认 3)、删除保护、暂停 / 恢复与进度框收尾。 + +真实 list 与 Kit 一起用:A9 的「点图标不关窗」只能靠真行 / 真按钮的事件顺序证明。 +Themed 只负责记录弹窗参数;装完把它的 list 桩摘掉,require 真组件。 + +@module tests.moonsource_kavita.volume_list_spec +--]] +---@diagnostic disable: undefined-field, missing-fields, inject-field + +local Assert = require("support.assert") +local Config = require("support.config") +local Kit = require("support.widget_stubs") +Kit.install("paper") + +local Themed = require("support.theme_stubs") +Themed.install() +-- 真实的 list:Themed 的桩会把 item.widget 丢掉,A9 就无从验证。 +package.preload["ui.themes.widgets.list"] = nil +package.loaded["ui.themes.widgets.list"] = nil + +-- 缓存层另有 cache_spec;这里只关心 UI 传了什么、显示了什么。 +package.loaded["utils.log"] = { + info = function() end, warn = function() end, err = function() end, dbg = function() end, +} +local offline = false +local local_progress = {} +local progress_list_calls = 0 +package.loaded["ui/network/manager"] = { isConnected = function() return not offline end } +-- 本地卷进度(ProgressDB):卷行在阅读器关闭时写回,比 toc 快照新。 +package.loaded["book.progress_db"] = { + get = function(_source_id, stable_id) return local_progress[stable_id] end, + list = function(_source_id, series_id) + progress_list_calls = progress_list_calls + 1 + local out = {} + local prefix = tostring(series_id) .. ":" + for stable, row in pairs(local_progress) do + if stable:sub(1, #prefix) == prefix then out[stable] = row end + end + return out + end, +} +package.loaded["source.registry"] = { + resolve = function() + return { coverRequest = function() end } + end, +} + +local PLUGIN = (debug.getinfo(1, "S").source:match("^@(.-)/tests/") .. "/moonsource-kavita.koplugin/moonsource_kavita") +local RealCache = dofile(PLUGIN .. "/cache.lua") + +local st, calls = {}, {} +--- 后台任务句柄的记录(stub 与 reset 共用同一个 upvalue)。 +local tracked = {} +local function reset(overrides) + calls = { enqueue = {}, delete = {}, retry = {}, pause = 0, resume = 0, resume_page = 0, chapters = 0 } + local_progress = {} + progress_list_calls = 0 + tracked = {} + st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, queue_control = true, + enqueue = true, delete = true, estimate = true, + } } + st.queue = { state = "idle", entries = {}, percent = 0, bytes_done = 0, bytes_total = 0 } + st.queue_code = nil + st.statuses, st.resumes = {}, {} + st.plan = nil + st.open_chapter = nil + st.estimate = { chapters = 1, bytes = 100 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } + st.enqueue_ok, st.enqueue_code, st.enqueue_message, st.enqueue_detail = true, nil, nil, nil + st.delete_ok, st.delete_code, st.delete_message = true, nil, nil + st.pause_ok, st.resume_ok, st.retry_ok = true, true, true + st.pause_reason = "user" + st.retry_code = nil + st.pause_code = nil + st.resume_code = nil + offline = false + for key, value in pairs(overrides or {}) do st[key] = value end +end + +local Cache = setmetatable({}, { __index = RealCache }) +function Cache.probe() return st.probe end +function Cache.queueState() return st.queue, st.queue_code end +function Cache.status(chapter_id) return st.statuses[tostring(chapter_id)] end +function Cache.resumePage(chapter_id) + calls.resume_page = calls.resume_page + 1 + return st.resumes[tostring(chapter_id)] +end +function Cache.isChapterOpen(chapter_id) + return st.open_chapter ~= nil and tostring(st.open_chapter) == tostring(chapter_id) +end +function Cache.estimate(entries) + calls.estimate = entries + return st.estimate +end +function Cache.enqueue(entries) + calls.enqueue[#calls.enqueue + 1] = entries + if st.enqueue_ok then return true end + return nil, st.enqueue_code, st.enqueue_message, st.enqueue_detail +end +function Cache.delete(ids) + calls.delete[#calls.delete + 1] = ids + if st.delete_ok then + -- 真 kamare 删完 index 里就没有这一章了:刷新后行要变回「未缓存 / 已读」。 + local wanted = {} + for _idx, id in ipairs(ids) do + wanted[tostring(id)] = true + st.statuses[tostring(id)] = nil + end + if st.plan then + local kept = {} + for _idx, item in ipairs(st.plan) do + if not wanted[tostring(item.chapterId)] then kept[#kept + 1] = item end + end + st.plan = kept + end + + return true + end + return nil, st.delete_code, st.delete_message +end +function Cache.chapters(series_id) + calls.chapters = calls.chapters + 1 + calls.chapters_series = series_id + return st.plan +end +function Cache.queuePause() + calls.pause = calls.pause + 1 + if st.pause_ok then + st.queue.state = "paused" + st.queue.pause_reason = st.pause_reason or "user" + end + return st.pause_ok, st.pause_code +end +function Cache.queueResume() + calls.resume = calls.resume + 1 + if st.resume_ok then + st.queue.pause_reason = nil + st.queue.state = "idle" + end + return st.resume_ok, st.resume_code +end +function Cache.queueRetry(ids) + calls.retry[#calls.retry + 1] = ids + return st.retry_ok, st.retry_code +end +package.preload["moonsource_kavita.cache"] = function() return Cache end +-- 后台任务登记:这里只记调用与静音状态;真实轮询见 cache_task_spec 与 tasks_e2e_spec。 +package.preload["moonsource_kavita.cache_task"] = function() + local CacheTask = dofile(PLUGIN .. "/cache_task.lua") + CacheTask.track = function(opts) + local handle = { opts = opts, adds = {} } + handle.mute = function(value) handle.muted = value ~= false end + handle.add = function(entries) handle.adds[#handle.adds + 1] = entries end + tracked[#tracked + 1] = handle + return handle + end + return CacheTask +end +package.preload["moonsource_kavita.volume_list"] = function() + return dofile(PLUGIN .. "/volume_list.lua") +end +package.preload["moonsource_kavita.busy"] = function() + return dofile(PLUGIN .. "/busy.lua") +end + +local VolumeList = require("moonsource_kavita.volume_list") + +---@param id integer +---@param title string +---@param pages integer +---@param read integer +---@return table +local function entry(id, title, pages, read) + return { chapterId = id, volumeId = id, seriesId = 900, libraryId = 1, format = 1, + title = title, pages = pages, pagesRead = read or 0 } +end + +local toc = { + entry(601, "第 1 卷", 100, 100), + entry(602, "第 2 卷", 100, 40), + entry(603, "第 3 卷", 100, 0), +} +local series = { source_id = "kavita", stable_id = "900", title = "测试系列" } + +--- 子串断言:Assert.contains 只认数组,文案用这个。 +---@param haystack string +---@param needle string +---@param msg string|nil +local function textContains(haystack, needle, msg) + Assert.is_true(type(haystack) == "string" and haystack:find(needle, 1, true) ~= nil, + (msg or "text") .. ":" .. needle .. " 不在 " .. tostring(haystack)) +end + +--- 打开卷列表;返回 list、选中回调的接收表。 +---@param volumes table[]|nil 缺省用共享的 toc(全读退化等用例换一份目录) +---@return table, table +local function open(volumes, opts) + local picked = {} + local list = assert(VolumeList.pick(series, volumes or toc, + function(value) picked.value = value end, opts)) + list:show() + list:paintTo(Kit.canvas(), 0, 0) + return list, picked +end + +--- 所有行尾按钮(排除标题栏的 left / close)。 +---@param list table +---@return table[] +local function tails(list) + local first = Kit.taps(list)[1] + local top = first and first.dimen.y or 0 + local out = {} + for _idx, button in ipairs(Kit.buttons(list)) do + if button.dimen.y >= top + and (button.icon == "download" or button.icon == "delete" or button.icon == "refresh" + or button.icon == "pause" or button.icon == "play_arrow") then + out[#out + 1] = button + end + end + return out +end + +--- 按 04 A9 的路径点一个控件:坐标落在按钮上,事件从窗口一路下发。 +---@param list table +---@param widget table +local function tap(list, widget) + local size = widget.dimen + local ges = Kit.tap(size.x + math.floor(size.w / 2), size.y + math.floor(size.h / 2)) + ges.ges = "tap" + list:handleEvent(require("ui/event"):new("Gesture", ges)) +end + +--- 按行标题找控件:续读卡也在控件树里,固定下标会被它挤偏。 +---@param list table +---@param title string +---@return table|nil +local function findRow(list, title) + for _idx, w in ipairs(Kit.taps(list)) do + if w.row_title == title then return w end + end +end + +--- 按行标题点按。 +---@param list table +---@param title string +local function tapRow(list, title) + local row = findRow(list, title) + if not row then error("row not found: " .. tostring(title)) end + tap(list, row) +end + + +--- 这个窗口被 UIManager 关过吗(真实组件不写 `.closed`,只能看桩的关闭记录)。 +---@param widget table +---@return boolean +local function wasClosed(widget) + for _idx, w in ipairs(Kit.closed) do + if w == widget then return true end + end + return false +end + +--- 标题栏左钮 → 二级菜单;返回菜单控件(真实 list,与卷列表分开的窗口)。 +---@param list table +---@return table +local function openMenu(list) + local before = #Kit.shown + list.left_callback() + Assert.is_true(#Kit.shown > before, "左钮弹二级菜单") + local menu = Kit.shown[#Kit.shown] + Assert.is_true(menu ~= list, "菜单不是卷列表本身") + menu:paintTo(Kit.canvas(), 0, 0) + return menu +end + +--- 菜单第 index 项;越界即断言失败。 +---@param menu table +---@param index integer +local function chooseMenu(menu, index) + local rows = Kit.taps(menu) + Assert.is_true(#rows >= index, "菜单有第 " .. index .. " 项") + tap(menu, rows[index]) +end + +--- 标题栏左钮 → 「缓存整部」(菜单第一项)。 +---@param list table +local function batchAll(list) + chooseMenu(openMenu(list), 1) +end + +--- 入队对象的章 id,逗号拼接:断言「选了哪几卷」。 +---@param entries table[]|nil +---@return string +local function idsText(entries) + local out = {} + for _idx, entry in ipairs(entries or {}) do out[#out + 1] = entry.chapterId end + return table.concat(out, ",") +end + +-- A9:点行尾按钮被按钮吃掉,不关窗、不选中,只弹该卷的确认框。 +reset() +st.statuses["601"] = { state = "complete", bytes = 80 * 1024 * 1024 } +local list, picked = open() +local delete_buttons = {} +for _idx, button in ipairs(tails(list)) do + if button.icon == "delete" then delete_buttons[#delete_buttons + 1] = button end +end +Assert.len(delete_buttons, 1, "只有已缓存的第 1 卷有删除按钮") +local closed_before = #Kit.closed +tap(list, delete_buttons[1]) +Assert.eq(#Kit.closed, closed_before, "点行尾按钮不关窗") +Assert.is_nil(picked.value, "点行尾按钮不触发行选中") +local confirm = Themed.last("confirm") +Assert.not_nil(confirm, "删除走确认框") +textContains(confirm.text, "将释放") +textContains(confirm.text, "离线不可读") +Assert.eq(confirm.title, "删除缓存") +confirm.ok_callback() +Assert.eq(calls.delete[1][1], 601, "只删这一卷") + +-- 行状态字:已读 · 已缓存 / 在读 / 未缓存;图标各归各位。 +st.statuses["601"] = { state = "complete", bytes = 80 * 1024 * 1024 } +st.resumes["602"] = { page = 41, status = "pending" } +list, picked = open() +local text = table.concat(Kit.texts(list), "\n") +textContains(text, "已读 · 已缓存") +textContains(text, "在读 · 待同步") +textContains(text, "未缓存") +local icons = {} +for _idx, button in ipairs(tails(list)) do icons[#icons + 1] = button.icon end +Assert.eq(table.concat(icons, ","), "delete,download,download") + +-- 点标题区域仍然是选中(关窗后回调)。 +tapRow(list, "第 2 卷") +Assert.eq(picked.value and picked.value.chapterId, 602) + +reset() +st.statuses["601"] = { state = "stale", bytes = 1 } +st.statuses["602"] = { state = "complete", bytes = 1 } +st.statuses["603"] = { state = "complete", bytes = 1 } +list = open() +text = table.concat(Kit.texts(list), "\n") +textContains(text, "已读 · 已缓存") +textContains(text, "在读 · 已缓存") +textContains(text, "已缓存") +Assert.eq(#tails(list), 3) + +-- 打开列表时队列已经在跑(不是本页发起的批次):也要排拍刷新, +-- 不能停在打开那一瞬的「下载中 32%」。 +reset() +Kit.scheduled = {} +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 32, bytes_total = 100 } }, bytes_done = 32, bytes_total = 100 } +list = open() +textContains(table.concat(Kit.texts(list), "\n"), "下载中 32%", "打开时看到的是队列快照") +local poll +for index, item in ipairs(Kit.scheduled) do + if item.delay == 1 then poll = item; table.remove(Kit.scheduled, index); break end +end +Assert.not_nil(poll, "队列在跑时打开列表也要排 1 秒轮询") +st.queue = { state = "idle", entries = {} } +st.statuses["602"] = { state = "complete", bytes = 1 } +poll.fn() +textContains(table.concat(Kit.texts(list), "\n"), "在读 · 已缓存", "收尾后行就地刷新") +local repoll = false +for _idx, item in ipairs(Kit.scheduled) do if item.delay == 1 then repoll = true end end +Assert.is_false(repoll, "队列停了就不再多排拍") + +-- 标题栏左钮=批量预设菜单(04 A9 的 C 变体):整部 / 未读 / 后 N 卷。 +-- 菜单是独立的 list 窗口,点菜单行不会被当成选卷;「缓存整部」仍然只选未缓存 +-- (跳过已缓存 / 排队中),先 estimate 再确认。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [603] = { chapterId = 603, state = "downloading", + bytes_done = 50, bytes_total = 100 } }, bytes_done = 50, bytes_total = 100 } +st.estimate = { chapters = 1, bytes = 120 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } +list, picked = open() +local title = Kit.buttons(list)[1] +Assert.eq(title.icon, "download", "标题栏左钮是下载图标") +Assert.is_true(title.dimen.y < Kit.taps(list)[1].dimen.y, "左钮在标题栏里,不是行尾") +local menu = openMenu(list) +local menu_items = {} +for _idx, item in ipairs(menu.items) do menu_items[#menu_items + 1] = item.text end +Assert.eq(menu.title, "批量操作", "菜单标题") +Assert.eq(table.concat(menu_items, "|"), "缓存整部|缓存未读|缓存后 N 卷…", "菜单三项与顺序") +Assert.is_nil(picked.value, "开菜单不选卷") +chooseMenu(menu, 1) +Assert.is_true(wasClosed(menu), "选完关菜单") +Assert.is_false(wasClosed(list), "点菜单不关卷列表") +Assert.is_nil(picked.value, "点菜单行不选卷") +Assert.len(calls.estimate, 1, "先估算") +Assert.eq(calls.estimate[1].chapterId, 602, "只估算未缓存的第 2 卷") +confirm = Themed.last("confirm") +Assert.not_nil(confirm, "估算通过后弹确认框") +Assert.eq(confirm.title, "缓存这一卷") +textContains(confirm.text, "第 2 卷") +textContains(confirm.text, "预计占用 120.0 MB(峰值)") +textContains(confirm.text, "设备可用 2000.0 MB") +textContains(confirm.text, "完成后剩余 1880.0 MB") +Assert.eq(confirm.ok_text, "开始缓存") +confirm.ok_callback() +Assert.len(calls.enqueue, 1) +Assert.eq(calls.enqueue[1][1].chapterId, 602) +local progress = Themed.last("progress_dialog") +Assert.not_nil(progress, "入队后开进度框") +Assert.eq(progress.title, "正在缓存") +Assert.eq(progress.cancel_text, "暂停", "按钮是暂停,不是取消") +Assert.not_nil(progress.on_cancel) +Assert.not_nil(progress.on_background, "后台运行") +Assert.is_true(#calls.retry == 0, "没有失败项就不调 queue_retry") + +-- 预设「缓存未读」:没读完的卷都算(含正在读的一卷),已读跳过; +-- 已缓存 / 已排队照旧跳过,也不逐卷调 resume_page。 +local preset_toc = { + entry(701, "第 1 卷", 100, 100), + entry(702, "第 2 卷", 100, 40), + entry(703, "第 3 卷", 100, 0), + entry(704, "第 4 卷", 100, 0), +} +reset() +st.statuses["703"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [704] = { chapterId = 704, state = "downloading", + bytes_done = 10, bytes_total = 100 } }, bytes_done = 10, bytes_total = 100 } +list = open(preset_toc) +local probes = calls.resume_page +menu = openMenu(list) +chooseMenu(menu, 2) +Assert.eq(idsText(calls.estimate), "702", "在读的第 2 卷算未读:跳过已读完 / 已缓存 / 已排队") +Assert.eq(calls.resume_page, probes, "预设不逐卷调 resume_page") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存这一卷") +textContains(confirm.text, "第 2 卷") +confirm.ok_callback() +Assert.eq(idsText(calls.enqueue[1]), "702", "只入队选中的未缓存卷") +Assert.eq(#calls.retry, 0) + +-- 全部都读完:没有未读卷,只提示,不再退化成整部。 +local all_read = { + entry(711, "第 1 卷", 100, 100), + entry(712, "第 2 卷", 100, 100), + entry(713, "第 3 卷", 100, 100), +} +reset() +local read_list = open(all_read) +local read_menu = openMenu(read_list) +local all_read_confirms = #Themed.all("confirm") +chooseMenu(read_menu, 2) +Assert.is_nil(calls.estimate, "全部已读不估算") +textContains(Themed.last("toast").text, "没有未读的卷") +Assert.eq(#Themed.all("confirm"), all_read_confirms, "全部已读不弹确认") + +-- 预设也没有对象:与「缓存整部」同一条 toast,不弹框。 +reset() +for _idx, item_entry in ipairs(preset_toc) do + st.statuses[tostring(item_entry.chapterId)] = { state = "complete", bytes = 1 } +end +list = open(preset_toc) +local no_object_confirms = #Themed.all("confirm") +menu = openMenu(list) +chooseMenu(menu, 2) +Assert.is_nil(calls.estimate, "没有对象不估算") +textContains(Themed.last("toast").text, "全部已缓存") +Assert.eq(#Themed.all("confirm"), no_object_confirms, "空选择不弹框") + +-- toc 是带 TTL 的快照:刚读完 / 刚开读的卷在服务端可能还是旧进度(大剑 Vol.17 的现场: +-- toc 仍是 117/196,本地已经 196/196)。本地卷进度(ProgressDB)比快照新,必须一起算, +-- 否则「后 N 卷」会从已经读完的卷重新缓存。 +local stale_toc = { + entry(801, "第 1 卷", 196, 196), + entry(802, "第 2 卷", 196, 117), -- toc 还是 60%,本地已读完 + entry(803, "第 3 卷", 196, 0), -- toc 没有进度,本地刚开读 + entry(804, "第 4 卷", 196, 0), +} +reset() +local_progress["900:802"] = { fraction = 1.0, page = 196, total_pages = 196 } +local_progress["900:803"] = { fraction = 0.015, page = 3, total_pages = 196 } +list = open(stale_toc) +local rows_text = table.concat(Kit.texts(list), "\n") +textContains(rows_text, "第 2 卷", "行还在") +Assert.is_true(rows_text:find("已读", 1, true) ~= nil, "本地读完的卷显示已读") +local stale_menu = openMenu(list) +chooseMenu(stale_menu, 2) +Assert.eq(idsText(calls.estimate), "803,804", "已读完的卷跳过,在读的 803 仍算未读") +Assert.is_true(rows_text:find("在读", 1, true) ~= nil, "本地刚开读的卷显示在读") + +-- 「缓存未读」不是连续后缀:中间已读的卷不打包,正在读的卷照收。 +local unread_toc = { + entry(721, "第 1 卷", 100, 100), -- 已读 + entry(722, "第 2 卷", 100, 30), -- 在读:算未读 + entry(723, "第 3 卷", 100, 0), -- 未读 + entry(724, "第 4 卷", 100, 0), -- 未读但已缓存 + entry(725, "第 5 卷", 100, 100), -- 已读(乱序,排在后面) + entry(726, "第 6 卷", 100, 0), -- 未读 +} +reset() +st.statuses["724"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 3, bytes = 30 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } +list = open(unread_toc) +menu = openMenu(list) +chooseMenu(menu, 2) +Assert.eq(idsText(calls.estimate), "722,723,726", "在读算未读;已读与已缓存跳过") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存 3 卷") +textContains(confirm.text, "第 2 卷") +Assert.is_true(not confirm.text:find("第 5 卷", 1, true), "后面已读的卷不打包进来") + +-- 预设「缓存后 N 卷…」:默认 3(不足 3 取剩余);0 / 非数字不动作;N 超过剩余卷数时截断。 +reset() +list = open(preset_toc) +menu = openMenu(list) +chooseMenu(menu, 3) +local input = Themed.last("spin") +Assert.not_nil(input, "后 N 卷走主题加减控件,不是文本输入") +Assert.eq(input.title, "缓存后 N 卷") +Assert.eq(input.fields[1].label, "卷数") +Assert.eq(input.fields[1].min, 1, "最少 1 卷") +Assert.eq(input.fields[1].max, 3, "最多到末卷(进度起点之后还有 3 卷)") +Assert.eq(input.fields[1].value, 3, "默认 3 卷(正好等于剩余卷数)") +Assert.is_nil(calls.estimate, "选之前不估算") +input.callback(1) +Assert.eq(idsText(calls.estimate), "702", "N=1 从进度起点取一卷") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存这一卷") +st.estimate = { chapters = 3, bytes = 10 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } +input.callback(9) +Assert.eq(idsText(calls.estimate), "702,703,704", "N 超过剩余卷数时截断到末卷") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "缓存 3 卷") +confirm.ok_callback() +Assert.eq(idsText(calls.enqueue[1]), "702,703,704", "三个入口共用同一确认与入队") +textContains(Themed.last("progress_dialog").text, "1/3 卷", "三个入口共用同一进度框") +Assert.eq(#calls.retry, 0) + +-- 剩余不足 3 卷:默认值取剩余卷数。 +local short_toc = { + entry(741, "第 1 卷", 100, 100), + entry(742, "第 2 卷", 100, 40), + entry(743, "第 3 卷", 100, 0), +} +reset() +list = open(short_toc) +menu = openMenu(list) +chooseMenu(menu, 3) +local short_input = Themed.last("spin") +Assert.eq(short_input.fields[1].max, 2, "剩 2 卷") +Assert.eq(short_input.fields[1].value, 2, "不足 3 卷时默认取剩余卷数") + +-- 「后 N 卷」同样跳过已缓存 / 已排队,不重复入队。 +reset() +st.queue = { state = "downloading", entries = { [703] = { chapterId = 703, state = "downloading", + bytes_done = 10, bytes_total = 100 } }, bytes_done = 10, bytes_total = 100 } +list = open(preset_toc) +menu = openMenu(list) +chooseMenu(menu, 3) +Themed.last("spin").callback(9) +Assert.eq(idsText(calls.estimate), "702,704", "已排队的卷不再入队") + +-- 「后 N 卷」没有对象:同一条 toast。 +reset() +for _idx, item_entry in ipairs(preset_toc) do + st.statuses[tostring(item_entry.chapterId)] = { state = "complete", bytes = 1 } +end +list = open(preset_toc) +local empty_confirms = #Themed.all("confirm") +menu = openMenu(list) +chooseMenu(menu, 3) +Themed.last("spin").callback(2) +Assert.is_nil(calls.estimate, "没有对象不估算") +textContains(Themed.last("toast").text, "全部已缓存") +Assert.eq(#Themed.all("confirm"), empty_confirms, "空选择不弹框") + +-- 全部已缓存:不估算,直接 toast。 +reset() +for _idx, item_entry in ipairs(toc) do + st.statuses[tostring(item_entry.chapterId)] = { state = "complete", bytes = 1 } +end +list = open() +local confirms = #Themed.all("confirm") +batchAll(list) +Assert.is_nil(calls.estimate, "没有对象不估算") +textContains(Themed.last("toast").text, "全部已缓存") +Assert.eq(#Themed.all("confirm"), confirms, "全部已缓存不弹框") + +-- estimate 说没事可做:toast,不弹框。 +reset() +st.estimate = { chapters = 0, bytes = 0, available = 1, ok = false, reason = "nothing_to_do" } +list = open() +batchAll(list) +textContains(Themed.last("toast").text, "全部已缓存或正在下载") +Assert.eq(#Themed.all("confirm"), confirms, "没事可做只 toast") + +-- 空间不足:确认框就地换成「空间不足」,主按钮只 toast,不入队。 +reset() +st.estimate = { chapters = 3, bytes = 849 * 1024 * 1024, available = 480 * 1024 * 1024, ok = false, reason = "space" } +list = open() +batchAll(list) +confirm = Themed.last("confirm") +Assert.not_nil(confirm) +textContains(confirm.text, "空间不足:需要 849.0 MB,可用 480.0 MB") +Assert.eq(confirm.ok_text, "去清理空间") +confirm.ok_callback() +Assert.len(calls.enqueue, 0, "空间不足不入队") +textContains(Themed.last("toast").text, "空间不足") + +-- 低水位:同样不给「开始缓存」。 +reset() +st.estimate = { chapters = 3, bytes = 1, available = 400 * 1024 * 1024, ok = false, reason = "low_water" } +list = open() +batchAll(list) +confirm = Themed.last("confirm") +textContains(confirm.text, "可用空间不足(剩余 400.0 MB)") +Assert.eq(confirm.ok_text, "去清理空间") + +-- 队列已暂停:确认框要说清「开始缓存会恢复整个队列」(07 A5)。 +reset() +st.queue = { state = "paused", pause_reason = "user", entries = {}, bytes_done = 0, bytes_total = 0 } +st.estimate = { chapters = 3, bytes = 10 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } +list = open() +batchAll(list) +textContains(Themed.last("confirm").text, "当前下载已暂停,开始缓存会恢复整个队列") + +-- 批量里含失败项:入队未缓存的,再逐条重试失败的,进度框算上两项。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 1, bytes = 10 * 1024 * 1024, available = 2000 * 1024 * 1024, ok = true } +st.queue = { state = "idle", entries = { + [602] = { chapterId = 602, state = "failed", bytes_done = 0, bytes_total = 100, last_error = "http 403" }, +}, bytes_done = 0, bytes_total = 0 } +list = open() +batchAll(list) +confirm = Themed.last("confirm") +textContains(confirm.text, "另有 1 卷失败将重试") +confirm.ok_callback() +Assert.eq(calls.enqueue[1][1].chapterId, 603) +Assert.eq(calls.retry[1][1], 602) +progress = Themed.last("progress_dialog") +textContains(progress.text, "1/2 卷", "进度框按「入队 + 重试」算总数") + +-- 只有失败项:直接给「重试缓存」,文案用 lastError 映射后的说法。 +reset() +st.statuses["603"] = { state = "complete", bytes = 1 } +st.queue = { state = "idle", entries = { + [601] = { chapterId = 601, state = "failed", last_error = "http 403" }, + [602] = { chapterId = 602, state = "failed", last_error = "socket closed" }, +}, bytes_done = 0, bytes_total = 0 } +list = open() +batchAll(list) +Assert.is_nil(calls.estimate, "没有要下载的就不估算") +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "重试缓存") +textContains(confirm.text, "服务器拒绝下载(403),检查 API Key / 权限") +textContains(confirm.text, "网络中断或服务器不可达") +confirm.ok_callback() +Assert.eq(table.concat(calls.retry[1], ","), "601,602") +Assert.len(calls.enqueue, 0, "没有未缓存的项就不入队") + +-- 删除下载中的卷:确认文案多一句「会取消这一卷的下载」(07 A4)。行尾只有一个动作槽, +-- 下载中显示暂停;确认文案本身是可复用的纯函数,供将来二级菜单 / 系列清理复用。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 30, bytes_total = 100 } }, bytes_done = 30, bytes_total = 100 } +list = open() +text = table.concat(Kit.texts(list), "\n") +textContains(text, "下载中 30%") +local row_buttons = tails(list) +Assert.eq(row_buttons[1].icon, "delete") +Assert.eq(row_buttons[2].icon, "pause") +textContains(VolumeList.deleteText(toc[2], 30 * 1024 * 1024, true), "删除会取消这一卷的下载。") + +-- 删除后重画:这一卷回到「在读」(缓存动作变回 download)。 +row_buttons[1]:onTapThemeButton() +Themed.last("confirm").ok_callback() +row_buttons = tails(list) +Assert.eq(row_buttons[1].icon, "download", "删完变回下载") +textContains(table.concat(Kit.texts(list), "\n"), "已读", "删缓存不动阅读进度") + +-- 正在读的卷:删除钮置灰,点按只 toast,不弹确认框、不选中(07 A1)。 +reset() +st.statuses["602"] = { state = "complete", bytes = 1 } +st.open_chapter = 602 +list, picked = open() +local disabled +for _idx, button in ipairs(tails(list)) do + if button.icon == "delete" then disabled = button end +end +Assert.is_false(disabled.enabled, "删除钮置灰") +confirms = #Themed.all("confirm") +tap(list, disabled) +Assert.eq(#Themed.all("confirm"), confirms, "置灰的删除钮不弹确认框") +textContains(Themed.last("toast").text, "正在阅读这一卷,关闭后可以删除") +Assert.is_nil(picked.value, "点置灰按钮不选中") + +-- 离线 + 未缓存:行仍可点,但只提示,不关窗也不选中(04 A7)。 +reset() +offline = true +list, picked = open() +textContains(table.concat(Kit.texts(list), "\n"), "未缓存 · 离线") +tapRow(list, "第 3 卷") +Assert.is_nil(picked.value, "离线未缓存行不选中") +textContains(Themed.last("toast").text, "这一卷还没缓存,联网后可下载") + +-- unknown_server:缓存状态整块不显示,只剩阅读状态,缓存动作全部隐藏(02 A9)。 +reset() +st.queue_code = "unknown_server" +st.queue = nil +list = open() +Assert.len(tails(list), 0, "没有行尾动作") +Assert.is_nil(list.left_icon, "没有缓存整部") +Assert.is_true(table.concat(Kit.texts(list), "\n"):find("缓存", 1, true) == nil, "不出现缓存状态字") + +-- 缺 queue_control:下载中只显示百分比,不出暂停 / 重试(02 A4)。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, enqueue = true, delete = true, estimate = true, +} } +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 62, bytes_total = 100 } }, bytes_done = 62, bytes_total = 100 } +list = open() +textContains(table.concat(Kit.texts(list), "\n"), "下载中 62%") +Assert.len(tails(list), 2, "只剩已缓存的删除钮与未缓存的下载钮") + +-- 暂停原因:行显示「已暂停 + 百分比 + play」,动作按 07 A5 分派。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +local function pausedQueue(reason, extra) + local entries = extra or {} + return { state = "paused", pause_reason = reason, entries = entries, + bytes_done = 0, bytes_total = 0 } +end +-- user / restored / offline / wifi:直接 resume。 +for _idx, reason in ipairs({ "user", "restored", "offline", "wifi" }) do + reset() + st.statuses["601"] = { state = "complete", bytes = 1 } + st.queue = pausedQueue(reason, { [602] = { chapterId = 602, state = "queued", + bytes_done = 62, bytes_total = 100 } }) + list = open() + textContains(table.concat(Kit.texts(list), "\n"), "已暂停 62%") + local play + for _i, button in ipairs(tails(list)) do + if button.icon == "play_arrow" then play = button end + end + Assert.not_nil(play, reason .. " 有继续钮") + play:onTapThemeButton() + Assert.eq(calls.resume, 1, reason .. " 直接继续") + Assert.len(calls.retry, 0, reason .. " 不重试") +end + +-- network:先重试本服务器的失败项,再继续。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = pausedQueue("network", { + [602] = { chapterId = 602, state = "failed", last_error = "socket closed" }, + [603] = { chapterId = 603, state = "queued" }, +}) +list = open() +for _idx, button in ipairs(tails(list)) do + if button.icon == "play_arrow" then button:onTapThemeButton() end +end +Assert.eq(table.concat(calls.retry[1], ","), "602") +Assert.eq(calls.resume, 1) + +-- low_space:不给继续,只 toast 清理提示。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = pausedQueue("low_space", { [602] = { chapterId = 602, state = "queued" } }) +list = open() +for _idx, button in ipairs(tails(list)) do + if button.icon == "play_arrow" then button:onTapThemeButton() end +end +Assert.eq(calls.resume, 0, "空间不足不恢复") +textContains(Themed.last("toast").text, "空间不足,已暂停") + +-- 进度框:入队后 1 秒轮询,暂停 → 已暂停收尾;继续 → 再开进度框。 +--- 走一遍「缓存整部」到出进度框;返回进度框与已排的 tick 数。 +---@return table +local function batchProgress() + reset() + st.statuses["601"] = { state = "complete", bytes = 1 } + st.estimate = { chapters = 2, bytes = 10 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } + list = open() + batchAll(list) + Themed.last("confirm").ok_callback() + return Themed.last("progress_dialog") +end + +--- 跑下一拍(1 秒)。 +local function tick() + local scheduled = Kit.scheduled[#Kit.scheduled] + Assert.not_nil(scheduled, "有下一拍") + Assert.eq(scheduled.delay, 1, "每秒轮询") + scheduled.fn() +end + +local progress_dialog = batchProgress() +Assert.eq(progress_dialog.sets and #progress_dialog.sets or 0, 0, "刚开还没走过一拍") +-- 下载中:聚合百分比 + 当前卷。 +st.queue = { state = "downloading", percent = 0.5, entries = { + [602] = { chapterId = 602, state = "downloading", bytes_done = 50, bytes_total = 100 }, +}, bytes_done = 50, bytes_total = 100, current_chapter_id = 602 } +local resume_page_calls = calls.resume_page +tick() +Assert.is_true(#progress_dialog.sets > 0, "轮询后更新说明行") +Assert.eq(calls.resume_page, resume_page_calls, "轮询不重复读 journal 的 resume_page") +local last_set = progress_dialog.sets[#progress_dialog.sets] +textContains(last_set[1], "第 2 卷") +Assert.eq(last_set[2], 50, "进度条用本服务器的聚合 percentage") + +-- 暂停:进度框按钮走 queue_pause;下一拍收尾成「已暂停」,按钮是继续 / 关闭。 +progress_dialog.on_cancel() +Assert.eq(calls.pause, 1) +tick() +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "已暂停") +textContains(confirm.text, "已暂停") +Assert.eq(confirm.ok_text, "继续") +Assert.eq(confirm.cancel_text, "关闭") +-- 继续:先 resume,再开回进度框。 +local dialogs = #Themed.all("progress_dialog") +confirm.ok_callback() +Assert.eq(calls.resume, 1) +Assert.eq(#Themed.all("progress_dialog"), dialogs + 1, "继续后重开进度框") + +-- 全部完成:自动关窗 + toast「已缓存 N 卷」,不再排下一拍。 +progress_dialog = Themed.last("progress_dialog") +st.queue = { state = "idle", entries = {}, bytes_done = 0, bytes_total = 0 } +local before = #Kit.scheduled +tick() +Assert.is_true(progress_dialog.closed, "全成关窗") +textContains(Themed.last("toast").text, "已缓存 2 卷") +Assert.eq(#Kit.scheduled, before, "收尾后不再轮询") + +-- 部分失败:说明行写成功 / 失败数并列出失败原因,按钮「查看失败原因」。 +progress_dialog = batchProgress() +st.queue = { state = "idle", entries = { + [602] = { chapterId = 602, state = "failed", last_error = "not an archive: html" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "部分失败") +textContains(confirm.text, "1 卷成功,1 卷失败") +textContains(confirm.text, "下载内容不完整或不是有效压缩包") +Assert.eq(confirm.ok_text, "查看失败原因") +confirm.ok_callback() +Assert.is_true(progress_dialog.closed) + +-- 断网暂停:文案带原因,按钮继续。 +progress_dialog = batchProgress() +st.queue = { state = "paused", pause_reason = "offline", entries = { + [602] = { chapterId = 602, state = "queued" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "已暂停") +textContains(confirm.text, "已暂停(断网)") +Assert.eq(confirm.ok_text, "继续") +Assert.eq(confirm.cancel_text, "关闭") + +-- 其余暂停原因:文案与主按钮都来自 07 A5 的表。 +for reason, expected in pairs({ + user = "已暂停", + restored = "已暂停(启动恢复)", + wifi = "已暂停(仅 Wi-Fi 下载)", +}) do + progress_dialog = batchProgress() + st.queue = { state = "paused", pause_reason = reason, entries = { + [602] = { chapterId = 602, state = "queued" }, + }, bytes_done = 0, bytes_total = 0 } + tick() + confirm = Themed.last("confirm") + Assert.eq(confirm.title, "已暂停", reason) + textContains(confirm.text, expected, reason) + Assert.eq(confirm.ok_text, "继续", reason) + Assert.eq(confirm.cancel_text, "关闭", reason) +end + +-- 空间不足暂停:没有继续,只有清理提示。 +progress_dialog = batchProgress() +st.queue = { state = "paused", pause_reason = "low_space", entries = { + [602] = { chapterId = 602, state = "queued" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +textContains(confirm.text, "空间不足,已暂停") +Assert.eq(confirm.ok_text, "去清理空间") +confirm.ok_callback() +textContains(Themed.last("toast").text, "空间不足") +Assert.eq(calls.resume, 0, "低水位不给继续") + +-- 连续失败暂停:主按钮「重试失败项并继续」,点了先逐条重试再恢复。 +progress_dialog = batchProgress() +st.queue = { state = "paused", pause_reason = "network", entries = { + [602] = { chapterId = 602, state = "failed", last_error = "http 403" }, +}, bytes_done = 0, bytes_total = 0 } +tick() +confirm = Themed.last("confirm") +textContains(confirm.text, "已暂停(连续下载失败)") +Assert.eq(confirm.ok_text, "重试失败项并继续") +confirm.ok_callback() +Assert.eq(table.concat(calls.retry[1], ","), "602") +Assert.eq(calls.resume, 1) +Assert.not_nil(Themed.last("progress_dialog")) + +-- 后台运行:关窗不影响队列,列表继续轮询;后台期间不再弹收尾框。 +progress_dialog = batchProgress() +progress_dialog.on_background() +st.queue = { state = "downloading", percent = 0.9, entries = { + [602] = { chapterId = 602, state = "downloading", bytes_done = 90, bytes_total = 100 }, +}, bytes_done = 90, bytes_total = 100, current_chapter_id = 602 } +local confirms_before = #Themed.all("confirm") +tick() +Assert.eq(#Themed.all("confirm"), confirms_before, "后台不弹窗") +st.queue = { state = "idle", entries = {}, bytes_done = 0, bytes_total = 0 } +tick() +Assert.eq(#Themed.all("confirm"), confirms_before, "后台收尾也不弹窗") + +-- 失败行:refresh 走单卷确认,文案是 lastError 映射后的说法(07 A7),没有 moon 侧重试。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "idle", entries = { + [602] = { chapterId = 602, state = "failed", last_error = "http 403" }, +}, bytes_done = 0, bytes_total = 0 } +list = open() +local refresh_button +for _idx, button in ipairs(tails(list)) do + if button.icon == "refresh" then refresh_button = button end +end +Assert.not_nil(refresh_button) +tap(list, refresh_button) +confirm = Themed.last("confirm") +Assert.eq(confirm.title, "重试缓存") +textContains(confirm.text, "服务器拒绝下载(403),检查 API Key / 权限") +confirm.ok_callback() +Assert.eq(table.concat(calls.retry[1], ","), "602") +Assert.eq(calls.resume, 0, "queue_retry 由 kamare 自己恢复,moon 不再补 resume") + +-- 删除失败:kamare 的 code / message 原样提示。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.delete_ok, st.delete_code, st.delete_message = false, "write_failed", "删除失败:磁盘错误" +list = open() +tap(list, tails(list)[1]) +Themed.last("confirm").ok_callback() +textContains(Themed.last("toast").text, "删除失败:磁盘错误") + +-- 关列表即停轮询(04 A8)。 +batchProgress() +Assert.is_true(#Kit.scheduled > 0) +list:close() +Assert.is_true(#Kit.unscheduled > 0, "关窗时撤掉定时器") + +-- 后台任务:入队就登记一条 passive 任务,页面自己的进度框在时静音(收尾只提示一次)。 +reset() +progress_dialog = batchProgress() +local handle = tracked[1] +Assert.not_nil(handle, "入队后登记后台任务") +Assert.eq(handle.opts.series, series, "任务按这一部书") +Assert.eq(#handle.opts.entries, 2, "任务只数本批的卷") +Assert.eq(handle.opts.entries[1].chapterId, 602) +Assert.is_true(handle.muted, "进度框开着时任务静音") +progress_dialog.on_background() +Assert.is_false(handle.muted, "转后台后由任务收尾提示") + +-- 关列表同样取消静音:页面不再轮询,完成提示归任务。 +reset() +progress_dialog = batchProgress() +handle = tracked[1] +Assert.is_true(handle.muted) +list:close() +Assert.is_false(handle.muted, "关列表后由任务收尾提示") + +-- 缺 queue:没有可轮询的队列,不登记任务(不能让后台任务永远挂着)。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, enqueue = true, delete = true, estimate = true, +} } +st.estimate = { chapters = 2, bytes = 1, available = 1000, ok = true } +list = open() +batchAll(list) +Themed.last("confirm").ok_callback() +Assert.len(tracked, 0, "缺 queue 不登记任务") + +-- 缺 queue_control:进度框只留后台运行。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, enqueue = true, delete = true, estimate = true, +} } +st.statuses["601"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 2, bytes = 1, available = 1000, ok = true } +list = open() +batchAll(list) +Themed.last("confirm").ok_callback() +progress_dialog = Themed.last("progress_dialog") +Assert.is_nil(progress_dialog.on_cancel, "没有暂停钮") +Assert.not_nil(progress_dialog.on_background, "仍可后台运行") + +-- 缺 queue:没有进度可轮询,行显示「已排队」且不能凭缺席的队列宣布完成(02 A4)。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, enqueue = true, delete = true, estimate = true, +} } +st.statuses["601"] = { state = "complete", bytes = 1 } +st.estimate = { chapters = 2, bytes = 10 * 1024 * 1024, available = 1000 * 1024 * 1024, ok = true } +local scheduled_before = #Kit.scheduled +local toasts_before = #Themed.all("toast") +list = open() +batchAll(list) +Themed.last("confirm").ok_callback() +progress_dialog = Themed.last("progress_dialog") +Assert.not_nil(progress_dialog, "缺 queue 也确认已入队") +Assert.eq(progress_dialog.text, "已排队", "没有百分比可写") +Assert.eq(#Kit.scheduled, scheduled_before, "没有 queue 可轮询:不排下一拍") +Assert.eq(#Themed.all("toast"), toasts_before, "不凭缺席的队列宣布完成") +local no_queue_text = table.concat(Kit.texts(list), "\n") +textContains(no_queue_text, "已排队", "行内显示排队") +Assert.is_nil(no_queue_text:find("已缓存 2 卷", 1, true), "不能谎报已缓存") + +-- 行内暂停是全局动作:文案要说清暂停的是整个队列(04 A3)。 +reset() +st.statuses["601"] = { state = "complete", bytes = 1 } +st.queue = { state = "downloading", entries = { [602] = { chapterId = 602, state = "downloading", + bytes_done = 30, bytes_total = 100 } }, bytes_done = 30, bytes_total = 100 } +list = open() +local pause_button +for _idx, button in ipairs(tails(list)) do + if button.icon == "pause" then pause_button = button end +end +Assert.not_nil(pause_button) +local toasts_used = #Themed.all("toast") +pause_button:onTapThemeButton() +Assert.eq(calls.pause, 1, "点暂停即 queue_pause") +Assert.eq(#Themed.all("toast"), toasts_used + 1, "暂停后提示") +textContains(Themed.last("toast").text, "整个下载队列", "说明作用于全局队列") + + +-- 系列清理:一次 chapters(series_id)、菜单计数、确认后批量删、就地刷新。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, queue = true, queue_control = true, enqueue = true, + delete = true, estimate = true, chapters = true, +} } +st.plan = { + { chapterId = 601, pages = 100, read = true, bytes = 1024, stale = false, queued = false }, + { chapterId = 602, pages = 100, read = false, bytes = 2048, stale = false, queued = false }, +} +list = open() +Assert.eq(calls.chapters, 1, "一次 chapters(series_id) 取代逐章 status") +Assert.eq(calls.chapters_series, "900", "按当前 seriesId 取计划") +textContains(table.concat(Kit.texts(list), "\n"), "已读 · 已缓存", "kamare 的已读进入行状态") + +menu = openMenu(list) +local cleanup_labels = {} +for _idx, item in ipairs(menu.items) do cleanup_labels[#cleanup_labels + 1] = item.text end +Assert.eq(table.concat(cleanup_labels, "|"), + "缓存整部|缓存未读|缓存后 N 卷…|清理本系列|清理本系列已读", + "清理项在批量菜单底部") +Assert.eq(menu.items[4].mandatory, "2 卷", "本系列缓存计数") +Assert.eq(menu.items[5].mandatory, "1 卷", "本系列已读计数") + +chooseMenu(menu, 5) +local cleanup_confirm = Themed.last("confirm") +Assert.not_nil(cleanup_confirm, "清理前确认") +textContains(cleanup_confirm.text, "将删除本系列 1 卷已读完的缓存") +textContains(cleanup_confirm.text, "阅读进度与 kamare journal 保留") +cleanup_confirm.ok_callback() +local busy = Themed.last("progress_dialog") +Assert.not_nil(busy, "同步删除先弹忙碌窗") +Assert.eq(busy.title, "清理本系列已读") +Assert.eq(busy.text, "正在清理…") +Assert.is_true(busy.shown and busy.closed, "先显示、删完关闭") +Assert.eq(#calls.delete, 1, "清理本系列已读只调一次 delete") +Assert.eq(#calls.delete[1], 1, "只删已读完的那一卷") +Assert.eq(calls.delete[1][1], 601, "删的是已读卷") +Assert.eq(calls.chapters, 2, "删后重取一次 chapters 比对残留") +textContains(Themed.last("toast").text, "已清理 1 卷") + +-- 0 个对象:菜单项置灰,点了也不会弹确认。 +reset() +st.probe = { ok = true, state = "enhanced", capabilities = { + status = true, enqueue = true, delete = true, estimate = true, chapters = true, +} } +st.plan = { { chapterId = 602, pages = 100, read = false, bytes = 2048 } } +list = open() +menu = openMenu(list) +Assert.is_false(menu.items[5].enabled, "没有已读完的卷时置灰") +Assert.eq(menu.items[5].mandatory, "无") +Assert.is_true(menu.items[4].enabled, "还有未读的缓存:整系列清理仍可点") +Assert.eq(menu.items[4].mandatory, "1 卷") + +-- 点开系列时后台刷新目录:服务器最新的 pagesRead 原地反映到行里(不用关掉重开)。 +reset() +local fresh_toc = { entry(631, "第 1 卷", 100, 0), entry(632, "第 2 卷", 100, 0) } +local live = open(fresh_toc) +Assert.not_nil(live.refreshToc, "列表暴露刷新入口") +live.refreshToc({ entry(631, "第 1 卷", 100, 100), entry(632, "第 2 卷", 100, 40) }) +live:paintTo(Kit.canvas(), 0, 0) +local live_text = table.concat(Kit.texts(live), "\n") +Assert.is_true(live_text:find("已读", 1, true) ~= nil, "服务器说读完的卷立刻变已读") +Assert.is_true(live_text:find("在读", 1, true) ~= nil, "服务器说读到一半的卷立刻变在读") +-- 空目录 / 已关的列表直接丢弃回包,不把列表清空。 +live.refreshToc({}) +live:paintTo(Kit.canvas(), 0, 0) +textContains(table.concat(Kit.texts(live), "\n"), "第 1 卷", "空回包不清空列表") +live.closed = true +live.refreshToc({ entry(631, "第 1 卷", 100, 0) }) +Assert.eq(#live.items, 2, "关掉的列表不再吃回包") + +-- 续读卡:主线 = 最远有进度的卷,标题写卷名 + 页数;点卡片直接选中它。 +reset() +local cover_hits = {} +list, picked = open(nil, { + cover = function(e) + cover_hits[#cover_hits + 1] = e.chapterId + return "http://cover/" .. e.chapterId .. ".jpg", { ["x-api-key"] = "k" } + end, +}) +local card = findRow(list, "继续阅读 · 第 2 卷") +Assert.not_nil(card, "续读卡写明是哪一卷") +Assert.eq(card.row_subtitle, "第 40/100 页 · 40%") +Assert.eq(#cover_hits, 3, "每一卷都取了封面(卡片复用同一张,不重复取)") +tap(list, card) +Assert.eq(picked.value and picked.value.chapterId, 602, "点卡片直接开第 2 卷") +Assert.is_true(wasClosed(list), "点卡片关列表") + +-- 回顾旧卷:主线仍是第 2 卷,第 1 卷只标「上次翻阅」。 +reset() +local_progress["900:601"] = { fraction = 1, page = 100, total_pages = 100, updated_at = 500 } +local_progress["900:602"] = { fraction = 0.4, page = 40, total_pages = 100, updated_at = 100 } +list = open() +Assert.not_nil(findRow(list, "继续阅读 · 第 2 卷"), "回顾旧卷不劫持主线") +Assert.eq(findRow(list, "第 1 卷").row_subtitle, "上次翻阅") +Assert.eq(findRow(list, "第 2 卷").row_subtitle, "第 40/100 页 · 40%") + +-- 全部读完:卡片写「已读完 · 共 N 卷」,点它重读第一卷。 +reset() +list, picked = open({ + entry(661, "第 1 卷", 100, 100), + entry(662, "第 2 卷", 100, 100), +}) +local done = findRow(list, "已读完 · 共 2 卷") +Assert.not_nil(done, "读完的系列有重读入口") +Assert.eq(done.row_subtitle, "重读 · 第 1 卷") +tap(list, done) +Assert.eq(picked.value and picked.value.chapterId, 661, "重读回到第一卷") + +-- 卷名缺失 / 退化成系列名:兜底「第 N 卷」。 +reset() +list = open({ + { idx = 1, chapterId = 671, volumeId = 1, seriesId = 900, libraryId = 1, + title = "测试系列", pages = 100, pagesRead = 0 }, +}) +Assert.not_nil(findRow(list, "第 1 卷"), "标题退化成系列名时用第 N 卷") + + +-- 服务端已读完、本机重新打开留下 1/194:行仍显示「已读」,不显示 1%,主线跳过它。 +reset() +local_progress["900:682"] = { fraction = 0.005, page = 1, total_pages = 194, updated_at = 999 } +list = open({ + entry(681, "第 1 卷", 210, 210), + entry(682, "第 2 卷", 194, 194), + entry(683, "第 3 卷", 200, 0), +}) +Assert.eq(findRow(list, "第 2 卷").row_subtitle, "上次翻阅", "已读完的卷不再显示 1/194") +Assert.not_nil(findRow(list, "继续阅读 · 第 3 卷"), "主线跳过已读完的第 2 卷") + +-- 离线续读卡和普通卷行使用同一套选择保护。 +reset() +offline = true +list, picked = open() +local offline_card = findRow(list, "继续阅读 · 第 2 卷") +tap(list, offline_card) +Assert.is_nil(picked.value, "未缓存卷不能从续读卡绕过离线保护") +Assert.is_false(wasClosed(list), "离线失败后保留卷列表,仍能挑别的缓存卷") +Assert.eq(Themed.last("toast").text, "这一卷还没缓存,联网后可下载") + +reset() +offline = true +st.statuses["602"] = { state = "complete", bytes = 2048 } +list, picked = open() +tap(list, findRow(list, "继续阅读 · 第 2 卷")) +Assert.eq(picked.value.chapterId, 602, "已缓存的续读卷离线照常打开") +Assert.is_true(wasClosed(list)) + +-- kamare 完成状态参与列表与对外目标计算;刷新后卡片也必须顺延。 +reset() +st.probe.capabilities.chapters = true +st.plan = { { chapterId = 602, pages = 100, read = false, bytes = 2048 } } +list = open() +Assert.not_nil(findRow(list, "继续阅读 · 第 2 卷")) +st.plan[1].read = true +list.refreshToc({ unpack(toc) }) +list:paintTo(Kit.canvas(), 0, 0) +Assert.not_nil(findRow(list, "继续阅读 · 第 3 卷"), "最新完成状态不能被刷新前的 ctx 遮住") +Assert.eq(VolumeList.continueTarget(series, toc).entry.chapterId, 603, + "对外目标和列表使用同一套 kamare 完成事实") + +-- 目标计算不逐卷读 resumePage(那是列表行「待同步」才需要的)。 +reset() +st.plan = { { chapterId = 601, pages = 100, read = true, bytes = 1 } } +VolumeList.continueTarget(series, toc) +Assert.eq(calls.resume_page, 0, "续读目标不读 resume_page") + + +-- 卷进度整列一次查询,不再逐卷 get。 +reset() +list = open() +Assert.eq(progress_list_calls, 1, "打开列表只读一次整列进度") + + +return true diff --git a/tools/package.sh b/tools/package.sh new file mode 100755 index 0000000..8c53048 --- /dev/null +++ b/tools/package.sh @@ -0,0 +1,25 @@ +#!/bin/sh +# 打包本仓库的书源插件:moonsource-<名字>.koplugin-.zip,同时生成 SHA256SUMS。 +# 用法:tools/package.sh [OUT_DIR] (OUT_DIR 默认 dist/) +# 打包时把 <包名>/version.lua 里的版本占位符换成发布版本;剔除 *.md、.DS_Store、*~。 +set -eu +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +VERSION="${1:?用法:tools/package.sh [OUT_DIR]}" +OUT="${2:-$ROOT/dist}" +case "$OUT" in /*) ;; *) OUT="$PWD/$OUT" ;; esac + +NAME="$(cd "$ROOT" && ls -d moonsource-*.koplugin | head -n 1)" +[ -f "$ROOT/$NAME/main.lua" ] || { echo "找不到插件目录:$NAME" >&2; exit 1; } +PKG="$(echo "${NAME%.koplugin}" | tr - _)" + +mkdir -p "$OUT" +STAGE="$(mktemp -d)" +trap 'rm -rf "$STAGE"' EXIT +rsync -a --exclude '*.md' --exclude '.DS_Store' --exclude '*~' "$ROOT/$NAME/" "$STAGE/$NAME/" +sed "s/@VERSION@/$VERSION/" "$ROOT/$NAME/$PKG/version.lua" > "$STAGE/$NAME/$PKG/version.lua" +ZIP="$OUT/$NAME-$VERSION.zip" +rm -f "$ZIP" +(cd "$STAGE" && zip -qr "$ZIP" "$NAME") +echo "Packaged $ZIP" + +(cd "$OUT" && { command -v sha256sum >/dev/null && sha256sum ./*.zip || shasum -a 256 ./*.zip; } | sed 's# \./# #' > SHA256SUMS) diff --git a/tools/release.sh b/tools/release.sh new file mode 100755 index 0000000..568693e --- /dev/null +++ b/tools/release.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# 发布本书源:校验更新日志 → 本地打包 → 打轻量标签 v<版本> → 推送当前分支和标签。 +# Release 由 .github/workflows/release.yml 在标签推上去之后创建,日志取 CHANGELOG.md 里精确的「## <版本>」一节。 +# 用法:tools/release.sh +set -eu +ROOT="$(cd "$(dirname "$0")/.." && pwd)" +cd "$ROOT" +VERSION="${1:?用法:tools/release.sh }" + +case "$VERSION" in + v*) echo "版本不要带 v:$VERSION" >&2; exit 1 ;; +esac +printf '%s\n' "$VERSION" | grep -Eq '^[0-9]+\.[0-9]+\.[0-9]+([.+-].*)?$' \ + || { echo "版本应为 MAJOR.MINOR.PATCH:$VERSION" >&2; exit 1; } + +grep -qx "## ${VERSION}" CHANGELOG.md \ + || { echo "CHANGELOG.md 缺少单独一行「## ${VERSION}」" >&2; exit 1; } + +if [ -n "$(git status --porcelain)" ]; then + echo "工作区不干净,先提交再发布" >&2 + exit 1 +fi + +tools/package.sh "$VERSION" dist + +TAG="v${VERSION}" +if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then + HAVE="$(git rev-parse "${TAG}^{}")" + HEAD="$(git rev-parse HEAD)" + if [ "$HAVE" != "$HEAD" ]; then + echo "标签 ${TAG} 已经指向别的提交" >&2 + exit 1 + fi +else + git tag "$TAG" +fi + +BRANCH="$(git rev-parse --abbrev-ref HEAD)" +git push origin "$BRANCH" +git push origin "$TAG" +echo "已推送 ${TAG}。Actions 会打包并创建 Release。" diff --git a/tools/run-tests.sh b/tools/run-tests.sh new file mode 100755 index 0000000..ec1706e --- /dev/null +++ b/tools/run-tests.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# 离线单元测试:借用月读仓库的测试运行器与桩,把本仓库的插件目录和 tests/ 加进 LUA_PATH。 +# 用法:MOON_DIR=/path/to/moon tools/run-tests.sh [spec 文件…] +set -euo pipefail +here="$(cd "$(dirname "$0")/.." && pwd)" +: "${MOON_DIR:?请把 MOON_DIR 设为月读仓库路径}" +paths="$here/tests/?.lua;$here/tests/?/init.lua" +for plugin in "$here"/moonsource-*.koplugin; do + paths="$paths;$plugin/?.lua" +done +export LUA_PATH="$paths;;" +if [ "$#" -eq 0 ]; then + set -- $(find "$here/tests" -name '*_spec.lua' | sort) +fi +cd "$MOON_DIR" +exec luajit tests/run.lua "$@"