🚚 (split): 从月读拆出独立仓库,沿用原书源 id
Release / release (push) Successful in 11s

This commit is contained in:
Garfield committed 2026-11-27 08:08:01 +08:00
commit df896cbe3b
28 files changed
+3586

No files matched your search

+86
View File
@@ -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
+4
View File
@@ -0,0 +1,4 @@
.DS_Store
*.swp
dist/
.idea/
+7
View File
@@ -0,0 +1,7 @@
# 更新日志
## 0.0.1
- 「开源阅读」书源拆成独立仓库,独立发版、独立更新;原来所有书源同版本一起更新的做法取消。
- 检查更新与自动更新只管本书源:月读「书库 → 更新」里每个书源各有一项,只提示、不静默安装,装完重启 KOReader。
- 书源 id、书架、进度、登录配置和缓存沿用原有数据,从旧版覆盖安装即可,无需迁移。
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+47
View File
@@ -0,0 +1,47 @@
# 月读书源:开源阅读
给月读增加「开源阅读」在线书源的 KOReader 插件。本仓库只含这一个插件,独立维护、独立发版,全部书源见 [moon-source 组织](https://git.garfieldho.me/moon-source)。
## 免责声明
- 本仓库与「开源阅读」官方**没有任何关联**,所有商标、书名、内容归原权利人所有。
- 插件只是在用户自己的账号、自己的设备上,按用户本人已有的权限读取内容;不提供、不分发任何书籍内容,也不绕过付费。
- 使用可能违反对应平台的用户协议,账号可能被限制或封禁。是否使用、风险如何,由使用者自行判断并承担。
- 权利人认为本仓库内容有问题,请通过仓库 issue 联系,核实后会及时处理。
## 安装
1. 先装好月读。
2. 从 [Release](../../releases) 下载 `moonsource-legado.koplugin-<版本>.zip`,解压出 `moonsource-legado.koplugin` 目录,整个复制到 KOReader 的 `plugins/` 下。
3. 重启 KOReader,在月读的书源列表里启用。
书源 id 是 `legado`,与旧版(合并仓库、内置书源)相同,书架、进度、登录配置、缓存沿用原有数据,无需迁移。
## 更新
在月读的「书库 → 开源阅读 更新」里有「检查书源插件更新」和「自动检查书源插件更新」(默认开,每 24 小时一次,只提示、不静默安装)。
本插件只检查并更新自己(本仓库的 Release),校验值取自 Release 的 `SHA256SUMS`,装完重启 KOReader。
> 从旧的合并仓库 `GarfieldTony/moon-source` 迁移:旧仓库的更新入口已停用,请直接从本仓库下载最新包覆盖安装。
## 发布
推送 `vX.Y.Z` 标签(带 `-` 的如 `v1.2.0-rc.1` 为预发布),Forgejo Actions 会打包 `moonsource-legado.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/legado/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)。
+5
View File
@@ -0,0 +1,5 @@
local _ = require("gettext")
return {
fullname = _("月读书源:开源阅读"),
description = _("给月读增加「开源阅读」书源。需要同时安装月读,与平台官方无关。"),
}
+9
View File
@@ -0,0 +1,9 @@
--[[--
KOReader 只认带 main.lua 的插件目录;书源本身不需要任何插件钩子,月读读取旁边的 moon_source.lua。
--]]
local WidgetContainer = require("ui/widget/container/widgetcontainer")
return WidgetContainer:extend{
name = "moonsource_legado",
is_doc_only = false,
}
@@ -0,0 +1,17 @@
--[[--
月读第三方书源描述:开源阅读。契约见月读 examples/moonsource-demo.koplugin/moon_source.lua。
--]]
local function lazy(module)
return setmetatable({}, { __index = function(_, key) return require(module)[key] end })
end
return {
api = 1,
provides = {
source = true,
},
meta = function() return require("moonsource_legado.source").meta() end,
new = function() return require("moonsource_legado.source").new() end,
setting = lazy("moonsource_legado.setting"),
}
@@ -0,0 +1,17 @@
# 开源阅读(Legado)
| 能力 | 是否支持 | 备注 |
| --- | --- | --- |
| 服务连接 | 支持 | 阅读 App Web 服务、reader3、轻阅读;不是直接导入规则书源 |
| 局域网发现 | 支持 | 可扫描阅读服务地址 |
| 账号密码 | 部分支持 | reader3、轻阅读可配置;普通阅读 App Web 服务无需账号 |
| 书架拉取 | 支持 | 书籍须先在阅读 App 或服务端添加 |
| 加入远端书架 | 不支持 | 请在对应 App 或服务端添加 |
| 移出远端书架 | 支持 | 服务端确认后清除本地墓碑 |
| 目录与文字正文 | 支持 | 取决于服务端书源可用性;轻阅读需有效书源信息 |
| 封面与正文图片 | 部分支持 | 具体行为取决于后端 |
| 阅读进度同步 | 支持 | 章节及章内偏移;不同排版不保证精确对齐 |
| 笔记与统计同步 | 不支持 | 本地记录保留 |
| 书评、章评、段评与回复 | 不支持 | 桥接后端没有统一评论契约;不代表上游网站没有评论 |
| 章节预取与全本缓存 | 支持 | 内容需由服务端正常返回 |
| 离线阅读 | 支持 | 仅已缓存目录和章节 |
@@ -0,0 +1,16 @@
--[[--
书源元信息:id / 名称 / 类型,加上启用页展示用的说明与能力清单。`init.lua` 的 `meta()` 直接返回本表。
@module moonsource_legado._meta
--]]
local _ = require("l10n").get("moonsource_legado")
return {
id = "legado",
name = _("开源阅读"),
type = "chapter",
description = _("连接阅读 App、reader3 或轻阅读服务"),
abilities = { _("书架与章节正文"), _("目录及整本缓存"), _("进度同步"), _("从服务端书架删除"),
_("他人段评(阅读 App)") },
}
@@ -0,0 +1,377 @@
--[[--
阅读(Legado)Web 服务 HTTP 客户端(仅异步)。
三种后端共用回包 `{ isSuccess, errorMsg, data }` 与 0 基章节 `index`,按地址后缀区分(Client.mode):
- app:阅读 App 的 Web 服务(http://192.168.1.8:1122),GET 查询、JSON 上报;
- reader3:服务器版(…/reader3),可登录;书架 GET,其余 POST JSON;
- qread:轻阅读(…/api/5),可登录;全部 POST 表单,章节 / 正文要带书源 origin。
@module koplugin.book.moonsource_legado.client
--]]
local JSON = require("json")
local Request = require("http.request")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_legado")
local Client = {}
local SOURCE_ID = "legado"
--- 服务器地址,缺协议头按 http 补;没配置返回 nil。
---@param cfg table|nil 校验待保存配置时显式传入,不改变当前库
---@return string|nil
function Client.base(cfg)
local addr = (cfg or require("utils.settings").getSource(SOURCE_ID)).server_address
if type(addr) ~= "string" or addr == "" then return nil end
if not addr:match("^https?://") then addr = "http://" .. addr end
return (addr:gsub("/+$", ""))
end
--- 解回包:isSuccess 为真才算成功,返回 data。
---@param raw string|nil
---@param err any
---@return any|nil data, string|nil err
function Client.decode(raw, err)
if not raw then return nil, err and tostring(err) or _("请求失败") end
local ok, wire = pcall(JSON.decode, raw)
if not ok or type(wire) ~= "table" then return nil, _("响应无效") end
if not wire.isSuccess then return nil, wire.errorMsg ~= "" and wire.errorMsg or _("请求失败") end
if wire.data == nil then return {} end
return wire.data
end
---@alias LegadoMode "app"|"reader3"|"qread"
--- 后端类型,看地址路径的最后一段。
---@param cfg table|nil
---@return LegadoMode
function Client.mode(cfg)
local base = Client.base(cfg) or ""
if base:find("/reader3$") then return "reader3" end
if base:find("/api/%d+$") then return "qread" end
return "app"
end
--- 服务根(去掉 /reader3、/api/N),封面与书内图片的相对路径从这里起算。
---@return string
local function root()
return ((Client.base() or ""):gsub("/reader3$", ""):gsub("/api/%d+$", ""))
end
---@param path string
---@param query table<string, any>|nil
---@param cfg table|nil
---@return string|nil
local function url(path, query, cfg)
local base = Client.base(cfg)
if not base then return nil end
local out = base .. path
if query then
local qs = Text.formEncode(query)
if qs ~= "" then out = out .. "?" .. qs end
end
return out
end
--- 账号密码(阅读 App 的 Web 服务没有账号);缺一项视为无需登录。
---@param cfg table|nil
---@return string|nil user, string|nil password
local function credentials(cfg)
cfg = cfg or require("utils.settings").getSource(SOURCE_ID)
if type(cfg.username) == "string" and cfg.username ~= "" and type(cfg.password) == "string" and cfg.password ~= "" then
return cfg.username, cfg.password
end
return nil
end
-- accessToken 只在内存里,key 带地址与账号,改了配置自然作废。
local session = { key = nil, token = nil }
---@param method "GET"|"POST"
---@param enc "json"|"form"|nil POST 体编码
---@param target string
---@param body table|nil
---@param ratio number
---@param done fun(data: any|nil, err: string|nil)
---@return { cancel: fun() }
local function send(method, enc, target, body, ratio, done)
local opts = { accept = "application/json", timeout = require("http.timeout").net(ratio) }
local function finish(raw, err) done(Client.decode(raw, err)) end
if method == "GET" then return Request.get(target, opts, finish) end
if enc == "form" then
opts.content_type = "application/x-www-form-urlencoded"
local flat = {}
for k, v in pairs(body) do
if type(v) ~= "table" then flat[k] = v end
end
return Request.post(target, Text.formEncode(flat), opts, finish)
end
opts.content_type = "application/json"
return Request.post(target, JSON.encode(body), opts, finish)
end
---@param user string
---@param password string
---@param cb fun(token: string|nil, err: string|nil)
---@param cfg table|nil
---@return { cancel: fun() }
local function login(user, password, cb, cfg)
local target = url("/login", nil, cfg)
if not target then return require("source.base").defer(cb, nil, _("未配置阅读服务器地址")) end
local qread = Client.mode(cfg) == "qread"
local body = qread and { username = user, password = password, model = "web" }
or { username = user, password = password, code = "", isLogin = true, v = os.time() }
return send("POST", qread and "form" or "json", target, body, 0.5, function(data, reason)
local token = type(data) == "table" and data.accessToken
if type(token) ~= "string" or token == "" then
cb(nil, reason or _("登录失败"))
return
end
cb(token)
end)
end
--- 配了账号密码时先登录、请求带 accessToken;服务端回 NEED_LOGIN(令牌过期)就重新登录再试一次。
--- 重登仍失败 / 仍 NEED_LOGIN → Auth.expire,引导用户检查账号密码。
---@param go fun(token: string|nil, done: fun(data: any|nil, err: string|nil)): { cancel: fun() }
---@param cb fun(data: any|nil, err: string|nil)
---@param cfg table|nil
---@return { cancel: fun() }
local function authed(go, cb, cfg)
local user, password = credentials(cfg)
local base = Client.base(cfg)
-- 配置里可能只剩账号密码:没地址时交给 go 报「未配置」。
if not user or not base then return go(nil, cb) end
local auth_session = cfg and {} or session
local key = base .. "\0" .. user .. "\0" .. password
local expired_msg = _("打开「设置 → 书库 → 账号 → 开源阅读 → 阅读服务地址」。账号和密码重新填一遍,地址不用改,点「保存」。阅读 App 里如果改过密码,这里填新密码。")
---@type boolean, CancelHandle|nil
local cancelled, job = false, nil
local function run(retry)
local function call(token)
job = go(token, function(data, err)
if cancelled then return end
if retry and err and err:find("NEED_LOGIN", 1, true) then
auth_session.token = nil
run(false)
return
end
if err and err:find("NEED_LOGIN", 1, true) then
err = require("source.auth").expire(SOURCE_ID, expired_msg)
end
cb(data, err)
end)
end
if auth_session.key == key and auth_session.token then
call(auth_session.token)
else
job = login(user, password, function(token, err)
if cancelled then return end
if not token then
-- 令牌过期后的重登失败:明确通知;首次配置错误登录仍原样返回。
if not retry then
err = require("source.auth").expire(SOURCE_ID, expired_msg)
end
cb(nil, err)
return
end
auth_session.key, auth_session.token = key, token
require("source.auth").ok(SOURCE_ID)
call(token)
end, cfg)
end
end
run(true)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
--- 一次调用。kind:shelf(app / reader3 用 GET)、read(只有 app 用 GET)、write;其余按后端走 POST JSON / 表单。
---@param path string
---@param params table<string, any>
---@param ratio number 超时倍率
---@param kind "shelf"|"read"|"write"
---@param cb fun(data: any|nil, err: string|nil)
---@param cfg table|nil
---@return { cancel: fun() }
local function call(path, params, ratio, kind, cb, cfg)
local mode = Client.mode(cfg)
local get = (kind == "shelf" and mode ~= "qread") or (kind == "read" and mode == "app")
local method = get and "GET" or "POST"
return authed(function(token, done)
local query = token and { accessToken = token } or nil
if method == "GET" then
query = query or {}
for k, v in pairs(params) do query[k] = v end
end
local target = url(path, query, cfg)
if not target then return require("source.base").defer(done, nil, _("未配置阅读服务器地址")) end
return send(method, mode == "qread" and "form" or "json", target, params, ratio, done)
end, cb, cfg)
end
--- 书内图片地址:服务端给的相对路径补成可直接下载的 URL(app 的相对路径没有意义,原样返回)。
---@param src string
---@param base string|nil EPUB 章节 URL,按它解析相对引用;只给同服务器的资源带令牌。
---@return string
function Client.imageUrl(src, base)
local out
if base then
out = assert(Text.absoluteUrl(base, src), "invalid chapter resource URL")
if out:match("^(https?://[^/]+)") ~= root():match("^(https?://[^/]+)") then return out end
else
if src:find("^https?://") then return src end
local mode = Client.mode()
if mode == "app" then return src end
if mode == "qread" then
out = src:find("^baseurl/") and (Client.base() .. src:sub(8))
or (Client.base() .. "/proxypng?url=" .. Text.urlEncode(src))
else
out = root() .. src:gsub("^__API_ROOT__", "")
end
end
if session.token then
local target, fragment = out:match("^([^#]*)(.*)$")
out = target .. (target:find("?", 1, true) and "&" or "?") .. "accessToken=" .. session.token .. fragment
end
return out
end
--- 封面地址。阅读 App 的原地址常要 Referer / 本地路径,一律走 /cover 代理。
---@param path string
---@return string
function Client.coverUrl(path)
if Client.mode() == "app" then return url("/cover", { path = path }) end
return Client.imageUrl(path)
end
---@param cb fun(rows: table[]|nil, err: string|nil)
---@param cfg table|nil 待保存配置;缺省读取当前配置
---@return { cancel: fun() }
function Client.shelfAsync(cb, cfg)
local params = { app = { refresh = 0 }, reader3 = { refresh = 0 }, qread = { version = "3.2.1" } }
return call("/getBookshelf", params[Client.mode(cfg)], 0.5, "shelf", function(data, err)
if type(data) ~= "table" then cb(nil, err); return end
cb(data)
end, cfg)
end
--- 书架分组(用户在阅读 App 里建的分组)。轻阅读没有这个接口,回 nil 即可。
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.groupsAsync(cb)
if Client.mode() == "qread" then return require("source.base").defer(cb, nil, "unsupported") end
return call("/getBookGroups", {}, 0.5, "shelf", function(data, err)
if type(data) ~= "table" then cb(nil, err); return end
cb(data)
end)
end
--- 目录。book_url + 书源(轻阅读必需,其余忽略)。
---@param book_url string
---@param origin string|nil
---@param cb fun(rows: table[]|nil, err: string|nil)
---@return { cancel: fun() }
function Client.chaptersAsync(book_url, origin, cb)
return call("/getChapterList", { url = book_url, bookSourceUrl = origin }, 1, "read", function(data, err)
if type(data) ~= "table" then cb(nil, err); return end
cb(data)
end)
end
--- 一章正文(0 基序号),纯文本;轻阅读回包是 `{ text }`。
---@param book_url string
---@param index integer
---@param origin string|nil
---@param cb fun(text: string|nil, err: string|nil)
---@return { cancel: fun() }
function Client.contentAsync(book_url, index, origin, cb)
local params = { url = book_url, index = index, bookSourceUrl = origin, type = origin and 0 or nil }
return call("/getBookContent", params, 1, "read", function(data, err)
local text = type(data) == "table" and data.text or data
if type(text) ~= "string" or text == "" then
require("utils.log").warn("legado empty chapter", book_url, index, type(text), err)
cb(nil, err or (_("阅读章节内容为空") .. " #" .. (index + 1)))
return
end
cb(text)
end)
end
local function reviewCall(path, params, cb)
if Client.mode() ~= "app" then
return require("source.base").defer(cb, nil, _("段评仅支持阅读 App 的 Web 服务"))
end
return call(path, params, 1, "read", cb)
end
---@param book_url string
---@param index integer 阅读目录里的 0 基序号
---@param cb function
---@return { cancel: fun() }
function Client.reviewSummaryAsync(book_url, index, cb)
return reviewCall("/getReviewSummary", { url = book_url, index = index }, cb)
end
---@param book_url string
---@param index integer
---@param paragraph integer
---@param data string
---@param page integer
---@param cursor string|nil
---@param cb function
---@return { cancel: fun() }
function Client.reviewDetailAsync(book_url, index, paragraph, data, page, cursor, cb)
return reviewCall("/getReviewDetail", {
url = book_url, index = index, paraIndex = paragraph, paraData = data, page = page, cursor = cursor,
}, cb)
end
---@param book_url string
---@param index integer
---@param paragraph integer
---@param data string
---@param review_id string
---@param page integer
---@param cb function
---@return { cancel: fun() }
function Client.reviewRepliesAsync(book_url, index, paragraph, data, review_id, page, cb)
return reviewCall("/getReviewReplies", {
url = book_url, index = index, paraIndex = paragraph, paraData = data, reviewId = review_id, page = page,
}, cb)
end
--- 上报阅读位置。row 是书架原行(name / author / bookUrl / origin)。
---@param row table
---@param pos { index: integer, title: string|nil, offset: integer }
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.saveProgressAsync(row, pos, cb)
local body = {
name = row.name,
author = row.author,
url = row.bookUrl,
index = pos.index,
durChapterIndex = pos.index,
durChapterPos = pos.offset,
durChapterTitle = pos.title or "",
durChapterTime = os.time() * 1000,
}
if Client.mode() == "qread" then
body = { url = row.bookUrl, index = pos.index, title = pos.title or "", pos = pos.offset }
end
return call("/saveBookProgress", body, 0.5, "write", function(_data, reason) cb(reason == nil or nil, reason) end)
end
--- 把书从阅读 App 书架移除,row 是书架原行。
---@param row table
---@param cb fun(ok: boolean|nil, err: string|nil)
---@return { cancel: fun() }
function Client.deleteBookAsync(row, cb)
return call("/deleteBook", row, 0.5, "write", function(_data, reason) cb(reason == nil or nil, reason) end)
end
return Client
@@ -0,0 +1,38 @@
return {
["本章讨论"] = "Chapter discussion",
["章节评论"] = "Chapter comments",
["他人段评(阅读 App)"] = "Paragraph comments (Legado app)",
["段评仅支持阅读 App 的 Web 服务"] = "Paragraph comments require the Legado app's web service",
["阅读段评位置无效"] = "Invalid Legado comment location",
["阅读段评分页位置无效"] = "Invalid Legado comment page position",
["阅读段评响应无效"] = "Invalid Legado comment response",
["书架与章节正文"] = "Bookshelf and chapter content",
["从服务端书架删除"] = "Remove from the server bookshelf",
["目录及整本缓存"] = "Table of contents and full-book caching",
["连接阅读 App、reader3 或轻阅读服务"] = "Connect to Legado, reader3 or a Qingyuedu service",
["打开「设置 → 书库 → 账号 → 开源阅读 → 阅读服务地址」。账号和密码重新填一遍,地址不用改,点「保存」。阅读 App 里如果改过密码,这里填新密码。"] = "Open Settings → Library → Account → Legado → Legado server address. Enter the username and password again, leave the address as it is, and tap Save. If you changed the password in the Legado app, enter the new one.",
["确定退出开源阅读?"] = "Sign out of Legado?",
["已配置"] = "Configured",
["章节目录保存失败"] = "Failed to save chapter list",
["开源阅读"] = "Legado",
["请在阅读 App 里添加书籍"] = "Add books in the Legado app",
["未配置阅读服务器地址"] = "Legado server address is not set",
["这本书不在阅读书架上"] = "This book is not on the Legado shelf",
["缺少阅读章节位置"] = "Missing Legado chapter position",
["阅读目录为空"] = "Legado table of contents is empty",
["阅读章节内容为空"] = "Chapter content is empty",
["阅读插图下载失败,请重试"] = "Failed to download chapter illustrations. Please retry.",
["阅读服务"] = "Legado server",
["账号(reader3 服务器版才需要)"] = "Account (reader3 server only)",
["阅读服务地址"] = "Legado server address",
["正在连接阅读服务…"] = "Connecting to Legado…",
["已连接,书架共 %1 本"] = "Connected, %1 books on the shelf",
["连接失败"] = "Connection failed",
["扫描局域网"] = "Scan the local network",
["正在扫描局域网…"] = "Scanning the local network…",
["没有找到阅读服务"] = "No Legado service found",
["没有局域网地址"] = "No local network address",
["选择阅读服务"] = "Choose a Legado service",
["进度同步"] = "Progress sync",
["连接开源阅读(Legado)服务"] = "Connect to an Open Reader (Legado) service",
}
@@ -0,0 +1,38 @@
return {
["本章讨论"] = "本章討論",
["章节评论"] = "章節評論",
["他人段评(阅读 App)"] = "他人段評(閱讀 App)",
["段评仅支持阅读 App 的 Web 服务"] = "段評僅支援閱讀 App 的 Web 服務",
["阅读段评位置无效"] = "閱讀段評位置無效",
["阅读段评分页位置无效"] = "閱讀段評分頁位置無效",
["阅读段评响应无效"] = "閱讀段評回應無效",
["书架与章节正文"] = "書架與章節正文",
["从服务端书架删除"] = "從伺服器書架刪除",
["目录及整本缓存"] = "目錄及整本快取",
["连接阅读 App、reader3 或轻阅读服务"] = "連接閱讀 App、reader3 或輕閱讀服務",
["打开「设置 → 书库 → 账号 → 开源阅读 → 阅读服务地址」。账号和密码重新填一遍,地址不用改,点「保存」。阅读 App 里如果改过密码,这里填新密码。"] = "打開「設定 → 書庫 → 帳號 → 開源閱讀 → 閱讀服務位址」。帳號和密碼重新填一遍,位址不用改,點「儲存」。閱讀 App 裡如果改過密碼,這裡填新密碼。",
["确定退出开源阅读?"] = "確定登出開源閱讀?",
["已配置"] = "已設定",
["章节目录保存失败"] = "章節目錄儲存失敗",
["开源阅读"] = "開源閱讀",
["请在阅读 App 里添加书籍"] = "請在閱讀 App 裡新增書籍",
["未配置阅读服务器地址"] = "未設定閱讀伺服器位址",
["这本书不在阅读书架上"] = "這本書不在閱讀書架上",
["缺少阅读章节位置"] = "缺少閱讀章節位置",
["阅读目录为空"] = "閱讀目錄為空",
["阅读章节内容为空"] = "閱讀章節內容為空",
["阅读插图下载失败,请重试"] = "閱讀插圖下載失敗,請重試",
["阅读服务"] = "閱讀服務",
["账号(reader3 服务器版才需要)"] = "帳號(僅 reader3 伺服器版需要)",
["阅读服务地址"] = "閱讀服務位址",
["正在连接阅读服务…"] = "正在連接閱讀服務…",
["已连接,书架共 %1 本"] = "已連接,書架共 %1 本",
["连接失败"] = "連接失敗",
["扫描局域网"] = "掃描區域網路",
["正在扫描局域网…"] = "正在掃描區域網路…",
["没有找到阅读服务"] = "沒有找到閱讀服務",
["没有局域网地址"] = "沒有區域網路位址",
["选择阅读服务"] = "選擇閱讀服務",
["进度同步"] = "進度同步",
["连接开源阅读(Legado)服务"] = "連接開源閱讀(Legado)服務",
}
@@ -0,0 +1,5 @@
return function()
local copy = {}
for k, v in pairs(require("moonsource_legado._meta")) do copy[k] = v end
return copy
end
@@ -0,0 +1,155 @@
--[[--
阅读(Legado)Web 服务数据映射(纯函数)。
@module koplugin.book.moonsource_legado.mapper
--]]
local Text = require("utils.text")
local Mapper = {}
local SOURCE_ID = "legado"
--- 封面走阅读服务器的 /cover 代理(原地址常要 Referer / 本地路径)。
---@param coverUrl fun(path: string): string
---@param row table
---@return string|nil
local function cover(coverUrl, row)
local path = row.customCoverUrl
if type(path) ~= "string" or path == "" then path = row.coverUrl end
if type(path) ~= "string" or path == "" then return nil end
return coverUrl(path)
end
--- 书的 group 是分组 id 的位掩码(id 为 2 的幂);返回命中的分组名,没有分组返回 nil。
local function groupNames(groups, mask)
local names = {}
mask = tonumber(mask) or 0
for _idx, g in ipairs(groups) do
local id = tonumber(g.groupId)
if id and id > 0 and type(g.groupName) == "string" and math.floor(mask / id) % 2 == 1 then
names[#names + 1] = g.groupName
end
end
return #names > 0 and table.concat(names, ",") or nil
end
--- 书架行 → Book[]。rows.groups 有值时分类取阅读 App 的书架分组(权威:没分组就是未分类);否则退回书源标签 kind。bookUrl 是书在阅读 App 里的唯一键。
---@param coverUrl fun(path: string): string 封面代理地址构造(Client.coverUrl)
---@param rows table[]
---@return Book[]
function Mapper.shelfList(coverUrl, rows)
local out, groups = {}, rows.groups
local now = os.time()
local n = #rows
for idx, row in ipairs(rows) do
if type(row.bookUrl) == "string" and row.bookUrl ~= "" then
local dur_time = tonumber(row.durChapterTime)
local read_at = (dur_time and dur_time > 1000000000)
and math.floor(dur_time > 100000000000 and dur_time / 1000 or dur_time) or nil
out[#out + 1] = {
source_id = SOURCE_ID,
stable_id = row.bookUrl,
title = row.name,
authors = row.author,
category = groups and groupNames(groups, row.group) or (not groups and row.kind or nil),
category_authoritative = groups and true or nil,
intro = row.intro and Text.stripHtml(row.intro),
cover = cover(coverUrl, row),
read_at = read_at,
inserted_at = now + (n - idx),
}
end
end
return out
end
--- 书架行里的阅读位置(序号 0 基)。没读过返回 nil。
---@param row table|nil
---@return { index: integer, title: string|nil, offset: integer }|nil
function Mapper.readPos(row)
local index = row and tonumber(row.durChapterIndex)
if not index or (index == 0 and (tonumber(row.durChapterTime) or 0) <= 0) then return nil end
local title = row.durChapterTitle
return { index = index, title = type(title) == "string" and title ~= "" and title or nil,
offset = tonumber(row.durChapterPos) or 0 }
end
--- 目录:按服务端顺序,idx 连续,uid 是 0 基章节序号;origin 是书源(轻阅读取正文要用,随目录落盘)。
---@param rows table[]
---@param origin string|nil
---@return BookChapter[]
function Mapper.toc(rows, origin)
local toc = {}
for i, row in ipairs(rows) do
toc[i] = { idx = i, uid = tostring(tonumber(row.index) or (i - 1)), title = row.title, origin = origin }
end
return toc
end
--- 正文纯文本里夹着 ``<img>``(图片章、网站插图):图片留成真标签,其余照旧转义,否则标签原样显示。
--- 懒加载占位用的 data:image/svg+xml 没有内容,直接丢掉;src 尾部 Legado 的 ``,{请求头 JSON}`` 剥掉。
---@param title string
---@param text string
---@param imageUrl fun(src: string): string 相对图片地址补全(Client.imageUrl)
---@param reviews boolean|nil 保存阅读 App 的段落编号
---@return string
function Mapper.chapterHtml(title, text, imageUrl, reviews)
if reviews then
local paragraph = 0
text = (text:gsub("\n+", "\n") .. "\n"):gsub("(.-)\n", function(line)
paragraph = paragraph + 1
return line .. "\2" .. paragraph .. "\2\n"
end)
end
local imgs = {}
text = text:gsub("<img%s[^>]*>", function(tag)
local src = tag:match('src%s*=%s*"([^"]*)"') or tag:match("src%s*=%s*'([^']*)'")
src = src and src:gsub(",%s*{.*$", "")
if not src or src == "" or src:find("^data:image/svg") then return "" end
imgs[#imgs + 1] = '<img src="' .. Text.xmlEscape(imageUrl(Text.xmlDecode(src))) .. '"/>'
return "\1" .. #imgs .. "\1"
end)
local html = Text.chapterHtml(title, text)
if reviews then
html = html:gsub("<p>(.-)\2(%d+)\2</p>", function(body, paragraph)
body = Text.rtrim(body)
if body == "" then return "" end
return '<p id="moon-legado-paragraph-' .. paragraph .. '">' .. body .. "</p>"
end)
end
return (html:gsub("\1(%d+)\1", function(n) return imgs[tonumber(n)] end))
end
--- reader3 本地 EPUB 资源 → 正文片段;图片按章节 URL 解析并规范化属性,供公共 Assets 落地。
---@param title string
---@param raw string
---@param base string
---@param imageUrl fun(src: string, base: string): string
---@return string|nil
function Mapper.assetHtml(title, raw, base, imageUrl)
local inner = Text.htmlBodyFragment(raw)
:gsub("<script[^>]*>.-</script>", "")
:gsub("<style[^>]*>.-</style>", "")
local function svgToImg(block)
local href = block:match('xlink:href%s*=%s*"([^"]*)"')
or block:match("xlink:href%s*=%s*'([^']*)'")
or block:match('href%s*=%s*"([^"]*)"')
or block:match("href%s*=%s*'([^']*)'")
if not href or href == "" then return "" end
return '<img src="' .. Text.xmlEscape(Text.xmlDecode(href)) .. '"/>'
end
inner = inner:gsub("<svg[^>]*>.-</svg>", svgToImg)
:gsub("<image%s[^>]-/>", svgToImg)
inner = inner:gsub("<img%s+[^>]*>", function(tag)
return (tag:gsub("src%s*=%s*(['\"])(.-)%1", function(_quote, src)
if src == "" then return 'src=""' end
local url = Text.escapeUrl(imageUrl(Text.xmlDecode(src), base))
return 'src="' .. Text.xmlEscape(url) .. '"'
end, 1))
end)
if not inner:find("<img", 1, true) and Text.stripHtml(inner) == "" then return nil end
return "<h1>" .. Text.xmlEscape(title) .. "</h1>\n" .. inner
end
return Mapper
@@ -0,0 +1,129 @@
--[[--
阅读 App 段评映射。range 保存 { 段号, paraData },评论 id 保存同一上下文及原始 id;
分页位置保存 { page, cursor }。这些不透明键随公共段评缓存落盘,不依赖源实例的临时状态。
段落按章节里的 moon-legado-paragraph-N 标记定位,图片或被丢弃的空段不能改变源站段号。
@module koplugin.book.moonsource_legado.reviews
--]]
local JSON = require("json")
local Locate = require("book.review_locate")
local Text = require("utils.text")
local _ = require("l10n").get("moonsource_legado")
local Reviews = {}
---@param range string
---@param reply boolean|nil
---@return table|nil, string|nil
function Reviews.context(range, reply)
local ok, value = pcall(JSON.decode, range)
if not ok or type(value) ~= "table" or type(value[1]) ~= "number"
or (value[1] ~= -1 and (value[1] < 1 or value[1] % 1 ~= 0))
or type(value[2]) ~= "string"
or (reply and (type(value[3]) ~= "string" or value[3] == "")) then
return nil, _("阅读段评位置无效")
end
return value
end
---@param data table
---@return table[]|nil, string|nil
function Reviews.hotspots(data)
if type(data) ~= "table" or type(data.counts) ~= "table" or type(data.keys) ~= "table" then
return nil, _("阅读段评响应无效")
end
local out = {}
for key, count in pairs(data.counts) do
local paragraph = tonumber(key)
local value = data.keys[key]
if not paragraph or paragraph % 1 ~= 0 or type(count) ~= "number" or count < 0 or count % 1 ~= 0
or (value ~= nil and type(value) ~= "string") then
return nil, _("阅读段评响应无效")
end
if (paragraph > 0 or paragraph == -1) and count > 0 then
out[#out + 1] = {
range = JSON.encode({ paragraph, value and value ~= "" and value or tostring(paragraph) }),
paragraph = paragraph, text = "", total = count,
}
end
end
table.sort(out, function(a, b) return a.paragraph < b.paragraph end)
return out
end
---@param max_idx integer|string
---@return integer|nil, string|nil, string|nil
function Reviews.pagination(max_idx)
if max_idx == 0 then return 1 end
local ok, value = pcall(JSON.decode, max_idx)
if not ok or type(value) ~= "table" or type(value.page) ~= "number" or value.page < 1
or value.page % 1 ~= 0 or (value.cursor ~= nil and type(value.cursor) ~= "string") then
return nil, nil, _("阅读段评分页位置无效")
end
return value.page + 1, value.cursor
end
---@param data table
---@param context table
---@param page integer
---@return table|nil, string|nil
function Reviews.page(data, context, page)
if type(data) ~= "table" or type(data.items) ~= "table" or type(data.hasMore) ~= "boolean"
or (data.nextCursor ~= nil and type(data.nextCursor) ~= "string")
or (#data.items == 0 and next(data.items) ~= nil) then
return nil, _("阅读段评响应无效")
end
local items = {}
for _idx, row in ipairs(data.items) do
if type(row) ~= "table" or (row.content ~= nil and type(row.content) ~= "string")
or (row.name ~= nil and type(row.name) ~= "string")
or (row.id ~= nil and type(row.id) ~= "string") then
return nil, _("阅读段评响应无效")
end
local images = {}
if type(row.imageUrl) == "string" and row.imageUrl:match("^https?://") then
images[1] = { url = row.imageUrl, width = 0, height = 0 }
end
local has_id = row.id ~= nil and row.id ~= ""
items[#items + 1] = {
id = has_id and JSON.encode({ context[1], context[2], row.id }) or "",
author = row.name or "", content = Text.stripHtml(row.content or ""),
time = type(row.time) == "string" and row.time or "",
likes = tonumber(row.likeCount) or 0,
replies = has_id and (tonumber(row.replyCount) or 0) or 0,
reply_to = row.replyToName, images = images,
}
end
return {
items = items, total = #items == 0 and 0 or nil,
max_idx = JSON.encode({ page = page, cursor = data.nextCursor }),
more = #items > 0 and data.hasMore,
}
end
---@param hotspots table[]
---@param html string
---@return table[]
function Reviews.locate(hotspots, html)
local paras = {}
for tag, body in html:gmatch("(<p%s+[^>]*>)(.-)</p>") do
local paragraph = tag:match('id="moon%-legado%-paragraph%-(%d+)"')
if paragraph then paras[paragraph] = Text.stripHtml(body) end
end
if #hotspots > 0 and next(paras) == nil then
require("utils.log").warn("legado reviews: cached chapter has no paragraph anchors; download it again")
return {}
end
local numbered, ranges = {}, {}
for _idx, hotspot in ipairs(hotspots) do
local paragraph = tostring(hotspot.paragraph)
numbered[#numbered + 1] = { range = paragraph, total = hotspot.total }
ranges[paragraph] = hotspot.range
end
local spots = Locate.locate(paras, numbered, html)
for _idx, spot in ipairs(spots) do spot.range = ranges[spot.range] end
return spots
end
return Reviews
@@ -0,0 +1,189 @@
--[[--
手动扫描局域网里的阅读 App Web 服务。
阅读不广播自己。只扫本机所在的 IPv4 /24,只探已经保存的端口(没配过就是 1122),
端口通了再拉一次 /getBookshelf,回包长得像书架才算。
@module koplugin.book.moonsource_legado.scan
--]]
local Scan = {}
local DEFAULT_PORT = 1122
local PARALLEL = 32
local CONNECT_TIMEOUT = 0.6
local POLL = 0.05
-- 家用网段里阅读服务就一两台。端口全通是网关在假装连上,再打 HTTP 没有意义。
local MAX_OPEN = 8
---@param ip string
---@return string[]
function Scan.hosts(ip)
local a, b, c, d = ip:match("^(%d+)%.(%d+)%.(%d+)%.(%d+)$")
a, b, c, d = tonumber(a), tonumber(b), tonumber(c), tonumber(d)
if not a or a > 255 or b > 255 or c > 255 or d > 255 or a == 0 then return {} end
local prefix = string.format("%d.%d.%d.", a, b, c)
local hosts = {}
for octet = 1, 254 do
if octet ~= d then hosts[#hosts + 1] = prefix .. octet end
end
return hosts
end
--- 本机出口 IPv4。UDP setpeername 只查路由,不发包。
---@return string|nil
function Scan.localIP()
local udp = require("socket").udp()
if not udp then return nil end
local ip
if udp:setpeername("203.0.113.1", "53") then
ip = udp:getsockname()
end
udp:close()
if type(ip) ~= "string" or #Scan.hosts(ip) == 0 then return nil end
return ip
end
--- 已保存的阅读 App 端口;没配过或不是 App 地址就用默认端口。
---@return integer
local function savedPort()
local Client = require("moonsource_legado.client")
local base = Client.mode() == "app" and Client.base()
local port = tonumber(base and base:match("^https?://[^/:]+:(%d+)$"))
return port and port >= 1 and port <= 65535 and port or DEFAULT_PORT
end
--- `{ isSuccess, errorMsg, data: [] | [book, ...] }`。对象塞在 data 里不算书架。
---@param raw string|nil
---@return boolean
function Scan.isShelf(raw)
if type(raw) ~= "string" or raw == "" then return false end
local ok, wire = pcall(require("json").decode, raw)
if not ok or type(wire) ~= "table" or wire.isSuccess ~= true or type(wire.errorMsg) ~= "string" then
return false
end
if type(wire.data) ~= "table" then return false end
if wire.data[1] ~= nil then return type(wire.data[1]) == "table" end
return next(wire.data) == nil
end
---@param current table
local function abort(current)
current.cancelled = true
require("ui/uimanager"):unschedule(current.poll)
for _idx, item in ipairs(current.pending) do item.sock:close() end
for _idx, job in ipairs(current.jobs) do job.cancel() end
end
local function take(current)
local socket = current.socket
while #current.pending < PARALLEL and current.cursor <= #current.hosts do
local host = current.hosts[current.cursor]
current.cursor = current.cursor + 1
local sock = socket.tcp()
if not sock then
current.cursor = #current.hosts + 1
return
end
sock:settimeout(0)
local ok, err = sock:connect(host, current.port)
if ok or err == "already connected" then
sock:close()
current.open[#current.open + 1] = host
elseif err == "timeout" then
current.pending[#current.pending + 1] = {
sock = sock, host = host, deadline = socket.gettime() + CONNECT_TIMEOUT,
}
else
sock:close()
end
end
end
local function reap(current)
if #current.pending == 0 then return end
local socks = {}
for idx, item in ipairs(current.pending) do socks[idx] = item.sock end
local _recv, writable = current.socket.select({}, socks, 0)
if type(writable) ~= "table" then writable = {} end
local ready = {}
for _idx, sock in ipairs(writable) do ready[sock] = true end
local now = current.socket.gettime()
local left = {}
for _idx, item in ipairs(current.pending) do
if ready[item.sock] then
local ok, err = item.sock:connect(item.host, current.port)
item.sock:close()
if ok or err == "already connected" then
current.open[#current.open + 1] = item.host
end
elseif now >= item.deadline then
item.sock:close()
else
left[#left + 1] = item
end
end
current.pending = left
end
local function verify(current)
if #current.open == 0 or #current.open > MAX_OPEN then
current.cb({})
return
end
local Timeout = require("http.timeout")
local Request = require("http.request")
local left = #current.open
local found = {}
for _idx, host in ipairs(current.open) do
local address = "http://" .. host .. ":" .. current.port
current.jobs[#current.jobs + 1] = Request.get(address .. "/getBookshelf?refresh=0", {
accept = "application/json",
timeout = Timeout.net(0.1),
connect_timeout = Timeout.net(0.05),
}, function(raw)
if current.cancelled then return end
if Scan.isShelf(raw) then found[#found + 1] = address end
left = left - 1
if left == 0 then current.cb(found) end
end)
end
end
--- 扫完回调 `cb(addresses)` 或 `cb(nil, "no-ip")`。回调一定在返回之后;取消后不再回调。
---@param cb fun(found: string[]|nil, err: string|nil)
---@return { cancel: fun() }
function Scan.find(cb)
local UIManager = require("ui/uimanager")
local ip = Scan.localIP()
local current = {
cb = cb,
pending = {},
open = {},
jobs = {},
hosts = ip and Scan.hosts(ip) or {},
cursor = 1,
port = savedPort(),
socket = require("socket"),
}
function current.poll()
if current.cancelled then return end
reap(current)
take(current)
if #current.pending > 0 or current.cursor <= #current.hosts then
UIManager:scheduleIn(POLL, current.poll)
else
verify(current)
end
end
if ip then
UIManager:scheduleIn(POLL, current.poll)
else
UIManager:nextTick(function()
if not current.cancelled then cb(nil, "no-ip") end
end)
end
return { cancel = function() abort(current) end }
end
return Scan
@@ -0,0 +1,177 @@
--[[--
阅读(Legado)源设置:Web 服务地址。
在阅读 App「我的 → Web 服务」打开服务,把页面上的地址(如 http://192.168.1.8:1122)填进来;
手机 IP 会变,也可以扫本机所在网段,认端口上的阅读服务。
reader3 服务器版地址带 /reader3 后缀(如 http://host:8080/reader3)、轻阅读带 /api/5 后缀,
并填账号密码(后端类型按后缀判断);
保存时先拉一次书架校验,通过才落盘并重载源。
@module koplugin.book.moonsource_legado.setting
--]]
local _ = require("l10n").get("moonsource_legado")
local T = require("ffi/util").template
local SOURCE_ID = "legado"
local Setting = {}
---@return string, boolean
function Setting.rowStatus()
local on = require("moonsource_legado.client").base() ~= nil
return on and _("已配置") or _("未配置"), on
end
---@param address string
---@param user string
---@param password string
local function save(address, user, password)
local Toast = require("ui.themes.widgets.toast")
local settings = require("utils.settings")
local cfg = settings.getSource(SOURCE_ID)
local previous_user = cfg.username or ""
local next_cfg = { server_address = address, username = user ~= "" and user or nil,
password = password ~= "" and password or nil }
local function commit()
cfg.server_address, cfg.username, cfg.password = next_cfg.server_address, next_cfg.username, next_cfg.password
settings.saveSource(SOURCE_ID, cfg)
end
local Client = require("moonsource_legado.client")
local waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("开源阅读"), text = _("正在连接阅读服务…"), dismissable = false,
}
waiting:show()
Client.shelfAsync(function(rows, err)
waiting:close()
if not rows then
Toast:new{ text = err or _("连接失败"), timeout = 3 }:show()
return
end
-- 手机 IP 会变化,地址不是书籍身份;换账号也只准备同步,不清记录。
if previous_user ~= user then
if not require("source.logout").replaceLibrary(SOURCE_ID, commit) then
Toast:new{ text = _("准备本地同步失败"), timeout = 3 }:show()
return
end
else
if cfg.server_address ~= address then require("source.logout").abort(SOURCE_ID) end
commit()
require("source.registry").reload()
end
Toast:new{ text = T(_("已连接,书架共 %1 本"), #rows), timeout = 2 }:show()
end, next_cfg)
end
local scanning = false
local function scan()
if scanning then return end
local NetworkMgr = require("ui/network/manager")
NetworkMgr:runWhenConnected(function()
if scanning then return end
scanning = true
local waiting, handle, closed
waiting = require("ui.themes.widgets.progress_dialog"):new{
title = _("开源阅读"),
text = _("正在扫描局域网…"),
dismissable = false,
on_cancel = function()
-- 弹窗自己先关。这里只停扫描。
if closed then return end
closed = true
scanning = false
if handle then handle.cancel() end
end,
}
waiting:show()
handle = require("moonsource_legado.scan").find(function(found, err)
if closed then return end
closed = true
scanning = false
waiting:close()
local Toast = require("ui.themes.widgets.toast")
if type(found) ~= "table" or #found == 0 then
local text = err == "no-ip" and _("没有局域网地址") or _("没有找到阅读服务")
Toast:new{ text = text, timeout = 3 }:show()
return
end
local cfg = require("utils.settings").getSource(SOURCE_ID)
local user, password = cfg.username or "", cfg.password or ""
if #found == 1 then
save(found[1], user, password)
return
end
local items = {}
for _idx, address in ipairs(found) do
items[#items + 1] = { text = address, value = address }
end
require("ui.themes.widgets.list"):new{
title = _("选择阅读服务"),
items = items,
on_select = function(value) save(value, user, password) end,
}:show()
end)
end)
end
local function edit()
local cfg = require("utils.settings").getSource(SOURCE_ID)
require("ui.themes.widgets.input"):new{
title = _("阅读服务"),
fields = {
{ text = require("moonsource_legado.client").base() or "", hint = "http://192.168.1.8:1122" },
{ text = cfg.username or "", hint = _("账号(reader3 服务器版才需要)") },
{ text = cfg.password or "", hint = _("密码"), text_type = "password" },
},
ok_text = _("保存"),
callback = function(value, user, password)
local Text = require("utils.text")
local address = Text.stripWhitespace(value)
if address == "" then
require("source.logout").abort(SOURCE_ID)
cfg.server_address = nil
require("utils.settings").saveSource(SOURCE_ID, cfg)
require("source.registry").reload()
return
end
require("ui/network/manager"):runWhenConnected(function()
save(address, Text.stripWhitespace(user), password)
end)
end,
}:show()
end
---@param plugin table|nil
---@return table[]
function Setting.rows(plugin)
local rows = {
function(iw)
local status, status_on = Setting.rowStatus()
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true, kind = "nav", icon = "dns", title = _("阅读服务地址"),
status = require("moonsource_legado.client").base() or status, status_on = status_on,
callback = edit,
})
end,
function(iw)
return require("ui.themes.widgets.row").widget({
width = iw, chevron = true, kind = "nav", icon = "wifi_find", title = _("扫描局域网"),
callback = scan,
})
end,
}
if require("moonsource_legado.client").mode() == "app" then
rows[#rows + 1] = require("source.review_setting").row(SOURCE_ID, plugin)
end
if require("moonsource_legado.client").base() ~= nil then
rows[#rows + 1] = require("source.logout").row(SOURCE_ID, _("确定退出开源阅读?"), function()
local settings = require("utils.settings")
local cfg = settings.getSource(SOURCE_ID)
cfg.server_address, cfg.username, cfg.password = nil, nil, nil
settings.saveSource(SOURCE_ID, cfg)
end)
end
return rows
end
return Setting
@@ -0,0 +1,381 @@
--[[--
阅读(Legado / 开源阅读)数据源。
直连阅读 App 的 Web 服务,或 reader3 服务器版(地址可带 /reader3 前缀,再配账号密码,setting.lua 配置)。书架只拉不加(书在阅读 App 里添加),
目录 / 正文按章落盘走公共 source/chapter;进度只到章,开书从书架行的 durChapterIndex 拉,
关书经 /saveBookProgress 上报。笔记和统计没有接口。
@module koplugin.book.moonsource_legado.source
--]]
local Client = require("moonsource_legado.client")
local Mapper = require("moonsource_legado.mapper")
local Text = require("utils.text")
local Request = require("http.request")
local Assets = require("source.assets")
local Paths = require("utils.paths")
local Shelf = require("source.shelf")
local SourceBase = require("source.base")
local Toc = require("source.toc")
local _ = require("l10n").get("moonsource_legado")
local Legado = {}
---@return BookSourceMeta
function Legado.meta()
return require("moonsource_legado.loadmeta")()
end
---@class LegadoSource : SourceBase
local Source = setmetatable({}, { __index = SourceBase })
Source.__index = Source
---@return LegadoSource
function Legado.new()
local meta = Legado.meta()
return setmetatable({ id = meta.id, name = meta.name, type = meta.type }, Source)
end
---@return boolean
function Source:configured()
return Client.base() ~= nil
end
---@param rows table[]
---@param stable_id string
---@return table|nil
local function findRow(rows, stable_id)
for _idx, row in ipairs(rows) do
if row.bookUrl == stable_id then return row end
end
return nil
end
--- 书架远端:Shelf.syncAsync 要的三个冒号方法。书只能在阅读 App 里加,本地没有「加入」入口。
local Remote = {}
--- 书架 + 分组:分组取不到(旧版 App / 轻阅读)不影响同步,分类退回书源标签。
function Remote:shelfSyncAsync(cb)
local cancelled, job = false, nil
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
job = Client.groupsAsync(function(groups)
if cancelled then return end
rows.groups = groups
cb(rows)
end)
end)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
function Remote:addToShelfAsync(_stable_id, cb)
return SourceBase.defer(cb, nil, _("请在阅读 App 里添加书籍"))
end
--- 远端已经没有这本书就算删除完成。
function Remote:removeFromShelfAsync(stable_id, cb)
local cancelled, job = false, nil
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
local row = findRow(rows, stable_id)
if not row then cb(true); return end
job = Client.deleteBookAsync(row, cb)
end)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
function Source:syncBooksAsync(opts, cb)
if not self:configured() then return SourceBase.skipped(cb, "legado not configured") end
opts = opts or {}
local sync_opts = {}
for k, v in pairs(opts) do sync_opts[k] = v end
sync_opts.inserted_at_from_row = true
return Shelf.syncAsync(self.id, Remote, function(rows) return Mapper.shelfList(Client.coverUrl, rows) end, sync_opts, cb)
end
--- 取书架行再交给 fn(row, toc, done);没配置 / 不在书架上 / 目录空都走 cb 报错。
--- fn 要再发请求就返回它的句柄,取消会传过去;done 是取消后不再投递的 cb。
---@param identity BookIdentity
---@param cb function
---@param fn fun(row: table, toc: BookChapter[], done: function): { cancel: fun() }|nil
---@return { cancel: fun() }
function Source:withRow(identity, cb, fn)
if not self:configured() then return SourceBase.defer(cb, nil, _("未配置阅读服务器地址")) end
local cancelled, job = false, nil
local function done(...)
if not cancelled then cb(...) end
end
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
local row = findRow(rows, identity.stable_id)
if not row then cb(nil, _("这本书不在阅读书架上")); return end
job = self:loadTocAsync(identity, function(toc, reason)
if cancelled then return end
if not toc then cb(nil, reason); return end
job = fn(row, toc, done) or job
end)
end)
return { cancel = function()
cancelled = true
job.cancel()
end }
end
function Source:getProgressAsync(identity, cb)
return self:withRow(identity, cb, function(row, toc)
local read = Mapper.readPos(row)
if not read then cb(nil, nil, { empty = true }); return end
local idx = math.min(read.index + 1, #toc)
cb({
chapter_idx = idx,
chapter_title = read.title or toc[idx].title,
fraction = (idx - 1) / #toc,
extra = { chapter_uid = toc[idx].uid, chapter_idx = idx },
})
end)
end
function Source:putProgressAsync(identity, pos, cb)
return self:withRow(identity, cb, function(row, toc, done)
local idx = tonumber(pos.chapter_idx) or tonumber(identity.chapter_idx)
local chapter = idx and toc[idx]
if not chapter then cb(nil, _("缺少阅读章节位置")); return end
local read = Mapper.readPos(row)
local same = read and read.index == idx - 1
return Client.saveProgressAsync(row, {
index = idx - 1,
title = chapter.title,
offset = same and read.offset or 0,
}, done)
end)
end
--- 书库里已有的元数据。
function Source:getDetailAsync(identity, cb)
return SourceBase.defer(cb, identity.book or require("book.books_db").get(self.id, identity.stable_id))
end
--- 强制拉目录并写回;失败由调用方继续用旧缓存。轻阅读按书源取,先从书架行查 origin。
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@return { cancel: fun() }
local function fetchTocAsync(self, identity, cb)
local cancelled, job = false, nil
local function fetch(origin)
job = Client.chaptersAsync(identity.stable_id, origin, function(rows, err)
if cancelled then return end
if not rows then cb(nil, err); return end
local toc = Mapper.toc(rows, origin)
if #toc == 0 then cb(nil, _("阅读目录为空")); return end
if not Toc.put(self.id, identity.stable_id, toc) then cb(nil, _("章节目录保存失败")); return end
cb(toc)
end)
end
if Client.mode() ~= "qread" then
fetch(nil)
else
job = Client.shelfAsync(function(rows, err)
if cancelled then return end
local row = rows and findRow(rows, identity.stable_id)
if not row then cb(nil, err or _("这本书不在阅读书架上")); return end
fetch(row.origin)
end)
end
return { cancel = function()
cancelled = true
job.cancel()
end }
end
---@param identity BookIdentity
---@param cb fun(toc: BookChapter[]|nil, err: string|nil)
---@param force boolean|nil 真=跳过缓存强制拉
---@return { cancel: fun() }
function Source:loadTocAsync(identity, cb, force)
if not force then
local cached = Toc.read(self.id, identity.stable_id)
if cached and #cached > 0 then
return SourceBase.defer(cb, cached)
end
end
return fetchTocAsync(self, identity, cb)
end
Source.refreshTocAsync = fetchTocAsync
---@return ChapterFetchContent
local function contentFetcher(reviews)
return function(identity, chapter, done)
local cancelled = false
---@type { job: CancelHandle|nil }|nil
local active
---@param start fun(cb: function): CancelHandle|nil
---@param finish function
local function run(start, finish)
local stage = {}
active = stage
stage.job = start(function(...)
if cancelled or active ~= stage then return end
active = nil
finish(...)
end)
end
local function fetchAsset(path)
local url = Text.escapeUrl(Client.imageUrl(path))
run(function(cb)
return Request.get(url, { timeout = 20 }, cb)
end, function(raw, err)
if not raw or raw == "" then done(nil, err or _("阅读章节内容为空")); return end
local html = Mapper.assetHtml(chapter.title, raw, url, Client.imageUrl)
if not html then done(nil, _("阅读章节内容为空")); return end
local image_err
run(function(cb)
return Assets.localizeAsync(html, Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/images",
function(image_url, on_done)
return Request.get(image_url, { timeout = 45 }, function(data, reason)
if reason then image_err = tostring(reason) end
on_done(data, reason)
end)
end, cb)
end, function(localized)
if Text.hasRemoteImageSrc(localized) then
done(nil, image_err or _("阅读插图下载失败,请重试"))
return
end
done({ title = chapter.title, html = localized })
end)
end)
end
run(function(cb)
return Client.contentAsync(identity.stable_id, tonumber(chapter.uid), chapter.origin, cb)
end, function(text, err)
if not text then done(nil, err); return end
-- 只有 reader3 的明确资源前缀才是 EPUB 路径,不能按 .html 后缀猜正文类型。
if Client.mode() == "reader3" and text:find("^/book%-assets/") then
fetchAsset(text)
return
end
local html = Mapper.chapterHtml(chapter.title, text, Client.imageUrl, Client.mode() == "app")
-- 只有 <h1> 没有段落 = 服务器给的是空白正文,不能当成功落盘缓存。
if not html:find("<p", 1, true) then done(nil, _("阅读章节内容为空")); return end
done({ title = chapter.title,
html = reviews and require("book.review_locate").prepareChapterEnd(html) or html })
end)
return { cancel = function()
cancelled = true
local job = active and active.job
active = nil
if job then job.cancel() end
end }
end
end
function Source:openBookAsync(identity, opts, cb)
local Chapter = require("source.chapter")
local reviews = self:paragraphReviewsEnabled()
local open = opts and opts.chapter_idx and Chapter.openAsync or Chapter.openWithUi
return open(self, identity, identity.book, opts, {
loadToc = function(ref, done) return self:loadTocAsync(ref, done) end,
fetchContent = contentFetcher(reviews),
reuse = reviews and require("book.review_locate").reuseChapterEnd or nil,
}, cb)
end
function Source:prefetchChaptersAsync(identity, toc, from_idx, count, cb)
local reviews = self:paragraphReviewsEnabled()
return require("source.chapter").prefetchAsync(identity, identity.book, toc, from_idx, count, {
fetchContent = contentFetcher(reviews),
reuse = reviews and require("book.review_locate").reuseChapterEnd or nil,
}, cb)
end
function Source:cacheAllChaptersAsync(identity, on_progress, cb, range)
return require("source.chapter").cacheAllAsync(self, identity, contentFetcher(self:paragraphReviewsEnabled()),
on_progress, cb, 0, range)
end
function Source:paragraphReviewsEnabled()
return Client.mode() == "app" and require("source.review_setting").enabled(self.id)
end
local function hotspotsAsync(self, identity, cb)
return require("book.review_cache").hotspotsAsync(identity, function(done)
return require("source.with_chapter_uid").run(self, identity, _("缺少阅读章节位置"), function(uid, finish)
return Client.reviewSummaryAsync(identity.stable_id, tonumber(uid), function(data, err)
if data == nil then finish(nil, err or _("阅读段评响应无效")); return end
finish(require("moonsource_legado.reviews").hotspots(data))
end)
end, done)
end, cb)
end
function Source:paragraphHotspotsAsync(identity, cb)
return hotspotsAsync(self, identity, function(list, err)
if not list then cb(nil, err); return end
local out = {}
for _idx, spot in ipairs(list) do
if spot.paragraph > 0 then out[#out + 1] = spot end
end
cb(out)
end)
end
function Source:chapterReviewHotspotsAsync(identity, cb)
return hotspotsAsync(self, identity, function(list, err)
if not list then cb(nil, err); return end
local out = {}
for _idx, spot in ipairs(list) do
if spot.paragraph == -1 then
out[#out + 1] = { range = spot.range, text = _("本章讨论"), total = spot.total,
badge = tostring(spot.total), heading = _("章节评论"),
anchor = require("book.review_locate").CHAPTER_ANCHOR }
end
end
cb(out)
end)
end
function Source:locateHotspots(hotspots, html)
return require("moonsource_legado.reviews").locate(hotspots, html)
end
local function reviewPageAsync(self, identity, range, max_idx, reply, cb)
local Reviews = require("moonsource_legado.reviews")
local context, err = Reviews.context(range, reply)
if not context then return SourceBase.defer(cb, nil, err) end
local page, cursor, reason = Reviews.pagination(max_idx)
if not page then return SourceBase.defer(cb, nil, reason) end
return require("book.review_cache").pageAsync(identity, (reply and "reply:" or "") .. range, max_idx, function(done)
return require("source.with_chapter_uid").run(self, identity, _("缺少阅读章节位置"), function(uid, finish)
local function onPage(data, error)
if data == nil then finish(nil, error or _("阅读段评响应无效")); return end
finish(Reviews.page(data, context, page))
end
if reply then
return Client.reviewRepliesAsync(identity.stable_id, tonumber(uid), context[1], context[2],
context[3], page, onPage)
end
return Client.reviewDetailAsync(identity.stable_id, tonumber(uid), context[1], context[2],
page, cursor, onPage)
end, done)
end, cb)
end
function Source:paragraphReviewPageAsync(identity, range, max_idx, cb)
return reviewPageAsync(self, identity, range, max_idx, false, cb)
end
function Source:paragraphReviewRepliesAsync(identity, review_id, max_idx, cb)
return reviewPageAsync(self, identity, review_id, max_idx, true, cb)
end
return Legado
@@ -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
+170
View File
@@ -0,0 +1,170 @@
--[[--
reader3 本地 EPUB:正文资源与图片的成功、失败、取消及同步回调接力。
@module tests.moonsource_legado.source_content_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, assign-type-mismatch
local Assert = require("support.assert")
local JSONStub = require("support.json_stub")
local Paths = require("utils.paths")
local cfg = { server_address = "http://reader.example/reader3" }
local requests, sync_replies, writes = {}, {}, {}
local payload, reason, calls
local write_failed = false
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end }
end
package.preload["json"] = function()
return { encode = JSONStub.encode, decode = JSONStub.decode }
end
package.preload["http.request"] = function()
local function request(url, cb)
local entry = { url = url, cb = cb, cancelled = false }
requests[#requests + 1] = entry
local reply = table.remove(sync_replies, 1)
if reply then cb(reply.body, reply.err) end
return { cancel = function() entry.cancelled = true end }
end
return {
get = function(url, _opts, cb) return request(url, cb) end,
post = function(url, _body, _opts, cb) return request(url, cb) end,
}
end
package.preload["source.chapter"] = function()
return {
prefetchAsync = function(identity, _book, toc, _from, _count, ops, cb)
return ops.fetchContent(identity, toc[1], cb)
end,
}
end
for _idx, name in ipairs({ "utils.settings", "json", "http.request", "source.chapter",
"source.assets", "moonsource_legado.source", "moonsource_legado.client" }) do
package.loaded[name] = nil
end
local Assets = require("source.assets")
Assets.materializeImage = function(dir, data)
writes[#writes + 1] = { dir = dir, data = data }
if write_failed then return nil end
return "images/fixture.png"
end
local source = require("moonsource_legado.source").new()
local identity = { source_id = "legado", stable_id = "legado-content-fixture", book = {} }
local toc = { { idx = 1, uid = "0", title = "章" } }
local resource = "/book-assets/book/Text/chapter%20one.xhtml"
local image_body = '<body><img src = "../Images/cover%20one.png"/></body>'
local function wire(text) return JSONStub.encode({ isSuccess = true, data = text }) end
local function start(replies)
requests, writes, sync_replies = {}, {}, replies or {}
payload, reason, calls, write_failed = nil, nil, 0, false
return source:prefetchChaptersAsync(identity, toc, 1, 1, function(value, err)
payload, reason, calls = value, err, calls + 1
end)
end
-- 普通正文不能因为以 .html 结尾而被当作资源,包括 App 和轻阅读。
for _idx, address in ipairs({ "http://reader.example/reader3", "http://reader.example", "http://reader.example/api/5" }) do
cfg.server_address = address
start()
requests[1].cb(wire("Documentation is at index.html"))
Assert.eq(payload.html, address == "http://reader.example"
and '<h1>章</h1>\n<p id="moon-legado-paragraph-1">Documentation is at index.html</p>'
or "<h1>章</h1>\n<p>Documentation is at index.html</p>")
Assert.len(requests, 1)
end
cfg.server_address = "http://reader.example/reader3"
-- 资源路径保留已有编码;合法的 src = 属性在图片落地后不再留下远程引用。
do
start()
requests[1].cb(wire(resource))
Assert.eq(requests[2].url, "http://reader.example" .. resource)
requests[2].cb(image_body)
Assert.eq(requests[3].url, "http://reader.example/book-assets/book/Images/cover%20one.png")
requests[3].cb("image data")
Assert.eq(payload.html, '<h1>章</h1>\n<img src="images/fixture.png"/>')
Assert.eq(writes[1].dir, Paths.bookWorkDir(identity.stable_id, identity.source_id) .. "/images")
Assert.eq(calls, 1)
end
-- 资源 GET 的错误直接上报;标题和空白实体不能让空正文成功。
do
start()
requests[1].cb(wire(resource))
requests[2].cb(nil, "HTTP 404")
Assert.is_nil(payload)
Assert.eq(reason, "HTTP 404")
start()
requests[1].cb(wire(resource))
requests[2].cb("<body><div>&nbsp; &#160;</div></body>")
Assert.is_nil(payload)
Assert.eq(reason, "阅读章节内容为空")
start()
requests[1].cb(wire(resource))
requests[2].cb("<body><div>&amp;</div></body>")
Assert.eq(payload.html, "<h1>章</h1>\n<div>&amp;</div>")
end
-- 下载失败、不识别的图片或图片写盘失败,均不得返回成功章节。
for _idx, failure in ipairs({ "network", "invalid", "write" }) do
start()
requests[1].cb(wire(resource))
requests[2].cb(image_body)
if failure == "network" then
requests[3].cb(nil, "HTTP 404")
else
if failure == "invalid" then
local materialize = Assets.materializeImage
Assets.materializeImage = function() return nil end
requests[3].cb("<html>not an image</html>")
Assets.materializeImage = materialize
else
write_failed = true
requests[3].cb("image data")
end
end
Assert.is_nil(payload)
Assert.eq(reason, failure == "network" and "HTTP 404" or "阅读插图下载失败,请重试")
Assert.eq(calls, 1)
end
-- 三个阶段分别取消;即使底层桩强行投递迟到响应也不能继续或落地图片。
for phase = 1, 3 do
local job = start()
if phase > 1 then requests[1].cb(wire(resource)) end
if phase > 2 then requests[2].cb(image_body) end
job.cancel()
Assert.is_true(requests[phase].cancelled)
requests[phase].cb(phase == 1 and wire(resource) or phase == 2 and image_body or "image data")
Assert.len(requests, phase)
Assert.len(writes, 0)
Assert.eq(calls, 0)
end
-- 同步 API / XHTML 回调不能把旧句柄写回,取消必须命中仍在飞的下一阶段。
for phase = 2, 3 do
local replies = { { body = wire(resource) } }
if phase == 3 then replies[2] = { body = image_body } end
local job = start(replies)
job.cancel()
Assert.is_true(requests[phase].cancelled)
Assert.is_false(requests[1].cancelled)
Assert.eq(calls, 0)
end
-- 已登录时 XHTML 和同服务器图片都带令牌,CDN 图片不带服务器令牌。
do
cfg.username, cfg.password = "fixture-user", "fixture-password"
start()
requests[1].cb(wire({ accessToken = "fixture-token" }))
requests[2].cb(wire(resource))
Assert.eq(requests[3].url, "http://reader.example" .. resource .. "?accessToken=fixture-token")
requests[3].cb('<body><img src="../Images/cover.png"/><img src="//cdn.example/cover.png"/></body>')
Assert.eq(requests[4].url, "http://reader.example/book-assets/book/Images/cover.png?accessToken=fixture-token")
requests[4].cb("image data")
Assert.eq(requests[5].url, "http://cdn.example/cover.png")
requests[5].cb("cdn image data")
Assert.is_nil(reason)
Assert.eq(calls, 1)
end
+70
View File
@@ -0,0 +1,70 @@
--[[--
阅读(Legado)进度推送:返回的句柄要能取消真正在飞的 saveBookProgress 请求,取消后不再回调。
@module tests.moonsource_legado.source_progress_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
Stubs.install()
Stubs.reset()
local row = { bookUrl = "u1", name = "书", author = "人", durChapterIndex = 0, durChapterPos = 0 }
local saves = {}
package.preload["moonsource_legado.client"] = function()
return {
base = function() return "http://h" end,
shelfAsync = function(cb)
cb({ row })
return { cancel = function() end }
end,
saveProgressAsync = function(_row, pos, cb)
local req = { pos = pos, cb = cb, cancelled = false }
req.cancel = function() req.cancelled = true end
saves[#saves + 1] = req
return req
end,
}
end
package.preload["moonsource_legado.mapper"] = function()
return { readPos = function() return { index = 0, offset = 3 } end }
end
package.preload["source.toc"] = function()
return { read = function() return { { uid = "c1", idx = 1, title = "一" }, { uid = "c2", idx = 2, title = "二" } } end }
end
for _idx, name in ipairs({ "moonsource_legado.source", "moonsource_legado.client", "moonsource_legado.mapper", "source.toc" }) do
package.loaded[name] = nil
end
local Legado = require("moonsource_legado.source")
local identity = { source_id = "legado", stable_id = "u1" }
-- 正常:推到第二章,回调 ok
do
local src = Legado.new()
local got_ok, got_err
src:putProgressAsync(identity, { chapter_idx = 2 }, function(ok, err) got_ok, got_err = ok, err end)
Stubs.flush()
Assert.len(saves, 1)
Assert.eq(saves[1].pos.index, 1)
Assert.eq(saves[1].pos.offset, 0, "换章 offset 归零")
saves[1].cb(true)
Assert.is_true(got_ok, got_err)
saves = {}
end
-- 取消:传到在飞的保存请求;迟到的回包不再投递
do
local src = Legado.new()
local called = false
local handle = src:putProgressAsync(identity, { chapter_idx = 1 }, function() called = true end)
Stubs.flush()
Assert.len(saves, 1)
Assert.eq(saves[1].pos.offset, 3, "同章保留 offset")
handle.cancel()
Assert.is_true(saves[1].cancelled, "取消没有传到保存请求")
saves[1].cb(true)
Assert.is_false(called, "取消后不能再回调")
saves = {}
end
+242
View File
@@ -0,0 +1,242 @@
--[[--
阅读 App 换 IP:网段枚举、书架回包、失败分类,以及非阻塞端口扫描。
@module tests.moonsource_legado.source_scan_spec
--]]
---@diagnostic disable: undefined-field, missing-fields
local Assert = require("support.assert")
local JSONStub = require("support.json_stub")
local Stubs = require("support.stubs")
package.loaded["json"] = { decode = JSONStub.decode, encode = JSONStub.encode }
local cfg = { server_address = "http://192.168.1.8:1122" }
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() end,
}
package.loaded["moonsource_legado.client"] = {
mode = function()
local base = cfg.server_address or ""
if base:find("/reader3", 1, true) then return "reader3" end
if base:find("/api/%d+$") then return "qread" end
return "app"
end,
base = function()
local addr = cfg.server_address
if type(addr) ~= "string" or addr == "" then return nil end
if not addr:match("^https?://") then addr = "http://" .. addr end
return (addr:gsub("/+$", ""))
end,
}
local tcp_count = 0
local now = 1000
local no_ip = false
local open_at = {}
local blackhole = {}
local immediate = false
local requests = {}
local function installNet()
package.loaded["socket"] = {
udp = function()
return {
setpeername = function()
if no_ip then return nil end
return 1
end,
getsockname = function() return "192.168.1.50", 1 end,
close = function() end,
}
end,
tcp = function()
tcp_count = tcp_count + 1
local sock = {}
function sock:settimeout() end
function sock:close() self.closed = true end
function sock:connect(host, port)
self.host, self.port = host, port
if self.tried then
if open_at[host] then return 1 end
return nil, "connection refused"
end
self.tried = true
if immediate then return 1 end
if open_at[host] or blackhole[host] then
self.open = open_at[host] == true
return nil, "timeout"
end
return nil, "connection refused"
end
return sock
end,
select = function(_recv, sendt)
local ready = {}
for _idx, sock in ipairs(sendt or {}) do
if sock.open then ready[#ready + 1] = sock end
end
if #ready == 0 then now = now + 1 end
return {}, ready
end,
gettime = function() return now end,
}
package.loaded["http.request"] = {
get = function(url, _opts, cb)
requests[#requests + 1] = url
local body = url:find("192.168.1.9:", 1, true)
and '{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u"}]}'
or "<html>"
cb(body)
return { cancel = function() end }
end,
}
end
installNet()
package.loaded["moonsource_legado.scan"] = nil
local Scan = require("moonsource_legado.scan")
local function resetScan()
tcp_count = 0
now = 1000
no_ip = false
open_at = {}
blackhole = {}
immediate = false
requests = {}
cfg.server_address = "http://192.168.1.8:1122"
end
-- 网段:去掉自己和网络号 / 广播,254 - 1 = 253。
do
local hosts = Scan.hosts("192.168.1.50")
Assert.eq(#hosts, 253)
Assert.eq(hosts[1], "192.168.1.1")
Assert.eq(hosts[49], "192.168.1.49")
Assert.eq(hosts[50], "192.168.1.51")
Assert.eq(hosts[253], "192.168.1.254")
Assert.eq(#Scan.hosts("0.1.1.1"), 0)
Assert.eq(#Scan.hosts("999.1.1.1"), 0)
Assert.eq(#Scan.hosts("phone.lan"), 0)
end
-- 只有书架形状的回包算命中。
do
Assert.is_true(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":[]}'))
Assert.is_true(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u"}]}'))
Assert.is_false(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":{"a":1}}'))
Assert.is_false(Scan.isShelf('{"isSuccess":true,"errorMsg":"","data":["x"]}'))
Assert.is_false(Scan.isShelf('{"isSuccess":false,"errorMsg":"x","data":[]}'))
Assert.is_false(Scan.isShelf('{"isSuccess":true,"data":[]}'))
Assert.is_false(Scan.isShelf("<html>"))
Assert.is_false(Scan.isShelf(nil))
end
-- 本机地址来自路由表。没有路由就扫不了。
do
resetScan()
Assert.eq(Scan.localIP(), "192.168.1.50")
no_ip = true
Assert.is_nil(Scan.localIP())
end
-- 一台端口通且回包是书架:只校验这一台。
do
resetScan()
open_at["192.168.1.9"] = true
local found, err
Scan.find(function(list, reason) found, err = list, reason end)
Stubs.flush()
Assert.is_nil(err)
Assert.len(found, 1)
Assert.eq(found[1], "http://192.168.1.9:1122")
Assert.len(requests, 1)
Assert.eq(requests[1], "http://192.168.1.9:1122/getBookshelf?refresh=0")
end
-- 保存的端口不是 1122 时,探测和结果都用这个端口。
do
resetScan()
cfg.server_address = "http://192.168.1.8:1234"
open_at["192.168.1.9"] = true
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.eq(found[1], "http://192.168.1.9:1234")
Assert.eq(requests[1], "http://192.168.1.9:1234/getBookshelf?refresh=0")
cfg.server_address = "http://192.168.1.8:1122"
end
-- 回包不像书架的端口丢掉。
do
resetScan()
open_at["192.168.1.10"] = true
open_at["192.168.1.9"] = true
package.loaded["http.request"].get = function(url, _opts, cb)
requests[#requests + 1] = url
local host = url:match("http://([^:]+)")
local body = host == "192.168.1.10"
and '<html>'
or '{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u"}]}'
cb(body)
return { cancel = function() end }
end
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 1)
Assert.eq(found[1], "http://192.168.1.9:1122")
end
-- 没有阅读服务。端口全通(多于 8 台)不当成结果,也不发 HTTP。
do
resetScan()
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 0)
Assert.len(requests, 0)
resetScan()
immediate = true
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 0)
Assert.len(requests, 0)
end
-- 没路由:不探端口。
do
resetScan()
no_ip = true
local found, err
Scan.find(function(list, reason) found, err = list, reason end)
Stubs.flush()
Assert.is_nil(found)
Assert.eq(err, "no-ip")
Assert.eq(tcp_count, 0)
end
-- 取消后不再回调,也还没探端口。
do
resetScan()
local called = false
local handle = Scan.find(function() called = true end)
handle.cancel()
Stubs.flush()
Assert.is_false(called)
Assert.eq(tcp_count, 0)
end
-- 黑掉的地址等到超时就丢掉,不发 HTTP。
do
resetScan()
blackhole["192.168.1.9"] = true
local found
Scan.find(function(list) found = list end)
Stubs.flush()
Assert.len(found, 0)
Assert.len(requests, 0)
end
+402
View File
@@ -0,0 +1,402 @@
--[[--
阅读(Legado)Web 服务:地址归一、回包解码、请求形状与映射离线用例。
@module tests.moonsource_legado.source_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, redundant-parameter, missing-parameter, inject-field, assign-type-mismatch, param-type-mismatch, cast-type-mismatch, return-type-mismatch, cast-local-type
local Assert = require("support.assert")
local JSONStub = require("support.json_stub")
package.preload["json"] = function()
return { decode = JSONStub.decode, encode = JSONStub.encode }
end
local cfg = { server_address = "192.168.1.8:1122/" }
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end }
end
local requests, replies = {}, {}
package.preload["http.request"] = function()
return {
get = function(url, opts, cb)
requests[#requests + 1] = { method = "GET", url = url, opts = opts }
cb(table.remove(replies, 1))
return { cancel = function() end }
end,
post = function(url, body, opts, cb)
requests[#requests + 1] = { method = "POST", url = url, body = body, opts = opts }
cb(table.remove(replies, 1))
return { cancel = function() end }
end,
}
end
package.loaded["moonsource_legado.client"] = nil
package.loaded["moonsource_legado.mapper"] = nil
local Client = require("moonsource_legado.client")
local Mapper = require("moonsource_legado.mapper")
-- 地址缺协议头补 http、去尾斜杠;没配置为 nil。
do
Assert.eq(Client.base(), "http://192.168.1.8:1122")
cfg.server_address = "https://legado.lan:1122"
Assert.eq(Client.base(), "https://legado.lan:1122")
cfg.server_address = ""
Assert.is_nil(Client.base())
cfg.server_address = "http://h:1122"
end
-- 书架:GET /getBookshelf,isSuccess=false 带出 errorMsg。
do
replies = { '{"isSuccess":true,"errorMsg":"","data":[{"bookUrl":"u1"}]}' }
local rows, err
Client.shelfAsync(function(v, e) rows, err = v, e end)
Assert.is_nil(err)
Assert.len(rows, 1)
Assert.matches(requests[1].url, "^http://h:1122/getBookshelf%?refresh=0$")
replies = { '{"isSuccess":false,"errorMsg":"没有权限","data":null}' }
rows, err = nil, nil
Client.shelfAsync(function(v, e) rows, err = v, e end)
Assert.is_nil(rows)
Assert.eq(err, "没有权限")
replies = { "<html>" }
Client.shelfAsync(function(v, e) rows, err = v, e end)
Assert.eq(err, "响应无效")
end
-- 校验新库使用显式配置:地址与登录凭据不落盘,也不替换当前配置。
do
requests = {}
replies = {
'{"isSuccess":true,"data":{"accessToken":"probe-token"}}',
'{"isSuccess":true,"data":[{"bookUrl":"probe-book"}]}',
}
local rows, err
Client.shelfAsync(function(value, reason) rows, err = value, reason end, {
server_address = "https://probe.test/reader3", username = "probe-user", password = "probe-password",
})
Assert.is_nil(err)
Assert.eq(rows[1].bookUrl, "probe-book")
Assert.matches(requests[1].url, "^https://probe.test/reader3/login$")
Assert.matches(requests[1].body, '"username":"probe%-user"')
Assert.matches(requests[2].url, "^https://probe.test/reader3/getBookshelf%?")
Assert.matches(requests[2].url, "accessToken=probe%-token")
Assert.eq(Client.base(), "http://h:1122", "探测新库时当前客户端仍读旧库配置")
requests, replies = {}, { '{"isSuccess":true,"data":[]}' }
Client.shelfAsync(function() end)
Assert.matches(requests[1].url, "^http://h:1122/getBookshelf%?")
Assert.is_nil(requests[1].url:find("probe%-token"), "探测令牌不能污染旧库请求")
end
-- 正文:index 0 基、url 编码;空正文报错。
do
requests = {}
replies = { '{"isSuccess":true,"data":"第一段\\n第二段"}' }
local text
Client.contentAsync("https://a.b/c?d=1", 3, nil, function(v) text = v end)
Assert.eq(text, "第一段\n第二段")
Assert.matches(requests[1].url, "/getBookContent%?")
Assert.matches(requests[1].url, "index=3")
Assert.matches(requests[1].url, "url=https%%3A%%2F%%2Fa%.b%%2Fc%%3Fd%%3D1")
replies = { '{"isSuccess":true,"data":""}' }
local err
Client.contentAsync("u", 0, nil, function(_, e) err = e end)
Assert.eq(err, "阅读章节内容为空 #1")
end
-- 进度上报:JSON 体带 0 基章序号。
do
requests = {}
replies = { '{"isSuccess":true,"data":""}' }
local ok
Client.saveProgressAsync({ name = "书", author = "作者", bookUrl = "u1" },
{ index = 4, title = "第5章", offset = 12 }, function(v) ok = v end)
Assert.is_true(ok)
Assert.eq(requests[1].method, "POST")
Assert.matches(requests[1].url, "/saveBookProgress$")
Assert.eq(requests[1].opts.content_type, "application/json")
Assert.matches(requests[1].body, '"durChapterIndex":4')
Assert.matches(requests[1].body, '"url":"u1"')
end
-- 正文夹 <img>:真图留成标签、svg 懒加载占位丢弃、src 尾部请求头剥掉,其余文字照旧转义
do
local html = Mapper.chapterHtml("章", 'a<b>\n<img src="data:image/svg+xml;base64,PHN2Zy8+">\n'
.. '<img src="http://h/x.jpg?a=1&amp;b=2,{&quot;h&quot;:1}" alt="x">', function(src) return src end)
Assert.eq(html, '<h1>章</h1>\n<p>a&lt;b&gt;</p>\n<p><img src="http://h/x.jpg?a=1&amp;b=2"/></p>')
end
-- 映射:bookUrl 是身份,封面走 /cover 代理,自定义封面优先;没有 bookUrl 的行丢弃。
do
local books = Mapper.shelfList(function(path) return "http://h:1122/cover?path=" .. require("utils.text").urlEncode(path) end, {
{ bookUrl = "u1", name = "书", author = "作者", coverUrl = "http://img/a.jpg", kind = "玄幻", durChapterTime = 1700000000000 },
{ bookUrl = "u2", name = "二", customCoverUrl = "/local/b.jpg", coverUrl = "x" },
{ name = "无地址" },
})
Assert.len(books, 2)
Assert.eq(books[1].stable_id, "u1")
Assert.eq(books[1].cover, "http://h:1122/cover?path=http%3A%2F%2Fimg%2Fa.jpg")
Assert.eq(books[1].category, "玄幻")
Assert.eq(books[1].read_at, 1700000000)
Assert.is_true(books[1].inserted_at > books[2].inserted_at)
Assert.eq(books[2].cover, "http://h:1122/cover?path=%2Flocal%2Fb.jpg")
end
-- 有书架分组时分类取分组名(位掩码,可多组;没分组=未分类且权威),不再用网站抓来的 kind。
do
local rows = {
{ bookUrl = "a", kind = "玄幻", group = 5 },
{ bookUrl = "b", kind = "玄幻", group = 0 },
}
rows.groups = { { groupId = -1, groupName = "全部" }, { groupId = 1, groupName = "追更" },
{ groupId = 2, groupName = "完结" }, { groupId = 4, groupName = "收藏" } }
local books = Mapper.shelfList(function(p) return p end, rows)
Assert.eq(books[1].category, "追更,收藏")
Assert.is_nil(books[2].category)
Assert.is_true(books[2].category_authoritative)
end
-- 阅读位置与目录:durChapterIndex 0 基;没读过为 nil;目录 uid 是 0 基序号。
do
local pos = Mapper.readPos({ durChapterIndex = 2, durChapterPos = 30, durChapterTitle = "第3章", durChapterTime = 1 })
Assert.eq(pos.index, 2)
Assert.eq(pos.offset, 30)
Assert.eq(pos.title, "第3章")
Assert.is_nil(Mapper.readPos({ durChapterIndex = 0, durChapterTime = 0 }))
Assert.is_nil(Mapper.readPos(nil))
local toc = Mapper.toc({ { index = 0, title = "序" }, { index = 1, title = "一" } })
Assert.eq(toc[2].idx, 2)
Assert.eq(toc[2].uid, "1")
end
-- reader3:配了账号密码先 POST /login 取 accessToken,请求带上;令牌过期(NEED_LOGIN)重登一次。
do
cfg.server_address, cfg.username, cfg.password = "http://h:8080/reader3", "u", "p"
requests = {}
replies = {
'{"isSuccess":true,"data":{"accessToken":"T1"}}',
'{"isSuccess":true,"data":[{"bookUrl":"u1"}]}',
'{"isSuccess":false,"errorMsg":"NEED_LOGIN","data":"NEED_LOGIN"}',
'{"isSuccess":true,"data":{"accessToken":"T2"}}',
'{"isSuccess":true,"data":[]}',
}
local rows
Client.shelfAsync(function(v) rows = v end)
Assert.len(rows, 1)
Assert.matches(requests[1].url, "^http://h:8080/reader3/login$")
Assert.matches(requests[1].body, '"username":"u"')
Assert.matches(requests[2].url, "/reader3/getBookshelf%?.*accessToken=T1")
Assert.matches(Client.coverUrl("x"), "accessToken=T1")
Client.shelfAsync(function(v) rows = v end)
Assert.len(rows, 0)
Assert.matches(requests[5].url, "accessToken=T2")
cfg.username, cfg.password = nil, nil
end
-- reader3:相对图片 / 封面补成服务根 + accessToken;章节与正文走 POST JSON。
do
cfg.server_address, cfg.username, cfg.password = "http://h:8080/reader3", "u", "p"
Assert.eq(Client.mode(), "reader3")
Assert.eq(Client.imageUrl("__API_ROOT__/book-assets/a b.png"), "http://h:8080/book-assets/a b.png?accessToken=T2")
Assert.eq(Client.imageUrl("https://x/y.jpg"), "https://x/y.jpg")
local resource = "http://h:8080/proxy/book-assets/Text/chapter.xhtml?accessToken=T2"
Assert.eq(Client.imageUrl("../Images/cover%20one.png", resource),
"http://h:8080/proxy/book-assets/Images/cover%20one.png?accessToken=T2")
Assert.eq(Client.imageUrl("../Images/cover.png?v=1#cover", resource),
"http://h:8080/proxy/book-assets/Images/cover.png?v=1&accessToken=T2#cover")
Assert.eq(Client.imageUrl("//cdn.example/cover.png", resource), "http://cdn.example/cover.png")
Assert.eq(Client.imageUrl("data:image/png;base64,AAAA", resource), "data:image/png;base64,AAAA")
requests = {}
replies = { '{"isSuccess":true,"data":[{"index":0,"title":"序"}]}' }
local rows
Client.chaptersAsync("bu", nil, function(v) rows = v end)
Assert.len(rows, 1)
Assert.eq(requests[1].method, "POST")
Assert.matches(requests[1].url, "/reader3/getChapterList%?accessToken=T2$")
Assert.matches(requests[1].body, '"url":"bu"')
-- 重登仍失败:标记登录失效,给人看的中文说明(放在复用 T2 的用例之后)。
local Auth = require("source.auth")
Auth.reset()
requests, replies = {}, {
'{"isSuccess":false,"errorMsg":"NEED_LOGIN","data":"NEED_LOGIN"}',
'{"isSuccess":false,"errorMsg":"bad password"}',
}
local err
Client.shelfAsync(function(_v, e) err = e end)
Assert.matches(err, "阅读服务地址")
Assert.is_true(Auth.expired("legado"))
Auth.reset()
cfg.username, cfg.password = nil, nil
end
-- EPUB 正文不靠 <p> 判空;保留实体文本、转换 SVG、规范化图片属性及 URL。
do
local base = "http://h/book-assets/Text/chapter.xhtml"
local function imageUrl(src, document_url) return require("utils.text").absoluteUrl(document_url, src) end
local html = Mapper.assetHtml("章", '<?xml version="1.0"?><html><head><title>壳</title></head>'
.. '<body><style>p{color:red}</style><script>alert(1)</script><div>&amp;</div></body></html>', base, imageUrl)
Assert.eq(html, "<h1>章</h1>\n<div>&amp;</div>")
Assert.is_nil(Mapper.assetHtml("只有标题", "<body><div>&nbsp; &#160;</div></body>", base, imageUrl))
html = Mapper.assetHtml("图", '<body><svg><image xlink:href="../Images/封 面%20图.png"/></svg>'
.. "<img src = '../Images/a.png?a=1&amp;b=2'/></body>", base, imageUrl)
Assert.matches(html, 'src="http://h/book%-assets/Images/%%E5%%B0%%81%%20%%E9%%9D%%A2%%20%%E5%%9B%%BE%.png"')
Assert.matches(html, 'src="http://h/book%-assets/Images/a%.png%?a=1&amp;b=2"')
Assert.is_nil(html:find("<svg", 1, true))
end
-- 轻阅读:/api/N 后缀;表单 POST,登录带 model=web,目录 / 正文带书源,正文回包是 { text }。
do
cfg.server_address, cfg.username, cfg.password = "http://h:1122/api/5", "u", "p"
Assert.eq(Client.mode(), "qread")
requests = {}
replies = {
'{"isSuccess":true,"data":{"accessToken":"Q1"}}',
'{"isSuccess":true,"data":[{"bookUrl":"u1","origin":"src1"}]}',
'{"isSuccess":true,"data":{"rules":{},"text":"正文"}}',
'{"isSuccess":true,"data":""}',
}
local rows, text, ok
Client.shelfAsync(function(v) rows = v end)
Assert.eq(rows[1].origin, "src1")
Assert.eq(requests[1].opts.content_type, "application/x-www-form-urlencoded")
Assert.matches(requests[1].body, "model=web")
Assert.matches(requests[2].url, "/api/5/getBookshelf%?accessToken=Q1$")
Assert.eq(requests[2].body, "version=3.2.1")
Client.contentAsync("u1", 2, "src1", function(v) text = v end)
Assert.eq(text, "正文")
Assert.matches(requests[3].body, "bookSourceUrl=src1")
Assert.matches(requests[3].body, "index=2")
Client.saveProgressAsync({ bookUrl = "u1" }, { index = 2, title = "T", offset = 5 }, function(v) ok = v end)
Assert.is_true(ok)
Assert.eq(requests[4].body, "index=2&pos=5&title=T&url=u1")
Assert.eq(Client.imageUrl("baseurl/proxypng?url=a"), "http://h:1122/api/5/proxypng?url=a&accessToken=Q1")
Assert.eq(Client.coverUrl("/c.jpg"), "http://h:1122/api/5/proxypng?url=%2Fc.jpg&accessToken=Q1")
cfg.server_address, cfg.username, cfg.password = "http://h:1122", nil, nil
end
-- 地址是连接位置,不是书籍身份:换 IP / 清空后重连保留进度,换账号仍走清库边界。
do
local Themed = require("support.theme_stubs")
local ProgressDB = require("book.progress_db")
local stable_id = "legado-address-progress-spec"
assert(ProgressDB.upsert("legado", stable_id, { fraction = 0.63, chapter_idx = 8 }))
assert(ProgressDB.setDecisionPending("legado", stable_id, true))
Themed.install()
package.loaded["ui.themes.widgets.row"] = { widget = function(opts) return opts end }
cfg = { server_address = "http://old/reader3", username = "old-user", password = "old-password" }
local saved, reloaded, cleaned, aborted, cleanup_ok = 0, 0, 0, 0, true
package.loaded["utils.settings"] = {
getSource = function() return cfg end,
saveSource = function() saved = saved + 1 end,
}
package.loaded["source.registry"] = { reload = function() reloaded = reloaded + 1 end }
package.loaded["source.logout"] = {
row = require("source.logout").row,
abort = function(id)
Assert.eq(id, "legado")
aborted = aborted + 1
end,
replaceLibrary = function(_id, commit)
cleaned = cleaned + 1
if not cleanup_ok then return false end
commit()
require("source.registry").reload()
return true
end,
}
package.loaded["ui/network/manager"] = { runWhenConnected = function(_self, fn) fn() end }
local pending, candidate
local shelf = Client.shelfAsync
Client.shelfAsync = function(cb, settings)
pending, candidate = cb, settings
return { cancel = function() end }
end
local Setting = require("moonsource_legado.setting")
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "old-user", "old-password")
Assert.eq(candidate.server_address, "http://new/reader3")
Assert.eq(candidate.username, "old-user")
Assert.eq(cfg.server_address, "http://old/reader3", "校验期间当前源仍握着旧库")
Assert.eq(saved, 0)
pending(nil, "network failed")
Assert.eq(cfg.server_address, "http://old/reader3")
Assert.eq(saved, 0)
Assert.eq(reloaded, 0)
Assert.eq(Themed.last("toast").text, "network failed")
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "old-user", "old-password")
pending({ { bookUrl = stable_id } })
local progress = ProgressDB.get("legado", stable_id)
Assert.is_true(progress ~= nil, "更换地址不能删除阅读进度")
Assert.eq(progress.chapter_idx, 8)
Assert.eq(progress.fraction, 0.63)
Assert.eq(progress.sync_status, 0)
Assert.eq(progress.decision_pending, 1)
Assert.eq(cfg.server_address, "http://new/reader3")
Assert.eq(saved, 1)
Assert.eq(reloaded, 1)
Assert.eq(cleaned, 0)
Assert.eq(aborted, 1)
-- 先清空旧地址再填新地址也不是登出,不能在这一步清掉数据或账号身份。
Setting.rows()[1](300).callback()
Themed.last("input").callback("", "", "")
Assert.is_nil(cfg.server_address)
Assert.eq(cfg.username, "old-user")
Assert.eq(cfg.password, "old-password")
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
Assert.eq(cleaned, 0)
Assert.eq(aborted, 2)
-- 局域网扫描同样走保存地址流程;重新找到服务后继续用原账号与进度。
package.loaded["moonsource_legado.scan"] = {
find = function(cb)
cb({ "http://lan/reader3" })
return { cancel = function() end }
end,
}
Setting.rows()[2](300).callback()
Assert.eq(candidate.username, "old-user")
pending({ { bookUrl = stable_id } })
Assert.eq(cfg.server_address, "http://lan/reader3")
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
Assert.eq(cleaned, 0)
-- 换账号只准备同步;准备失败不能提交新账号,也不能删除进度。
saved, reloaded, cleanup_ok = 0, 0, false
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "new-user", "new-password")
pending({ { bookUrl = "new-book" } })
Assert.eq(cfg.server_address, "http://lan/reader3")
Assert.eq(cfg.username, "old-user")
Assert.eq(saved, 0)
Assert.eq(reloaded, 0)
Assert.eq(Themed.last("toast").text, "准备本地同步失败")
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
cleanup_ok = true
Setting.rows()[1](300).callback()
Themed.last("input").callback("http://new/reader3", "new-user", "new-password")
pending({ { bookUrl = "new-book" } })
Assert.eq(cfg.server_address, "http://new/reader3")
Assert.eq(cfg.username, "new-user")
Assert.eq(saved, 1)
Assert.eq(reloaded, 1)
Assert.eq(ProgressDB.get("legado", stable_id).chapter_idx, 8)
Assert.eq(ProgressDB.get("legado", stable_id).fraction, 0.63)
Assert.eq(ProgressDB.get("legado", stable_id).decision_pending, 1)
Client.shelfAsync = shelf
end
+245
View File
@@ -0,0 +1,245 @@
--[[--
阅读 App 段评:真实客户端回包、源接口、离线缓存与段落定位。
@module tests.moonsource_legado.reviews_spec
--]]
---@diagnostic disable: undefined-field, missing-fields, param-type-mismatch, inject-field, assign-type-mismatch
local Assert = require("support.assert")
local Stubs = require("support.stubs")
local JSON = require("support.json_stub")
Stubs.install()
local cfg = { server_address = "http://legado.example:1122" }
local connected, delayed_toc, toc_callback, toc_cancelled = true, false, nil, false
local requests = {}
package.preload["json"] = function() return { encode = JSON.encode, decode = JSON.decode } end
package.preload["utils.settings"] = function()
return { getSource = function() return cfg end, saveSource = function() end }
end
package.preload["ui/network/manager"] = function()
return { isConnected = function() return connected end,
isOnline = function() error("不能用同步 DNS 检查联网") end }
end
package.preload["http.request"] = function()
return {
get = function(url, _opts, cb)
local request = { url = url, cb = cb, cancelled = false }
requests[#requests + 1] = request
return { cancel = function() request.cancelled = true end }
end,
post = function() error("阅读 App 段评必须 GET") end,
}
end
for _idx, name in ipairs({ "json", "utils.settings", "ui/network/manager", "http.request",
"moonsource_legado.source", "moonsource_legado.client", "moonsource_legado.mapper", "moonsource_legado.reviews", "book.review_cache" }) do
package.loaded[name] = nil
end
local Client = require("moonsource_legado.client")
local Reviews = require("moonsource_legado.reviews")
local Mapper = require("moonsource_legado.mapper")
local Cache = require("book.review_cache")
local source = require("moonsource_legado.source").new()
local identity = { source_id = "legado", stable_id = "https://books.example/a?b=1&c=2", chapter_idx = 2 }
Cache.removeIdentity(identity.source_id, identity.stable_id)
function source:loadTocAsync(_identity, cb)
if delayed_toc then toc_callback = cb else cb({ {}, { uid = "7", title = "章" } }) end
return { cancel = function() toc_cancelled = true end }
end
local function answer(data, err)
requests[#requests].cb(data and JSON.encode({ isSuccess = true, data = data }), err)
end
local summary = { counts = { ["-1"] = 4, ["0"] = 9, ["1"] = 5, ["3"] = 2, ["8"] = 0 },
keys = { ["1"] = 'key&中文:"\n', ["3"] = "other" } }
local value, reason
local function receive(data, err) value, reason = data, err end
-- 开关默认关闭;reader3 / 轻阅读不宣称支持 Android App 的专用接口。
Assert.is_false(source:paragraphReviewsEnabled())
require("source.review_setting").set("legado", true)
Assert.is_true(source:paragraphReviewsEnabled())
for _idx, address in ipairs({ "http://legado.example/reader3", "http://legado.example/api/5" }) do
cfg.server_address = address
Assert.is_false(source:paragraphReviewsEnabled())
Client.reviewSummaryAsync(identity.stable_id, 7, receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "段评仅支持阅读 App 的 Web 服务")
Assert.len(requests, 0)
end
cfg.server_address = "http://legado.example:1122"
-- 请求使用目录 uid(7),不是月读的章序号(2)减一;摘要标识原样保留。
source:paragraphHotspotsAsync(identity, receive)
Assert.matches(requests[1].url, "/getReviewSummary%?")
Assert.matches(requests[1].url, "index=7")
Assert.matches(requests[1].url, "url=https%%3A%%2F%%2Fbooks%.example%%2Fa%%3Fb%%3D1%%26c%%3D2")
answer(summary)
Assert.is_nil(reason)
Assert.len(value, 2)
local hotspots = value
Assert.eq(hotspots[1].paragraph, 1)
Assert.eq(Reviews.context(hotspots[1].range)[2], summary.keys["1"])
Assert.eq(hotspots[2].paragraph, 3)
-- 图片段占段号;开头空段、连续换行、被丢弃的 SVG 占位也不能导致后文错位。
local html = Mapper.chapterHtml("章", '第一段原文。\n<img src="https://images.example/p.png">\n第三段原文。',
function(src) return src end, true)
Assert.matches(html, 'id="moon%-legado%-paragraph%-2"><img')
local spots = source:locateHotspots(hotspots, html)
Assert.len(spots, 2)
Assert.eq(spots[2].text, "第三段原文。")
Assert.eq(spots[2].range, hotspots[2].range)
local marked = Mapper.chapterHtml("章", '\n首段。\n\n<img src="data:image/svg+xml;base64,x">\n后段。',
function(src) return src end, true)
Assert.matches(marked, 'id="moon%-legado%-paragraph%-2">首段。')
Assert.matches(marked, 'id="moon%-legado%-paragraph%-4">后段。')
Assert.is_nil(marked:find("\2", 1, true))
Assert.len(source:locateHotspots(hotspots, "<h1>旧缓存</h1><p>未编号正文</p>"), 0,
"旧缓存不能靠猜测段序把评论挂错段")
source:chapterReviewHotspotsAsync(identity, receive)
answer(summary)
Assert.len(value, 1)
Assert.eq(Reviews.context(value[1].range)[1], -1)
Assert.eq(value[1].total, 4)
Assert.eq(value[1].anchor, require("book.review_locate").CHAPTER_ANCHOR)
-- 正文与回复的 id 是不透明字符串,大整数及同一段的 paraData 不得丢失。
source:paragraphReviewPageAsync(identity, hotspots[1].range, 0, receive)
Assert.matches(requests[#requests].url, "/getReviewDetail%?")
Assert.matches(requests[#requests].url, "page=1")
Assert.matches(requests[#requests].url, "paraIndex=1")
Assert.matches(requests[#requests].url, "paraData=key%%26%%E4%%B8%%AD%%E6%%96%%87%%3A%%22%%0A")
local original_id = "18446744073709551617"
answer({ items = { { id = original_id, name = "作者", content = "<b>评论 &amp; 内容</b>",
time = "2026-11-13", likeCount = 7, replyCount = 9, imageUrl = "https://images.example/comment.png" } },
hasMore = true, nextCursor = "cursor&%" })
Assert.is_nil(reason)
local first_page = value
Assert.eq(first_page.items[1].content, "评论 & 内容")
Assert.eq(first_page.items[1].author, "作者")
Assert.eq(first_page.items[1].likes, 7)
Assert.eq(first_page.items[1].replies, 9)
Assert.eq(first_page.items[1].images[1].url, "https://images.example/comment.png")
Assert.eq(Reviews.context(first_page.items[1].id, true)[3], original_id)
Assert.is_nil(first_page.total, "接口没给总数,不能伪造成本页条数")
Assert.is_true(first_page.more)
source:paragraphReviewPageAsync(identity, hotspots[1].range, first_page.max_idx, receive)
Assert.matches(requests[#requests].url, "page=2")
Assert.matches(requests[#requests].url, "cursor=cursor%%26%%25")
answer({ items = {}, hasMore = false })
Assert.is_false(value.more)
Assert.eq(value.total, 0)
source:paragraphReviewRepliesAsync(identity, first_page.items[1].id, 0, receive)
Assert.matches(requests[#requests].url, "/getReviewReplies%?")
Assert.matches(requests[#requests].url, "reviewId=" .. original_id)
Assert.matches(requests[#requests].url, "paraIndex=1")
answer({ items = { { id = "reply", name = "乙", content = "回复", replyToName = "丙" } }, hasMore = true })
local replies_page = value
Assert.eq(value.items[1].reply_to, "丙")
source:paragraphReviewRepliesAsync(identity, first_page.items[1].id, replies_page.max_idx, receive)
Assert.matches(requests[#requests].url, "page=2")
answer({ items = {}, hasMore = false })
-- JS 书源的更多页只有 page 信号,没有 cursor,同样按递增页号续拉。
local js_page = Reviews.page({ items = { { id = "js", content = "评论" } }, hasMore = true },
Reviews.context(hotspots[1].range), 1)
local page, cursor = Reviews.pagination(js_page.max_idx)
Assert.eq(page, 2)
Assert.is_nil(cursor)
Assert.is_true(js_page.more)
Assert.eq(Reviews.page({ items = { { content = "没有 ID", replyCount = 3 } }, hasMore = false },
Reviews.context(hotspots[1].range), 1).items[1].replies, 0)
-- HTTP 200 的业务失败及损坏回包不能变成空评论成功,也不能清掉旧缓存。
source:paragraphHotspotsAsync(identity, receive)
requests[#requests].cb('{"isSuccess":false,"errorMsg":"段评规则未配置"}')
Assert.is_nil(value)
Assert.eq(reason, "段评规则未配置")
source:paragraphHotspotsAsync(identity, receive)
requests[#requests].cb("<html>old app</html>")
Assert.is_nil(value)
Assert.eq(reason, "响应无效")
Assert.is_nil(Reviews.hotspots({ counts = {} }))
Assert.is_nil(Reviews.hotspots({ counts = { ["x"] = 1 }, keys = {} }))
Assert.is_nil(Reviews.page({ items = {}, hasMore = "yes" }, {}, 1))
Assert.is_nil(Reviews.page({ items = { bad = {} }, hasMore = false }, {}, 1))
-- 离线只保留首页评论已缓存的标记;正文页和回复均可从缓存读取,不发网络。
connected = false
local count = #requests
source:paragraphHotspotsAsync(identity, receive)
Stubs.flush()
Assert.is_nil(reason)
Assert.len(value, 1)
Assert.eq(value[1].range, hotspots[1].range)
source:paragraphReviewPageAsync(identity, hotspots[1].range, 0, receive)
Stubs.flush()
Assert.eq(value.items[1].author, "作者")
source:paragraphReviewRepliesAsync(identity, first_page.items[1].id, 0, receive)
Stubs.flush()
Assert.eq(value.items[1].content, "回复")
Assert.len(requests, count)
local missing = { source_id = "legado", stable_id = "legado-review-no-cache", chapter_idx = 2 }
Cache.removeIdentity(missing.source_id, missing.stable_id)
source:paragraphHotspotsAsync(missing, receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "未联网,无法加载段评")
Assert.len(requests, count)
-- 请求阶段和目录阶段都可取消;迟到响应不得写缓存或启动后续请求。
connected = true
local calls = 0
local job = source:paragraphHotspotsAsync(missing, function() calls = calls + 1 end)
job.cancel()
Assert.is_true(requests[#requests].cancelled)
answer(summary)
Assert.eq(calls, 0)
Assert.is_nil(Cache.hotspots(missing))
delayed_toc, toc_cancelled = true, false
count = #requests
job = source:paragraphHotspotsAsync(missing, function() calls = calls + 1 end)
job.cancel()
Assert.is_true(toc_cancelled)
toc_callback({ {}, { uid = "7" } })
Assert.len(requests, count)
Assert.eq(calls, 0)
source:paragraphReviewPageAsync(identity, "broken", 0, receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "阅读段评位置无效")
source:paragraphReviewPageAsync(identity, hotspots[1].range, "broken", receive)
Stubs.flush()
Assert.is_nil(value)
Assert.eq(reason, "阅读段评分页位置无效")
-- 源的真实正文路径保留段号并预留章评入口;关闭段评也保留段号,以便以后就地开启。
delayed_toc = false
package.loaded["source.chapter"] = nil
package.preload["source.chapter"] = function()
return {
openAsync = function(_source, ref, _book, _opts, ops, cb)
Assert.eq(type(ops.reuse), "function")
return ops.fetchContent(ref, { uid = "7", title = "章" }, cb)
end,
prefetchAsync = function(ref, _book, _toc, _from, _count, ops, cb)
Assert.is_nil(ops.reuse)
return ops.fetchContent(ref, { uid = "7", title = "章" }, cb)
end,
}
end
source:openBookAsync(identity, { chapter_idx = 2 }, receive)
answer("一段。\n二段。")
Assert.matches(value.html, 'id="moon%-legado%-paragraph%-2">二段。')
Assert.matches(value.html, 'id="moon%-chapter%-reviews"')
cfg.show_paragraph_reviews = false
source:prefetchChaptersAsync(identity, {}, 2, 1, receive)
answer("一段。\n二段。")
Assert.matches(value.html, 'id="moon%-legado%-paragraph%-2">二段。')
Assert.is_nil(value.html:find("moon-chapter-reviews", 1, true))
Cache.removeIdentity(identity.source_id, identity.stable_id)
Cache.removeIdentity(missing.source_id, missing.stable_id)
+25
View File
@@ -0,0 +1,25 @@
#!/bin/sh
# 打包本仓库的书源插件:moonsource-<名字>.koplugin-<VERSION>.zip,同时生成 SHA256SUMS。
# 用法:tools/package.sh <VERSION> [OUT_DIR] (OUT_DIR 默认 dist/)
# 打包时把 <包名>/version.lua 里的版本占位符换成发布版本;剔除 *.md、.DS_Store、*~。
set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
VERSION="${1:?用法:tools/package.sh <VERSION> [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)
+41
View File
@@ -0,0 +1,41 @@
#!/bin/sh
# 发布本书源:校验更新日志 → 本地打包 → 打轻量标签 v<版本> → 推送当前分支和标签。
# Release 由 .github/workflows/release.yml 在标签推上去之后创建,日志取 CHANGELOG.md 里精确的「## <版本>」一节。
# 用法:tools/release.sh <VERSION>
set -eu
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
cd "$ROOT"
VERSION="${1:?用法:tools/release.sh <VERSION>}"
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。"
+16
View File
@@ -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 "$@"