Full Code of JeffersonQin/lightnovel_epub for AI

master 05a6aee5a51f cached
15 files
96.5 KB
26.4k tokens
56 symbols
1 requests
Download .txt
Repository: JeffersonQin/lightnovel_epub
Branch: master
Commit: 05a6aee5a51f
Files: 15
Total size: 96.5 KB

Directory structure:
gitextract_33nrehfm/

├── .gitignore
├── LICENSE
├── LICENSE_AGPL
├── LICENSE_MIT
├── README.md
├── cli.py
├── gui.py
├── lightnovel.py
├── provider/
│   ├── lk_mobile.py
│   ├── lk_new.py
│   └── wenku8.py
├── requirements.txt
└── utils/
    ├── checker.py
    ├── downloader.py
    └── echo.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
# Custom settings
dump

# VSCode settings
.vscode

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/


================================================
FILE: LICENSE
================================================
MIXED LICENSE

lightnovel.py and cli.py are licensed under AGPL license.

Other files in the repo are licensed under MIT license.


================================================
FILE: LICENSE_AGPL
================================================
                    GNU AFFERO GENERAL PUBLIC LICENSE
                       Version 3, 19 November 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
our General Public Licenses are 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.

  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.

  Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.

  A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate.  Many developers of free software are heartened and
encouraged by the resulting cooperation.  However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.

  The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community.  It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server.  Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.

  An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals.  This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.

  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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.

  Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software.  This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.

  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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source.  For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code.  There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.

  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 AGPL, see
<http://www.gnu.org/licenses/>.


================================================
FILE: LICENSE_MIT
================================================
MIT License

Copyright (c) 2021 gyro永不抽风

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
- [Introduction](#introduction)
- [Supported Sites Overview](#supported-sites-overview)
- [Requirements](#requirements)
- [Usage Overview](#usage-overview)
- [Usage](#usage)
	- [轻之国度](#轻之国度)
		- [Options](#options)
		- [高权限文章](#高权限文章)
		- [缓存相关](#缓存相关)
	- [轻之国度 App](#轻之国度-app)
		- [Options](#options-1)
		- [Prerequisite](#prerequisite)
		- [Background](#background)
		- [界面布局相关参数](#界面布局相关参数)
		- [旋转相关](#旋转相关)
		- [合并模式相关](#合并模式相关)
		- [Mumu 模拟器点击位置不正确解决方案](#mumu-模拟器点击位置不正确解决方案)
		- [缓存相关](#缓存相关-1)
	- [轻小说文库](#轻小说文库)
		- [Options](#options-2)
		- [缓存相关](#缓存相关-2)
		- [指定卷数](#指定卷数)
- [Known Issues](#known-issues)
- [TODO](#todo)
- [Contribution](#contribution)
- [LICENSE](#license)
- [技术分析](#技术分析)
	- [原理概览](#原理概览)
	- [轻之国度网页版 合集文章](#轻之国度网页版-合集文章)

# Introduction

~~本工具用于基于[轻之国度](https://lightnovel.us)网页或 app 生成`epub`小说。~~

Update [2022/01/20]: **现已升级成为轻小说 epub 生成框架,支持更多网站**~~(当年名字取得好啊!)~~

Update [2023/09/08 (EST)]: 呃呃 LK 加了 Cloudflare 反爬,直接下载是寄了,但是还可以通过保存 `html` 然后指定 `--lk-html-dump` 参数来解决问题。

**注意:本工具仅作学习交流使用,作者不对内容和使用情况付任何责任!**

~~本来就是一个面向过程的小工具,怎么越发繁琐起来了。。。这里还要感慨一下LK牛逼的防御技术~~

# Supported Sites Overview

| 站点 | 单页 | 合集 | 详细说明 |
| :--: | :---: | :---: | :-: |
| [轻之国度](https://www.lightnovel.us) | ✅ | ✅ | [说明](#轻之国度) |
| 轻之国度 App | ✅ | ❌ | [说明](#轻之国度-app) |
| [轻小说文库](https://www.wenku8.net/index.php) | ❌ | ✅ | [说明](#轻小说文库) |

# Requirements

* python 3.5 +
* click
* beautifulsoup4
* requests
* ebooklib
* uiautomator2
* dominate
* opencc
* opencv
* js2py

# Usage Overview

下载命令:

```bash
python3 cli.py download <options> <url>
```

下面是我写的 `--help`:

```
$ python3 cli.py download --help
Usage: cli.py download [OPTIONS] URL

  download the light novel

  ARGUMENTS:

  * URL: url of light novel to download

Options:
  --dump-path PATH                directory for dumping files and caches      
  --title TEXT                    title of light novel
  --authors TEXT                  authors' names, separated by comma (,)      
  --identifier TEXT               identifier of light novel
  --cover-link TEXT               cover link of light novel. cover link can   
                                  either be web link or file path. if it is   
                                  not beginned with "http", it would be       
                                  recognized as file path. if nothing was     
                                  given, then it will use the first picture of
                                  webpage.
  --cvt TEXT                      OpenCC conversion configuration, used to    
                                  convert between different Chinese
                                  characters. you can choose the value from
                                  "s2t", "t2s", "s2tw", "tw2s", "s2hk",
                                  "hk2s", "s2twp", "tw2sp", "t2tw", "hk2t",
                                  "t2hk", "t2jp", "jp2t", "tw2t". if nothing
                                  is provided, no conversion would be
                                  performed. for more information, please
                                  visit: https://github.com/BYVoid/OpenCC
  --path PATH                     directory for saving the light novel
  --lk-html-dump PATH             (lightnovel.us) html content dump file path
  --wenku8-volume INTEGER         (wenku8.net) identify the index of the
                                  volume to generate. -1 means every volume,
                                  which is also the default option. index
                                  starts from 1.
  --lk-mobile-top-area-height INTEGER
                                  (lk mobile) the height of the top area
  --lk-mobile-bottom-area-height INTEGER
                                  (lk mobile) the height of the bottom area
  --lk-mobile-image-equal-threshold INTEGER
                                  (lk mobile) the threshold of judging whether
                                  two images are equal
  --lk-mobile-safe-area-padding INTEGER
                                  (lk mobile) the padding of the safe area
  --lk-mobile-vert-dump PATH      (lk mobile) vertical content dump file path
  --lk-mobile-horz-dump PATH      (lk mobile) horizontal content dump file
                                  path
  --lk-mobile-html-dump PATH      (lk mobile) html content dump file path
  --lk-mobile-conflict-mode BOOLEAN
                                  (lk mobile) whether to resolve conflict
                                  manually
  --lk-mobile-ignore-newline BOOLEAN
                                  (lk mobile) whether to ignore newline
  --help                          Show this message and exit.
```

注意:
* 书籍有关的 `options` 可以直接忽略,因为执行命令后如果发现没有 `options` 会进行第二轮询问。
* `dump-path` 是指缓存以及其他的临时文件的输出位置,若提示找不到路径,创建即可
* 针对每个网站,可能有自己的 `options`,具体可以参见 `help` 和下一小节

# Usage

## 轻之国度

### Options

```
  --lk-html-dump PATH             (lightnovel.us) html content dump file path
```

### 高权限文章

有部分文章会 **先显示无权限观看,后可以观看 先显示无权限观看,后可以观看**。这种情况下,浏览器保存 `HTML`,然后启用 `--lk-html-dump` 选项即可。

### 缓存相关

* 单页面
  * 会缓存 HTML,每下载一张图片后会用本地路径替换掉 HTML 中的链接
* 合集
  * 每篇文章都会像单页面一样进行缓存

| 情形 | 加载命令 | 描述 | 文件格式 | 文件名规范 |
| :-: | :-: | :-: | :-: | :-: |
| 单文章 | `--lk-html-dump` | 文章内容 | HTML | `<timestamp>.html` |
| 合集内文章 | 无,但会检查 `dump-path` 内是否存在 | 文章内容 | HTML | `<article-id>.html` |

## 轻之国度 App

### Options

由于没有 URL,所以在这种情况下 url 参数应指定为 `lk-mobile`,并打开需要处理的页面。

```
  --lk-mobile-top-area-height INTEGER
                                  (lk mobile) the height of the top area
  --lk-mobile-bottom-area-height INTEGER
                                  (lk mobile) the height of the bottom area
  --lk-mobile-image-equal-threshold INTEGER
                                  (lk mobile) the threshold of judging whether
                                  two images are equal
  --lk-mobile-safe-area-padding INTEGER
                                  (lk mobile) the padding of the safe area
  --lk-mobile-vert-dump PATH      (lk mobile) vertical content dump file path
  --lk-mobile-horz-dump PATH      (lk mobile) horizontal content dump file
                                  path
  --lk-mobile-html-dump PATH      (lk mobile) html content dump file path
  --lk-mobile-conflict-mode BOOLEAN
                                  (lk mobile) whether to resolve conflict
                                  manually
  --lk-mobile-ignore-newline BOOLEAN
                                  (lk mobile) whether to ignore newline
```

### Prerequisite

首先,不管是模拟器还是真机,都需要开启 ADB。现在的代码只适用于只有一个 ADB 设备的情况,如果有需求,请自行修改 `provider/lk_mobile.py`。

TODO:

- [ ] 日后为这块增加命令行参数

### Background

对 app 模拟手的滚动操作,同时获取元素,最后生成 epub。

注意到:客户端非常恶心,每一行文本都是一个 View,所以我采用了 Portrait 和 Landscape 扫两遍,然后双指针 Merge 的思路来进行对抗,效果喜人。

![](./assets/text-split.png)

### 界面布局相关参数

* `--lk-mobile-top-area-height`: 设备最顶端到导航栏的高度
* `--lk-mobile-bottom-area-height`: 设备下方评论栏的高度
* 上面两个参数默认值为分辨率是 Nox 模拟器 **3840 * 2160** 的情况
* 其余的可以保持默认,有兴趣可以研究

<div align="center">
	<img src="./assets/mobile-params.png" width=300>
</div>

### 旋转相关

* 最开始进入页面之前屏幕应为 Portrait 状态,命令行会要求用户确认
* Portrait 扫描完成之后,设备会自动进入 Landscape 状态,但是需要用户退出界面并重新进入,原因是需要 Layout 重新加载。这一步同样会要求用户确认
* 由于图片的获取是通过截图,所以建议将分辨率调高
* 由于整个过程耗时长,可能出现意外状况,故有若干 `dump` 命令。`--vert-dump` 可以加载之前操作获取的 Portrait (Vertical) 数据,`--horz-dump` 可以加载之前操作获取的 Landscape (Horizontal) 数据,`--html-dump` 可以加载之前导出的 `html` 数据

![](assets/rotate-quit.png)

### 合并模式相关

`--lk-mobile-new-line` 和 `--lk-mobile-conflict-mode`这两个参数的诞生和排版有着密切的关系。举个简单的例子:

<div align="center">
这是一前半段没有加粗的文字<b>这是中间加粗的文字</b>这是最后没有加粗的文字
</div>

如果上面这段话在同一行里,那么会解析成:

```json
[
	"这是一前半段没有加粗的文字\n这是中间加粗的文字\n这是最后没有加粗的文字"
]
```

但是,如果排版变成了:

<div align="center">
这是一前半段没有加粗的文字<b>这是中间加粗的文字</b><br/>这是最后没有加粗的文字
</div>

就会解析成:

```json
[
	"这是一前半段没有加粗的文字\n这是中间加粗的文字", 
	"这是最后没有加粗的文字"
]
```

可以发现有一个 `\n` 就这样凭空消失了。这就会导致一个问题:双指针扫描匹配的时候永远无法找到同样的文字内容。为了解决这个问题,我引入了两个方案:
1. `--lk-mobile-ignore-newline`: 将文中所有出现的 `\n` 全部忽略,效果很好。但是同时,我们也丧失了知道哪里有排版的机会。
2. `--lk-mobile-conflict-mode`: 程序最初的版本如果遇到图片但是文字还没有合并,会直接报错。如果加上了 `--lk-mobile-conflict-mode True` 就会在这个情况下让用户选择选择 Landscape 还是 Portrait 的版本。以后可能还会加上让用户手动输入的选项。

### Mumu 模拟器点击位置不正确解决方案

Mumu 模拟器点击可能错位,如下图所示:

<div align="center">
	<img src="./assets/mumu-error.png" width=300>
</div>

这种情况下只需在设置中交换长、宽数值即可,让宽大于长。

### 缓存相关

上面已经提到,由于整过过程耗时很长,所以在获取完 Landscape 和 Portrait 数据后会分别写入到文件,两组数据合并完成后也会写入到 Html。

| 情形 | 加载命令 | 描述 | 文件格式 | 文件名规范 |
| :-: | :-: | :-: | :-: | :-: |
| 单文章 | `--lk-mobile-vert-dump` | 获取到的 Portrait 数据 | Pickle 二进制数据 | `<timestamp>.out` |
| 单文章 | `--lk-mobile-horz-dump` | 获取到的 Landscape 数据 | Pickle 二进制数据 | `<timestamp>.out` |
| 单文章 | `--lk-mobile-html-dump` | 合并后的数据 | HTML | `<timestamp>.html` |

## 轻小说文库

### Options

```
  --wenku8-volume INTEGER         (wenku8.net) identify the index of the
                                  volume to generate. -1 means every volume,
                                  which is also the default option. index
                                  starts from 1.
```

### 缓存相关

| 情形 | 加载命令 | 描述 | 文件格式 | 文件名规范 |
| :-: | :-: | :-: | :-: | :-: |
| 合集内文章 | 无,但会检查 `dump-path` 内是否存在 | 文章内容 | HTML | `<article-id>.html` |

### 指定卷数

在轻小说文库的总览页面,一般以:卷 => 章 作为导航。而小说生成一般以卷为主。所以我们提供了指定卷数的选项:`--wenku8-volume`,来指定某一卷。若需要一并生成,参数为 -1 或保持默认。

# Known Issues

* 轻之国度
  * 【已解决,见上】~~对于部分 **先显示无权限观看**,**后可以观看** 的文章无效,以后可能会写浏览器模式~~
* 轻之国度 App
  * HTML 排版无法获取
  * 【已解决】 ~~排版问题可能导致 Lanscape / Portrait 信息无法 Merge,如果遇到这种情况,找到任意一个 Case 的 `dump` 文件 (这里记作 `dump-file`),并加上命令行参数:`--vert-dump <dump-file> --horz-dump <dump-file>`~~

# TODO

- [x] 图片下载至临时路径
- [ ] 用 PyQt 写 GUI ~~(基本上是不可能了,完全不想写,而且也没有意义)~~
- [x] 为漫画提供更好的支持
- [ ] 增加更多 `metadata` : `tags`, `publisher`, ...
- [ ] 自动抓取标题
- [ ] 自动生成目录,~~如果网页上有 headers 的话~~
- [ ] 添加自定义 CSS / 字体 等支持
- [x] 简繁自动转换
- [x] 模拟轻国手机版
- [ ] 增加移动端截屏图片压缩选项
- [ ] 目录多重嵌套
- [ ] 增加移动端 ADB 参数

相关帖子:
* https://www.v2ex.com/t/800508
* https://www.lightnovel.us/cn/themereply/1088005

# Contribution

1. 在 `provider` 文件夹中新建文件,最主要实现两个方法:
   * `get_contents(url, dump_path)` 用来获取信息。返回值可以是 `str` 或 `list`。`list` 内的数据均为 `{'title': title, 'content': content}`
   * `get_cover(link, dump_path)` 用来获取封面。之所以有这个是因为某些站有特殊的 http header,我不说是谁
   * 可以额外设计一些 `options`,写明即可
2. 在 `cli.py` 内接入即可

# LICENSE

* `lightnovel.py`, `cli.py` 使用 AGPL License 授权(`ebooklib` 使用该协议)
* 项目内的其他文件使用 MIT License 进行授权 

# 技术分析

~~以前写好了舍不得删掉所以再开一个板块,下面基本都是废话~~

## 原理概览

直接抓取 HTML,然后将其中的图片下载至本地,随后打包成 EPUB。

EPUB 内部目录:

```
.
├── Images               # 图片
│   ├── ...
│   └── ...
└── Text                 # 文本
    ├── about.xhtml      # 本项目自动生成
    └── lightnovel.xhtml # 轻小说正文
```

对于合集文章:

```
.
├── Images               # 图片
│   ├── ...
│   └── ...
└── Text                 # 文本
    ├── about.xhtml      # 本项目自动生成
    ├── Section1.xhtml   # P1
    ├── Section2.xhtml   # P2
    └── ...
```

TODO: 
- [ ] 日后可能会支持多重嵌套

## 轻之国度网页版 合集文章

对于合集文章,解析的过程比较有趣,这里讨论一下。

首先是对 HTML 的分析。

![](./assets/series-inspector.png)

很遗憾,并不是 `<a>` 也没有 `href`。去 `Source` 里一看,貌似框架选的是 `Vue`,不熟悉前端,不多做评价。

接着查看 `event`,发现是混淆过的 `js`,放弃逆向。

![](./assets/series-event.png)

经观察,数据应该在文档最后的某个 `<script>` 标签内:

![](./assets/series-script.png)

经过分析,这个 `<script>` 只暴露了一个接口:

```js
window.__NUXT__ = (function(...) { ... }) (...)
```

故我们只需要 evaluate 这个脚本,然后获取 `window.__NUXT__` 的值即可。


================================================
FILE: cli.py
================================================
import click
import sys
import traceback
import os
import opencc

from lightnovel import LightNovel
from utils import echo
from provider import lk_new
from provider import wenku8
from provider import lk_mobile


echo.init_subroutine()


@click.group()
def cli():
	pass


@cli.command()
# general options
@click.option('--dump-path', type=click.Path(), default='./dump', 
	help='directory for dumping files and caches')
@click.option('--title', default=None, 
	help='title of light novel')
@click.option('--authors', default=None, 
	help='authors\' names, separated by comma (,)')
@click.option('--identifier', default=None, 
	help='identifier of light novel')
@click.option('--cover-link', default=None, 
	help='cover link of light novel. cover link can either be web link or file path. if it is not beginned with "http", it would be recognized as file path. if nothing was given, then it will use the first picture of webpage.')
@click.option('--cvt', default=None, 
	help='OpenCC conversion configuration, used to convert between different Chinese characters. you can choose the value from "s2t", "t2s", "s2tw", "tw2s", "s2hk", "hk2s", "s2twp", "tw2sp", "t2tw", "hk2t", "t2hk", "t2jp", "jp2t", "tw2t". if nothing is provided, no conversion would be performed. for more information, please visit: https://github.com/BYVoid/OpenCC')
@click.option('--path', type=click.Path(exists=True), default='./', 
	help='directory for saving the light novel')
# lightnovel.us
@click.option('--lk-html-dump', type=click.Path(exists=True), default=None, 
	help='(lightnovel.us) html content dump file path')
# wenku8.net
@click.option('--wenku8-volume', default=-1,
	help='(wenku8.net) identify the index of the volume to generate. -1 means every volume, which is also the default option. index starts from 1.')
# lk mobile
@click.option('--lk-mobile-top-area-height', default=325, 
	help='(lk mobile) the height of the top area')
@click.option('--lk-mobile-bottom-area-height', default=200, 
	help='(lk mobile) the height of the bottom area')
@click.option('--lk-mobile-image-equal-threshold', default=1, 
	help='(lk mobile) the threshold of judging whether two images are equal')
@click.option('--lk-mobile-safe-area-padding', default=20, 
	help='(lk mobile) the padding of the safe area')
@click.option('--lk-mobile-vert-dump', type=click.Path(exists=True), default=None, 
	help='(lk mobile) vertical content dump file path')
@click.option('--lk-mobile-horz-dump', type=click.Path(exists=True), default=None, 
	help='(lk mobile) horizontal content dump file path')
@click.option('--lk-mobile-html-dump', type=click.Path(exists=True), default=None, 
	help='(lk mobile) html content dump file path')
@click.option('--lk-mobile-conflict-mode', type=bool, default=False, 
	help='(lk mobile) whether to resolve conflict manually')
@click.option('--lk-mobile-ignore-newline', type=bool, default=True, 
	help='(lk mobile) whether to ignore newline')
# general arguments
@click.argument('url')
def download(
	dump_path, 
	title: str, 
	authors: str, 
	identifier: str, 
	cover_link: str, 
	cvt: str, 
	path: str, 
	lk_html_dump, 
	wenku8_volume: int, 
	lk_mobile_top_area_height: int, 
	lk_mobile_bottom_area_height: int, 
	lk_mobile_image_equal_threshold: int, 
	lk_mobile_safe_area_padding: int, 
	lk_mobile_vert_dump, 
	lk_mobile_horz_dump,
	lk_mobile_html_dump,
	lk_mobile_conflict_mode: bool,
	lk_mobile_ignore_newline: bool, 
	url: str):
	'''
	download the light novel

	ARGUMENTS:

	* URL: url of light novel to download
	'''
	def convert_str(content, cvt):
		# chinese conversion
		if cvt in ["s2t", "t2s", "s2tw", "tw2s", "s2hk", "hk2s", "s2twp", "tw2sp", "t2tw", "hk2t", "t2hk", "t2jp", "jp2t", "tw2t"]:
			converter = opencc.OpenCC(f'{cvt}.json')
			return converter.convert(content)
		return content

	echo.push_subroutine(sys._getframe().f_code.co_name)

	try:
		# init directory
		if not os.path.exists(dump_path):
			os.mkdir(dump_path)

		if cover_link is None:
			cover_link = input('(Optional) Input cover_link of light novel (see --help for further explanation): ')

		if url.startswith('https://www.lightnovel.us/'):
			contents = lk_new.get_contents(url, dump_path, lk_html_dump)
			cover_link = lk_new.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link
		elif url.startswith('https://www.wenku8.net/'):
			source, authors, identifier, title, books, contents = wenku8.get_contents(url, dump_path, wenku8_volume)
			cover_link = wenku8.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link
		elif url == 'lk-mobile':
			contents = lk_mobile.get_contents(lk_mobile_top_area_height, lk_mobile_bottom_area_height, lk_mobile_image_equal_threshold, lk_mobile_safe_area_padding, dump_path, lk_mobile_vert_dump, lk_mobile_horz_dump, lk_mobile_html_dump, lk_mobile_conflict_mode, lk_mobile_ignore_newline)
			cover_link = lk_mobile.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link
			url = '轻之国度 APP'
		else:
			echo.cexit('unsupported url')

		if type(contents) == str:
			contents = convert_str(contents, cvt)
		elif type(contents) == list:
			for content in contents:
				content['title'] = convert_str(content['title'], cvt)
				content['content'] = convert_str(content['content'], cvt)
		else:
			echo.cexit('CONTENTS MUST BE STRING OR LIST')


		TITLE_INPUT_HINT = 'Input title of light novel: '
		AUTHOR_INPUT_HINT = '(Optional) Input authors\' names, separated by comma (,): '
		IDENTIFIER_INPUT_HINT = '(Optional) Input identifier of light novel: '

		def isempty(instr) -> bool:
			if instr is None:
				return True
			if len(instr) == 0 or str.isspace(instr):
				return True
			return False
		
		if isempty(title):
			title = input(TITLE_INPUT_HINT)
		else:
			user_title = input(f'Current Title: {title}. (Optional) {TITLE_INPUT_HINT}')
			title = title if isempty(user_title) else user_title
		if isempty(authors):
			authors = input(AUTHOR_INPUT_HINT)
		else:
			user_authors = input(f'Current Authors: {authors}. {AUTHOR_INPUT_HINT}')
			authors = authors if isempty(user_authors) else user_authors
		if isempty(identifier):
			identifier = input(IDENTIFIER_INPUT_HINT)
		else:
			user_identifier = input(f'Current identifier: {identifier}. {IDENTIFIER_INPUT_HINT}')
			identifier = identifier if isempty(user_identifier) else user_identifier

		novel = LightNovel(source=url, authors=authors.split(','), identifier=identifier, title=title, cover_link=cover_link)
		novel.contents = contents
		novel.write_epub(path)
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('DOWNLOAD LIGHTNOVEL FAILED')
	finally:
		echo.pop_subroutine()


if __name__ == '__main__':
	cli()


================================================
FILE: gui.py
================================================


================================================
FILE: lightnovel.py
================================================
import os
import sys
import traceback
import base64
from bs4 import BeautifulSoup
from ebooklib import epub

from utils import echo
from utils import downloader
from utils.checker import is_not_null, is_null

class LightNovel():
	'''
	object of light novel
	'''
	
	source = ''
	'''
	source of light novel
	'''

	authors = []
	'''
	author (Optional)
	'''
	
	identifier = None
	'''
	identifier (Optional)
	'''

	title = ''
	'''
	title of the book
	'''

	contents = ''
	'''
	can be either str or list
	the format of list is [{'conent': content, 'title': title}]
	'''

	cover_link = None
	'''
	link of cover. if `None`, then use the first picture of webpage.\n
	cover_link can either be web link or file path.\n
	if it is not beginned with `http`, it would be recognized as file path.
	'''

	def __init__(self, source: str, authors=None, identifier=None, title=None, cover_link=None):
		'''
		initialize light novel object
		'''
		self.source = source
		if authors is not None: self.authors = authors
		if identifier is not None: self.identifier = identifier
		if title is not None: self.title = title
		if cover_link is not None: self.cover_link = cover_link


	def process_image_content(self, content, book):
		'''
		process image content
		:param content: HTML content
		:return: content, first image bytes
		'''
		echo.push_subroutine(sys._getframe().f_code.co_name)

		# parse images
		try:
			soup = BeautifulSoup(content, 'lxml')
			image_tags = soup.find_all('img')
		except Exception as e:
			echo.cerr(f'Error: {repr(e)}')
			traceback.print_exc()
			echo.cexit('PARSING HTML FAILED')

		# store images
		first_flag = True # flag for storing first image
		first_image = None

		try:
			i = 0
			for tag in image_tags:
				i = i + 1
				echo.clog(f'Processing images: ({i} / {len(image_tags)})')
				# parse
				link = str(tag.attrs['src'])

				r_image = None

				if link.startswith('data:'):
					r_image = base64.decodebytes(link.split(';')[1].split(',')[1].encode('utf-8'))
				else:
					file_name = os.path.basename(link)
					file_dir = link
					
					# convert href
					tag.attrs['src'] = f'../Images/{file_name}'
					image = epub.EpubImage()
					image.file_name = f'Images/{file_name}'
					image.content = open(file_dir, 'rb').read()
					book.add_item(image)
					r_image = image.content
				
				if first_flag and r_image is not None:
					first_image = r_image
					first_flag = False
		except Exception as e:
			echo.cerr(f'Error: {repr(e)}')
			traceback.print_exc()
			echo.cexit('PROCESSING IMAGES FAILED')
		
		return soup, first_image


	def write_epub(self, path: str):
		'''
		generate the ebook to `path`
		'''
		echo.push_subroutine(sys._getframe().f_code.co_name)

		echo.clog(f'start generating...')

		try:
			# create epub book
			book = epub.EpubBook()
			
			# set metadata
			if is_not_null(self.authors):
				for author in self.authors:
					book.add_author(author=author)
			
			if is_not_null(self.identifier):
				book.set_identifier(self.identifier)

			book.set_title(self.title)
			book.set_language('zh-CN')
		except Exception as e:
			echo.cerr(f'Error: {repr(e)}')
			traceback.print_exc()
			echo.cexit('CREATING EPUB BOOK FAILED')
		
		if type(self.contents) == str:
			soup, first_image = self.process_image_content(self.contents, book)
		elif type(self.contents) == list:
			_contents = []
			first_image = None
			for content in self.contents:
				soup, _first_image = self.process_image_content(content['content'], book)
				if first_image is None:
					first_image = _first_image
				_contents.append({
					'content': str(soup),
					'title': content['title'],
				})
		else:
			echo.cexit('CONTENTS MUST BE STRING OR LIST')
		
		# set cover
		try:
			if is_not_null(self.cover_link):
				if os.path.exists(self.cover_link):
					book.set_cover(os.path.basename(self.cover_link), open(self.cover_link, 'rb').read())
			elif first_image is not None:
				book.set_cover('cover', first_image)
		except Exception as e:
			echo.cerr(f'Error: {repr(e)}')
			traceback.print_exc()
			echo.cexit('SETTING COVER IMAGE FAILED')
		
		try:
			# set content
			about_text = f'<p>本书由<a href="https://github.com/JeffersonQin/lightnovel_epub">JeffersonQin/lightnovel_epub</a>工具自动生成。<br>仅供学习交流使用,禁作商业用途。</p><br><p>本书根据 {self.source} 生成</p>'
			if type(self.contents) == str:
				about_content = epub.EpubHtml(title='关于本电子书', file_name='Text/about.xhtml', lang='zh-CN', content=about_text)
				main_content = epub.EpubHtml(title=self.title, file_name='Text/lightnovel.xhtml', lang='zh-CN', content=str(soup))

				book.add_item(about_content)
				book.add_item(main_content)

				# configure book
				book.toc = (about_content, main_content)
				# add default NCX and Nav file
				book.add_item(epub.EpubNcx())
				book.add_item(epub.EpubNav())
				book.spine = ['nav', about_content, main_content]
			elif type(self.contents) == list:
				about_content = epub.EpubHtml(title='关于本电子书', file_name='Text/about.xhtml', lang='zh-CN', content=about_text)
				i = 0
				epub_nav = ['nav', about_content]
				epub_toc = [about_content]
				epub_contents = [about_content]
				for content in _contents:
					i += 1
					item = (epub.EpubHtml(title=content['title'], file_name=f'Text/Section{i}.xhtml', lang='zh-CN', content=content['content']))
					epub_toc.append(item)
					epub_nav.append(item)
					epub_contents.append(item)
				
				for epub_content in epub_contents:
					book.add_item(epub_content)

				# configure book
				book.toc = tuple(epub_toc)
				
				# add default NCX and Nav file
				book.add_item(epub.EpubNcx())
				book.add_item(epub.EpubNav())
				
				book.spine = epub_nav

			# generate book
			epub.write_epub(os.path.join(path, f'{self.title}.epub'), book, {})
		except Exception as e:
			echo.cerr(f'Error: {repr(e)}')
			traceback.print_exc()
			echo.cexit('BOOK CONFIGURATION & GENERATION FAILED')
		
		echo.pop_subroutine()


================================================
FILE: provider/lk_mobile.py
================================================
import uiautomator2 as u2
from bs4 import BeautifulSoup
import cv2
import time
import numpy as np
import sys
import pickle
import os
import traceback
import dominate
from utils import echo
from utils import downloader

# define constants
TOP_AREA_HEIGHT = 325
BOTTOM_AREA_HEIGHT = 200
IMAGE_EQUAL_THRESHOLD = 1
SAFE_AREA_PADDING = 20
DUMP_PATH = './dump'

d = None


class Image:

	filePath: str = None

	shape = None
	
	def __init__(self, filePath, shape):
		self.filePath = filePath
		self.shape = shape


class EOF:
	def __init__(self):
		pass


def rotate2landscape():
	"""
	rotate screen to landscape
	:return: None
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		echo.clog('Rotate screen to landscape.')
		d.set_orientation('l')
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('ROTATE TO LANDSCAPE FAILED')
	finally:
		echo.pop_subroutine()


def rotate2portrait():
	"""
	rotate screen to portrait
	:return: None
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		echo.clog('Rotate screen to portrait.')
		d.set_orientation('n')
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('ROTATE TO PORTRAIT FAILED')
	finally:
		echo.pop_subroutine()


def take_screenshot():
	"""
	Take a screenshot
	:return: a numpy array of the screenshot
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		echo.clog('Take a screenshot.')
		screenshot = d.screenshot(format='opencv')
		if (d.info['displayHeight'] - d.info['displayWidth']) * \
			(screenshot.shape[0] - screenshot.shape[1]) < 0:
			screenshot = cv2.rotate(screenshot, cv2.ROTATE_90_COUNTERCLOCKWISE)
		return screenshot
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('TAKE SCREENSHOT FAILED')
	finally:
		echo.pop_subroutine()


def get_image(x1, y1, x2, y2) -> Image:
	"""
	Get image from device screen
	:param x1: top left x of image bound
	:param y1: top left y of image bound
	:param x2: bottom right x of image bound
	:param y2: bottom right y of image bound
	:return: Image object
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		# click center of image
		click_x = x1 * 0.7 + x2 * 0.3
		click_y = (y1 + y2) / 2
		if click_y > d.info['displayHeight'] - BOTTOM_AREA_HEIGHT or click_y < TOP_AREA_HEIGHT: 
			if y1 < TOP_AREA_HEIGHT:
				click_y = (y2 + TOP_AREA_HEIGHT) / 2
			elif y2 > d.info['displayHeight'] - BOTTOM_AREA_HEIGHT:
				click_y = (y1 + d.info['displayHeight'] - BOTTOM_AREA_HEIGHT) / 2
			else:
				raise Exception('Image is not in the visible area')

		click_x = click_x / d.info['displayWidth']
		click_y = click_y / d.info['displayHeight']

		time.sleep(1)
		echo.clog('Click at:', click_x, click_y)
		d.click(click_x, click_y)
		time.sleep(1)
		# take screenshot
		screenshot = take_screenshot()
		# go back
		echo.clog('Press back.')
		d.press('back')
		# get ride of navigation bar part of image
		cropped_image = screenshot[TOP_AREA_HEIGHT:, :, :]
		# calculate pixel sum of image on vertical direction
		vert = np.sum(np.sum(cropped_image, axis=2), axis=1)
		# get black border
		u = 0
		for i in vert:
			if i == 0:
				u += 1
			else:
				break
		vert = vert[::-1]
		b = 0
		for i in vert:
			if i == 0:
				b += 1
			else:
				break
		# crop black border out of image
		if b == 0:
			vert_cropped_image = cropped_image[u:, :, :]
		else:
			vert_cropped_image = cropped_image[u: -b, :, :]
		# calculate pixel sum of image on horizontal direction
		horz = np.sum(np.sum(vert_cropped_image, axis=2), axis=0)
		# get black border
		l = 0
		for i in horz:
			if i == 0:
				l += 1
			else:
				break
		horz = horz[::-1]
		r = 0
		for i in horz:
			if i == 0:
				r += 1
			else:
				break
		# crop black border out of image
		if r == 0:
			horz_cropped_image = vert_cropped_image[:, l:, :]
		else:
			horz_cropped_image = vert_cropped_image[:, l: -r, :]
		# save image
		image_name = os.path.join(DUMP_PATH, f'./{time.time_ns()}.png')
		cv2.imwrite(image_name, horz_cropped_image)
		echo.clog("Image saved,", image_name)
		# return image object
		return Image(image_name, horz_cropped_image.shape)
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET IMAGE FAILED')
	finally:
		echo.pop_subroutine()


def get_visible_elements(quick_mode=False):
	"""
	Get all visible elements on the screen
	:return: a list of visible elements
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		contents = []
		# dump hierarchy
		xml = d.dump_hierarchy()
		soup = BeautifulSoup(xml, 'lxml')
		# select contents
		contentView = soup.select('node[resource-id="android:id/content"] > node[class="android.widget.FrameLayout"] > node[class="android.widget.FrameLayout"] > node[class="android.view.View"] > node[class="android.view.View"] > node[class="android.view.View"] > node[class="android.view.View"] > node[class="android.view.View"] > node[class="android.view.View"]')[0].findAll('node', recursive=False)
		for child in contentView:
			bounds_str = child.attrs['bounds']
			bounds = bounds_str.split('][')
			x1 = int(bounds[0].split(',')[0][1:])
			y1 = int(bounds[0].split(',')[1])
			x2 = int(bounds[1].split(',')[0])
			y2 = int(bounds[1].split(',')[1][:-1])
			
			if y1 + SAFE_AREA_PADDING > d.info['displayHeight'] - BOTTOM_AREA_HEIGHT \
				or y2 - SAFE_AREA_PADDING < TOP_AREA_HEIGHT:
				continue
			if child.attrs['class'] == ['android.view.View']:
				if child.attrs['content-desc'] == '合集帖子\n更多' or \
					str(child.attrs['content-desc']).startswith('全部評論'):
					contents.append(EOF())
					break
				contents.append(child.attrs['content-desc'])
			elif child.attrs['class'] == ['android.widget.ImageView']:
				if quick_mode:
					contents.append(f'Image-Placeholder-{time.time_ns()}')
				else:
					contents.append(get_image(x1, y1, x2, y2))
		return contents
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET VISIBLE ELEMENTS FAILED')
	finally:
		echo.pop_subroutine()


def scroll_to_top():
	"""
	scroll the page to the top
	:return: None
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		last_top = None
		while True:
			d.swipe(0.5, 0.3, 0.5, 0.7, duration=0.1)
			contents = get_visible_elements(quick_mode=True)
			if contents[0] == last_top:
				break
			last_top = contents[0]
			echo.clog('Scrolling to top... last_top:', last_top)
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('SCROLL TO TOP FAILED')
	finally:
		echo.pop_subroutine()


def compare_content(content1, content2):
	"""
	Compare two contents
	:param content1: content 1
	:param content2: content 2
	:return: True if content1 == content2, False otherwise
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		t1 = type(content1)
		t2 = type(content2)
		if t1 == str and t2 == str:
			return content1 == content2
		if t1 != t2:
			return False
		if t1 != Image or t2 != Image:
			raise Exception('Unsupported type.')
		img1 = cv2.imread(content1.filePath)
		img2 = cv2.imread(content2.filePath)
		# judge whether shape of two images are same
		if img1.shape != img2.shape:
			return False
		# convert image to gray scale
		img1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
		img2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
		# calculate diff
		diff = cv2.absdiff(img1, img2)
		echo.clog('Image Diff between', content1.filePath, 'and', content2.filePath, ":", np.average(diff))
		return np.average(diff) < IMAGE_EQUAL_THRESHOLD
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('COMPARE CONTENT FAILED')
	finally:
		echo.pop_subroutine()


def get_content():
	"""
	scroll the page to the bottom and return the content of the page
	:return: the content of the page
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		scroll_to_top()
		time.sleep(2)
		echo.clog('Already scrolled to the top')
		contents = []
		while True:
			visible_contents = get_visible_elements()

			if contents == []:
				contents = visible_contents
				echo.clog("New contents:", contents)
			else:
				check_count = min(len(contents), len(visible_contents))
				# iterate from check_count to zero
				overlap_count = 0
				for i in range(check_count, 0, -1):
					flag = True
					for j in range(i):
						if not compare_content(contents[-(i - j)], visible_contents[j]):
							flag = False
							break
					if flag:
						overlap_count = i
						break
				if overlap_count < check_count:
					new_contents = visible_contents[overlap_count:]
					echo.clog('New contents:', new_contents)
					contents.extend(new_contents)
				else:
					echo.clog('Nothing New')
			# scroll down
			d.swipe(0.5, 0.7, 0.5, 0.3, duration=0.5)
			time.sleep(2)
			echo.clog('Scrolled down.')
			# check whether the page is at the bottom
			if type(contents[-1]) == EOF:
				echo.clog('Reached the end of the page.')
				break
		return contents[:-1]
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET CONTENT FAILED')
	finally:
		echo.pop_subroutine()


def dump_contents(contents):
	"""
	dump the contents to a file
	:param contents: the contents to dump
	:return: None
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		file_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.out')
		pickle.dump(contents, open(file_path, 'wb+'))
		echo.clog('Dumped contents to', file_path)
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('DUMP CONTENT FAILED')
	finally:
		echo.pop_subroutine()


def load_contents(file_path):
	"""
	load the contents from a file
	:param file_path: the file path
	:return: the contents
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		contents = pickle.load(open(file_path, 'rb'))
		echo.clog('Loaded contents from', file_path)
		return contents
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('LOAD CONTENT FAILED')
	finally:
		echo.pop_subroutine()


def get_contents(
	top_area_height, 
	bottom_area_height, 
	image_equal_threshold, 
	safe_area_padding, 
	dump_path, 
	vert_dump, 
	horz_dump,
	html_dump,
	conflict_mode: bool,
	ignore_newline: bool):
	"""
	get contents
	:param top_area_height: the height of the top area
	:param bottom_area_height: the height of the bottom area
	:param image_equal_threshold: the threshold of judging whether two images are equal
	:param safe_area_padding: the padding of the safe area
	:param dump_path: directory for dumping
	:param vert_dump: vertical content dump file path
	:param horz_dump: horizontal content dump file path
	:param html_dump: html content dump file path
	:param conflict_mode: whether to resolve conflict manually
	:param ignore_newline: whether to ignore newline
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	
	global TOP_AREA_HEIGHT
	global BOTTOM_AREA_HEIGHT
	global IMAGE_EQUAL_THRESHOLD
	global SAFE_AREA_PADDING
	global DUMP_PATH
	global d
	TOP_AREA_HEIGHT = top_area_height
	BOTTOM_AREA_HEIGHT = bottom_area_height
	IMAGE_EQUAL_THRESHOLD = image_equal_threshold
	SAFE_AREA_PADDING = safe_area_padding
	DUMP_PATH = dump_path

	try:
		d = u2.connect()
		echo.clog('Device Info:', d.info)
	except Exception as e:
		echo.cexit("CONNECT TO DEVICE FAILED, PLEASE ENSURE DEVICE IS CONNECTED TO ADB, AND THERE IS ONLY ONE DEVICE")

	try:
		# init directory
		if not os.path.exists(dump_path):
			os.mkdir(dump_path)
		if html_dump is not None:
			with open(html_dump, 'r', encoding='utf-8') as f:
				html_content = f.read()
		else:
			# load and dump data
			if vert_dump is not None:
				vert_contents = load_contents(vert_dump)
				echo.clog('Loaded vertical contents from', vert_dump)
				print(vert_contents)
			else:
				rotate2portrait()
				echo.clog('Please make sure that the orientation is portrait **before** entering the app. If not, please quit and re-enter the page. Press <Enter> when ready ...')
				input()
				vert_contents = get_content()
				echo.clog('Got vertical contents')
				dump_contents(vert_contents)
			if horz_dump is not None:
				horz_contents = load_contents(horz_dump)
				echo.clog('Loaded horizontal contents from', horz_dump)
				print(horz_contents)
			else:
				rotate2landscape()			
				print('==========================')
				print('==========================')
				echo.clog('Please quit and re-enter the page. Press <Enter> when ready ...')
				input()
				horz_contents = get_content()
				echo.clog('Got horizontal contents')
				dump_contents(horz_contents)
			# recalculate typesettings
			echo.clog('Recalculating typesettings ...')

			if ignore_newline:
				for i in range(len(vert_contents)):
					if type(vert_contents[i]) == str:
						vert_contents[i] = vert_contents[i].replace('\n', '')
						vert_contents[i] = vert_contents[i].replace('\r', '')
				for i in range(len(horz_contents)):
					if type(horz_contents[i]) == str:
						horz_contents[i] = horz_contents[i].replace('\n', '')
						horz_contents[i] = horz_contents[i].replace('\r', '')

			vert_ptr = horz_ptr = 0
			new_contents = []
			vert_str = horz_str = ''
			while horz_ptr < len(horz_contents):
				this_horz = horz_contents[horz_ptr]
				if type(this_horz) == Image:
					if not horz_str.startswith(vert_str):
						if conflict_mode:
							while not type(vert_contents[vert_ptr]) == Image:
								this_vert = vert_contents[vert_ptr]
								vert_str += this_vert
								vert_ptr += 1
							print('==========================')
							echo.cerr('CONFLICT HAPPENED, choose which version to accept:')
							echo.clog('Portrait (Vertical) Version:', vert_str)
							echo.clog('Landscape (Horizontal) Version:', horz_str)
							while True:
								c = input('Enter "p" or "v" to accept portrait version, "l" or "h" to accept landscape version, or "q" to quit:')
								if c == 'p' or c == 'v' or c == 'P' or c == 'V':
									new_contents.append(vert_str)
									horz_str = vert_str = ''
									break
								elif c == 'l' or c == 'h' or c == 'L' or c == 'H':
									new_contents.append(horz_str)
									horz_str = vert_str = ''
									break
								elif c == 'q' or c == 'Q':
									echo.cexit('USER QUIT')
								else:
									echo.cerr('Invalid input, please try again')
						else:
							echo.cerr('vert content:', vert_str)
							echo.cerr('horz content:', horz_str)
							raise Exception('Unexpected content')
					# string cleaned up
					if not (horz_str == '' and vert_str == ''):
						new_contents.append(horz_str)
						horz_str = vert_str = ''
					while not type(vert_contents[vert_ptr]) == Image:
						vert_ptr += 1
					# compare which image is larger
					this_vert = vert_contents[vert_ptr]
					if this_vert.shape[0] * this_vert.shape[1] > \
						this_horz.shape[0] * this_horz.shape[1]:
						new_contents.append(this_vert)
					else:
						new_contents.append(this_horz)
					horz_ptr += 1
					vert_ptr += 1
					continue
				elif type(this_horz) == str:
					horz_str += this_horz
					horz_ptr += 1

					while vert_ptr < len(vert_contents) and len(vert_str) < len(horz_str):
						this_vert = vert_contents[vert_ptr]
						if type(this_vert) != str:
							if conflict_mode:
								while not type(horz_contents[horz_ptr]) == Image:
									this_horz = horz_contents[horz_ptr]
									horz_str += this_horz
									horz_ptr += 1
								print('==========================')
								echo.cerr('CONFLICT HAPPENED, choose which version to accept:')
								echo.clog('Portrait (Vertical) Version:', vert_str)
								echo.clog('Landscape (Horizontal) Version:', horz_str)
								while True:
									c = input('Enter "p" or "v" to accept portrait version, "l" or "h" to accept landscape version, or "q" to quit:')
									if c == 'p' or c == 'v' or c == 'P' or c == 'V':
										new_contents.append(vert_str)
										horz_str = vert_str = ''
										break
									elif c == 'l' or c == 'h' or c == 'L' or c == 'H':
										new_contents.append(horz_str)
										horz_str = vert_str = ''
										break
									elif c == 'q' or c == 'Q':
										echo.cexit('USER QUIT')
									else:
										echo.cerr('Invalid input, please try again')
								break
							else:
								raise Exception('Unexpected content')
						vert_str += this_vert
						vert_ptr += 1

					if conflict_mode and horz_str == '' and vert_str == '':
						continue

					if horz_str == vert_str:
						new_contents.append(horz_str)
						horz_str = vert_str = ''
						continue
				else:
					raise Exception('Unknown type:', type(this_horz))

			# dump_contents(new_contents)

			doc = dominate.document(title='HTML of LK generated by JeffersonQin/lightnovel_epub')

			with doc:
				for content in new_contents:
					if isinstance(content, str):
						dominate.tags.p(content)
					elif isinstance(content, Image):
						img = dominate.tags.img(src=os.path.abspath(content.filePath))
						img.attributes['style'] = 'width: 100%;'
					else:
						raise Exception('Unknown type:', type(content))
			html_content = doc.render()

			html_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.html')
			with open(html_path, 'w+', encoding='utf-8') as f:
				f.write(html_content)
			echo.clog('Dumped HTML to', html_path)
		
		return html_content
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('DUMP CONTENT FAILED')
	finally:
		echo.pop_subroutine()


def get_cover(cover_link, dump_path):
	'''
	Get cover from link.
	:param cover_link: link to cover
	:param dump_path: path to dump cover
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		cover_name = cover_link.split('?')[0].split('/')[-1]
		cover_dir = os.path.join(dump_path, cover_name)
		downloader.download_file(cover_link, cover_dir, {})
		return cover_dir
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET COVER FAILED')
	finally:
		echo.pop_subroutine()


================================================
FILE: provider/lk_new.py
================================================
import time
import sys
import traceback
import os
import requests
import js2py
from bs4 import BeautifulSoup

from utils import downloader
from utils import echo


DUMP_PATH = './dump'
DOCUMENT_DOWNLOAD_HEADERS = {
	'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
	'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
	'cache-control': 'no-cache',
	'pragma': 'no-cache',
	'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Microsoft Edge";v="92"',
	'sec-ch-ua-mobile': '?0',
	'sec-fetch-dest': 'document',
	'sec-fetch-mode': 'navigate',
	'sec-fetch-site': 'same-origin',
	'sec-fetch-user': '?1',
	'upgrade-insecure-requests': '1',
	'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84'
}
IMAGE_DOWNLOAD_HEADERS = {
	'accept': 'image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',
	'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
	'cache-control': 'no-cache',
	'pragma': 'no-cache',
	'referer': 'https://www.lightnovel.us/',
	'sec-ch-ua': '"Chromium";v="92", " Not A;Brand";v="99", "Microsoft Edge";v="92"',
	'sec-ch-ua-mobile': '?0',
	'sec-fetch-dest': 'image',
	'sec-fetch-mode': 'no-cors',
	'sec-fetch-site': 'same-site',
	'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84',
}


def process_series_page(url):
	'''
	Process the series page.
	:param url: url to process
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)

	res = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS)
	# parse
	try:
		soup = BeautifulSoup(res, 'lxml')
		scripts = soup.find_all('script')

		for script in scripts:
			if script.string is not None:
				if script.string.startswith('window.__NUXT__'):
					context = js2py.EvalJs()
					context.execute(script.string)
					
					data = context.window.__NUXT__.to_dict()
					return data['data'][0]['series']['articles']
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('PARSING FAILED')
	finally:
		echo.pop_subroutine()


def obtain_article_content(content):
	'''
	obtain article content
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)
	# parse
	try:
		soup = BeautifulSoup(content, 'lxml')
		article = soup.find('article', id='article-main-contents')
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('PARSING FAILED')

	echo.pop_subroutine()
	return str(article)


def download_images(content, dump_path):
	"""
	download images from content
	:param content: html content
	:param dump_path: path to dump updated html
	:return:
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)
	
	echo.clog(f'Start Parsing Images')

	# parse images
	try:
		soup = BeautifulSoup(content, 'lxml')
		images = soup.find_all('img')
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('PARSING FAILED')
	# download images
	try:
		i = 0
		for tag in images:
			i += 1
			echo.clog(f'Processing images: ({i} / {len(images)})')
			# parse
			link = str(tag.attrs['src'])
			if link.startswith('http') or link.startswith('//'):
				file_name = link.split('?')[0].split('/')[-1]
				file_dir = os.path.join(DUMP_PATH, file_name)
				# download
				downloader.download_file(link, file_dir, IMAGE_DOWNLOAD_HEADERS)
				# replace src
				tag.attrs['src'] = os.path.abspath(file_dir)
				# update html
				with open(dump_path, 'w', encoding='utf-8') as f:
					f.write(str(soup))
		return str(soup)
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('DOWNLOAD FAILED')
	finally:
		echo.pop_subroutine()


def process_article_page(url, dump_path):
	'''
	Process the article page.
	:param url: url to process
	:param dump_path: path to dump html
	:return: string of html content
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)

	try:
		flag = True
		# obtain html
		if dump_path is not None:
			if os.path.exists(dump_path):
				with open(dump_path, 'r', encoding='utf-8') as f:
					content = f.read()
				flag = False
		if flag:
			content = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS)

		content = obtain_article_content(content)

		if flag:
			if dump_path is None:
				dump_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.html')
			with open(dump_path, 'w', encoding='utf-8') as f:
				f.write(content)
			echo.clog(f'Dumped HTML to {dump_path}')
		# download images
		content = download_images(content, dump_path)

		return content
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('PROCESS PAGE FAILED')
	finally:
		echo.pop_subroutine()


def get_contents(url, dump_path, html_dump):
	'''
	Get contents from url.
	:param url: url to process
	:param dump_path: path to dump things
	:param html_dump: html dump path
	'''
	global DUMP_PATH
	DUMP_PATH = dump_path

	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		if 'series' in url:
			contents = []
			# series
			articles = process_series_page(url)
			i = 0
			for article in articles:
				i += 1
				echo.clog(f'Processing article {i} / {len(articles)}')
				a_title = article["title"]
				aid = article["aid"]
				echo.clog(f'Title: {a_title}')
				echo.clog(f'Article ID: {aid}')
				a_url = f'https://www.lightnovel.us/cn/detail/{aid}/'
				a_dump_path = os.path.join(dump_path, f'{aid}.html')
				a_content = process_article_page(a_url, a_dump_path)
				contents.append({
					'title': a_title,
					'content': a_content
				})
		else:
			# article
			contents = process_article_page(url, html_dump)
		
		return contents
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET CONTENTS FAILED')
	finally:
		echo.pop_subroutine()


def get_cover(cover_link, dump_path):
	'''
	Get cover from link.
	:param cover_link: link to cover
	:param dump_path: path to dump cover
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		cover_name = cover_link.split('?')[0].split('/')[-1]
		cover_dir = os.path.join(dump_path, cover_name)
		downloader.download_file(cover_link, cover_dir, IMAGE_DOWNLOAD_HEADERS)
		return cover_dir
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET COVER FAILED')
	finally:
		echo.pop_subroutine()


================================================
FILE: provider/wenku8.py
================================================
from __future__ import annotations
import time
import sys
import traceback
import os
import re
from bs4 import BeautifulSoup

from utils import downloader
from utils import echo


DOCUMENT_DOWNLOAD_HEADERS = {
    'accept':
    'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Content-Type': 'text/html; charset=unicode',
    'accept-language':
    'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
    'cache-control':
    'no-cache',
    'pragma':
    'no-cache',
    'sec-ch-ua':
    '"Chromium";v="92", " Not A;Brand";v="99", "Microsoft Edge";v="92"',
    'sec-ch-ua-mobile':
    '?0',
    'sec-fetch-dest':
    'document',
    'sec-fetch-mode':
    'navigate',
    'sec-fetch-site':
    'same-origin',
    'sec-fetch-user':
    '?1',
    'upgrade-insecure-requests':
    '1',
    'user-agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36 Edg/92.0.902.84'
}

IMAGE_DOWNLOAD_HEADERS = {
    'Accept':
    'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
    'Accept-Language':
    'zh-CN,zh;q=0.9,en;q=0.8',
    'Host':
    'pic.wenku8.com',
    'Proxy-Connection':
    'keep-alive',
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
}

DECODE = 'gbk'
ENCODE = 'utf-8'

class BookInfo:
	def __init__(self, aid, cid, title, content=None, href=None) -> None:
		self.aid: str = aid
		self.cid: str = cid
		self.title: str = title
		self.content: str = content
		self.href: str = href


def obtain_article_content(url):
	'''
	download web content
	:param url: url to download
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)

	res = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS, DECODE)
	# parse
	try:
		soup = BeautifulSoup(res, 'lxml')
		article = soup.find('article', id='article-main-contents')
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('PARSING FAILED')

	echo.pop_subroutine()
	return str(article)


def download_images(content, dump_path):
	"""
	download images from content
	:param content: html content
	:param dump_path: path to dump updated html
	:return:
	"""
	echo.push_subroutine(sys._getframe().f_code.co_name)

	echo.clog(f'Start Parsing Images')

	# parse images
	try:
		soup = BeautifulSoup(content, 'lxml')
		images = soup.find_all('img')
	except Exception as e:
		echo.cerr(f'Error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('PARSING FAILED')
	# download images
	try:
		i = 0
		for tag in images:
			i += 1
			echo.clog(f'Processing images: ({i} / {len(images)})')
			# parse
			link = str(tag.attrs['src'])
			if link.startswith('http') or link.startswith('//'):
				file_name = link.split('?')[0].split('/')[-1]
				file_dir = os.path.join(DUMP_PATH, file_name)
				# download
				downloader.download_file(link, file_dir, IMAGE_DOWNLOAD_HEADERS)
				# replace src
				tag.attrs['src'] = os.path.abspath(file_dir)
				# update html
				with open(dump_path, 'w', encoding=ENCODE) as f:
					f.write(str(soup))
		return str(soup)
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('DOWNLOAD FAILED')
	finally:
		echo.pop_subroutine()

def process_article_page(url, dump_path, cvt=None):
    '''
        Process the article page.
        :param url: url to process
        :param dump_path: path to dump html
        :return: string of html content
        '''
    echo.push_subroutine(sys._getframe().f_code.co_name)

    try:
        flag = True
        # obtain html
        if dump_path is not None:
            if os.path.exists(dump_path):
                with open(dump_path, 'r', encoding=ENCODE) as f:
                    content = f.read()
                flag = False
        if flag:
            content = obtain_article_content(url)
            if dump_path is None:
                dump_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.html')
            with open(dump_path, 'w', encoding=ENCODE) as f:
                f.write(content)
            echo.clog(f'Dumped HTML to {dump_path}')
        # download images
        content = download_images(content, dump_path)

        return content
    except Exception as e:
        echo.cerr(f'error: {repr(e)}')
        traceback.print_exc()
        echo.cexit('PROCESS PAGE FAILED')
    finally:
        echo.pop_subroutine()

def getBookStructure(source: str, content: str):
	soup = BeautifulSoup(content, 'lxml')
	title = soup.find(id='title').text
	author = soup.find(id='info').text.replace('作者:', '')
	table = soup.find('table')
	units = table.find_all('td')
	bookId = re.search(r'var article_id = "(\S+)"', content)[1]
	books = {}
	curBook = None
	for unit in units:
		# print(unit.prettify())
		cl = unit.get('class')[0]
		if cl == 'vcss':
			curBook = unit.text
			books[curBook] = []
		elif cl == 'ccss':
			atag = unit.find('a')
			if atag is None:
				continue
			aid = re.search(r'var article_id = "(\S+)"', content)[1]
			cid = re.search(r'var chapter_id = "(\S+)"', content)[1]
			curChapter = BookInfo(aid,
						cid,
						href=atag.attrs['href'],
						title=atag.text)
			if curBook not in books:
				echo.cexit(f'No current book specified: {curChapter}')
			books[curBook].append(curChapter)
	return (source, author, bookId, title, books)


def getContent(content: str) -> BookInfo:
	aid = re.search(r'var article_id = "(\S+)"', content)[1]
	cid = re.search(r'var chapter_id = "(\S+)"', content)[1]
	soup = BeautifulSoup(content, 'lxml')
	title = soup.find('div', id='title').text
	content = soup.find('div', id='contentmain').prettify()
	return BookInfo(aid, cid, title, content)

def get_contents(url, dump_path, volume_index):
	'''
	Get contents from url.
	:param url: url to process
	:param dump_path: path to dump things
	:param volume_index: index of volume to generate
	:returns: LightNovel class
	'''
	global DUMP_PATH
	DUMP_PATH = dump_path

	echo.push_subroutine(sys._getframe().f_code.co_name)

	try:
		assert ('novel' in url) and ('index.htm' in url), 'not wenku8 novel toc page'
		relative = url.replace('index.htm', '')
		content = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS, DECODE)
		(source, author, bookId, title, books) = getBookStructure(url, content)
		contents = []
		book_titles = books.keys()
		volume_count = len(book_titles)

		if volume_index > volume_count:
			echo.cexit("ERROR: VOLUME INDEX OUT OF RANGE, TOTAL VOLUME:", volume_count)

		# series
		cur_volume_index = 0
		for book_title in book_titles:
			cur_volume_index += 1
			echo.clog(f'Processing volume {book_title} {cur_volume_index} / {volume_count}')

			if volume_index != -1 and volume_index != cur_volume_index: continue

			ch_index = 0
			for chapter in books[book_title]:
				addr = relative + '/' + chapter.href
				chWeb = downloader.download_webpage(addr, DOCUMENT_DOWNLOAD_HEADERS, DECODE)
				chContent = getContent(chWeb)
				a_title = chContent.title
				aid = chContent.cid

				ch_index += 1
				echo.clog(f'Processing chapter {ch_index} / {len(books[book_title])}')
				echo.clog(f'Title: {a_title}')
				echo.clog(f'Article ID: {aid}')

				a_dump_path = os.path.join(dump_path, f'{aid}.html')
				with open(a_dump_path, 'w', encoding=ENCODE) as f:
					echo.clog(f'Save content to {a_dump_path}')
					f.write(chContent.content)
				# to call download images
				img_content = process_article_page(None, a_dump_path)
				contents.append({'title': a_title, 'content': img_content})

		return source, author, bookId, title, books, contents
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET CONTENTS FAILED')
	finally:
		echo.pop_subroutine()


def get_cover(cover_link, dump_path):
	'''
	Get cover from link.
	:param cover_link: link to cover
	:param dump_path: path to dump cover
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)
	try:
		cover_name = cover_link.split('?')[0].split('/')[-1]
		cover_dir = os.path.join(dump_path, cover_name)
		downloader.download_file(cover_link, cover_dir, IMAGE_DOWNLOAD_HEADERS)
		return cover_dir
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		echo.cexit('GET COVER FAILED')
	finally:
		echo.pop_subroutine()


================================================
FILE: utils/checker.py
================================================

def is_null(data):
	if data is None:
		return True
	if data == {}:
		return True
	if data == []:
		return True
	if data == "":
		return True
	return False

def is_not_null(data):
	return not is_null(data)


================================================
FILE: utils/downloader.py
================================================
import sys
import requests
import os
import unicodedata
import re
import click
import traceback

from utils import echo

def _download_file(url, dir, headers):
	echo.push_subroutine(sys._getframe().f_code.co_name)

	echo.clog(f'start downloading: {url} => {dir}')
	ret = 0
	try:
		# start and block request
		r = requests.get(url, stream=True, headers=headers, timeout=3000)
		# obtain content length
		length = int(r.headers['content-length'])
		echo.clog(f'file size: {size_description(length)}')
		THRESHOLD = 32
		if os.path.exists(dir) and abs(os.path.getsize(dir) - length) < THRESHOLD:
			echo.clog(f'file already exists {dir}')
		else:
			# start writing
			f = open(dir, 'wb+')
			# show in progressbar
			with click.progressbar(label="Downloading from remote: ", length=length) as bar:
				for chunk in r.iter_content(chunk_size = 512):
					if chunk:
						f.write(chunk)
						bar.update(len(chunk))
			echo.csuccess('Download Complete.')
			f.close()
	except Exception as err:
		echo.cerr(f'Error: {repr(err)}')
		traceback.print_exc()
		ret = 1
	finally:
		echo.pop_subroutine()
		return ret


def download_file(url, dir, headers, trial=5):
	fail_count = 0
	while True:
		ret = _download_file(url, dir, headers)
		if ret == 0:
			return
		if fail_count < trial:
			fail_count += 1
			echo.cerr(f'Download failed, Trial {fail_count}/{trial}')
		else:
			echo.cexit('Download failed. Exceeded trial limit.')


def _download_webpage(url, headers, encoding):
	'''
	Download webpage from url.
	:param url: url to download
	'''
	echo.push_subroutine(sys._getframe().f_code.co_name)

	echo.clog(f'start downloading: {url} => memory')
	# download
	try:
		return requests.get(url=url, headers=headers).content.decode(encoding)
	except Exception as e:
		echo.cerr(f'error: {repr(e)}')
		traceback.print_exc()
		return -1
	finally:
		echo.pop_subroutine()


def download_webpage(url, headers, encoding='utf-8', trial=5):
	'''
	Download webpage from url.
	:param url: url to download
	:param trial: number of trials
	'''
	fail_count = 0
	while True:
		ret = _download_webpage(url, headers, encoding)
		if ret != -1:
			return ret
		if fail_count < trial:
			fail_count += 1
			echo.cerr(f'Download failed, Trial {fail_count}/{trial}')
		else:
			echo.cexit('Download failed. Exceeded trial limit.')


def size_description(size):
	'''
	Taken and modified from https://blog.csdn.net/wskzgz/article/details/99293181
	'''
	def strofsize(integer, remainder, level):
		if integer >= 1024:
			remainder = integer % 1024
			integer //= 1024
			level += 1
			return strofsize(integer, remainder, level)
		else:
			return integer, remainder, level

	units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
	integer, remainder, level = strofsize(size, 0, 0)
	if level + 1 > len(units):
		level = -1
	return ( '{}.{:>03d} {}'.format(integer, remainder, units[level]) )


================================================
FILE: utils/echo.py
================================================
import click
import sys


def init_subroutine():
	global subroutine_stack
	subroutine_stack = []


def push_subroutine(cmd_name: str):
	global subroutine_stack
	subroutine_stack.append(cmd_name)


def pop_subroutine():
	global subroutine_stack
	last = subroutine_stack[-1]
	subroutine_stack = subroutine_stack[:-1]
	return last


def get_subroutine():
	return subroutine_stack[-1]


def _clog(message: str):
	click.echo(click.style(f"[{get_subroutine()}]", bg='magenta', fg='white'), nl=False)
	click.echo(message)


def clog(*messages):
	val = ''
	for message in messages:
		val = val + ' ' + str(message)
	_clog(val)


def _cerr(message: str):
	click.echo(click.style(f"[{get_subroutine()}]", bg='magenta', fg='white'), nl=False)
	click.echo(click.style(f" {message}", fg = 'bright_red'))


def cerr(*messages):
	val = ''
	for message in messages:
		val = val + ' ' + str(message)
	_cerr(val)


def _csuccess(message: str):
	click.echo(click.style(f"[{get_subroutine()}]", bg='magenta', fg='white'), nl=False)
	click.echo(click.style(f" {message}", fg = 'green'))


def csuccess(*messages):
	val = ''
	for message in messages:
		val = val + ' ' + str(message)
	_csuccess(val)


def _cexit(message: str):
	cerr(f'{message}, exiting program.')
	sys.exit(1)


def cexit(*messages):
	val = ''
	for message in messages:
		val = val + ' ' + str(message)
	_cexit(val)
Download .txt
gitextract_33nrehfm/

├── .gitignore
├── LICENSE
├── LICENSE_AGPL
├── LICENSE_MIT
├── README.md
├── cli.py
├── gui.py
├── lightnovel.py
├── provider/
│   ├── lk_mobile.py
│   ├── lk_new.py
│   └── wenku8.py
├── requirements.txt
└── utils/
    ├── checker.py
    ├── downloader.py
    └── echo.py
Download .txt
SYMBOL INDEX (56 symbols across 8 files)

FILE: cli.py
  function cli (line 18) | def cli():
  function download (line 65) | def download(

FILE: lightnovel.py
  class LightNovel (line 12) | class LightNovel():
    method __init__ (line 50) | def __init__(self, source: str, authors=None, identifier=None, title=N...
    method process_image_content (line 61) | def process_image_content(self, content, book):
    method write_epub (line 117) | def write_epub(self, path: str):

FILE: provider/lk_mobile.py
  class Image (line 24) | class Image:
    method __init__ (line 30) | def __init__(self, filePath, shape):
  class EOF (line 35) | class EOF:
    method __init__ (line 36) | def __init__(self):
  function rotate2landscape (line 40) | def rotate2landscape():
  function rotate2portrait (line 57) | def rotate2portrait():
  function take_screenshot (line 74) | def take_screenshot():
  function get_image (line 95) | def get_image(x1, y1, x2, y2) -> Image:
  function get_visible_elements (line 187) | def get_visible_elements(quick_mode=False):
  function scroll_to_top (line 231) | def scroll_to_top():
  function compare_content (line 254) | def compare_content(content1, content2):
  function get_content (line 291) | def get_content():
  function dump_contents (line 344) | def dump_contents(contents):
  function load_contents (line 363) | def load_contents(file_path):
  function get_contents (line 382) | def get_contents(
  function get_cover (line 597) | def get_cover(cover_link, dump_path):

FILE: provider/lk_new.py
  function process_series_page (line 43) | def process_series_page(url):
  function obtain_article_content (line 72) | def obtain_article_content(content):
  function download_images (line 90) | def download_images(content, dump_path):
  function process_article_page (line 136) | def process_article_page(url, dump_path):
  function get_contents (line 176) | def get_contents(url, dump_path, html_dump):
  function get_cover (line 220) | def get_cover(cover_link, dump_path):

FILE: provider/wenku8.py
  class BookInfo (line 57) | class BookInfo:
    method __init__ (line 58) | def __init__(self, aid, cid, title, content=None, href=None) -> None:
  function obtain_article_content (line 66) | def obtain_article_content(url):
  function download_images (line 87) | def download_images(content, dump_path):
  function process_article_page (line 132) | def process_article_page(url, dump_path, cvt=None):
  function getBookStructure (line 167) | def getBookStructure(source: str, content: str):
  function getContent (line 198) | def getContent(content: str) -> BookInfo:
  function get_contents (line 206) | def get_contents(url, dump_path, volume_index):
  function get_cover (line 269) | def get_cover(cover_link, dump_path):

FILE: utils/checker.py
  function is_null (line 2) | def is_null(data):
  function is_not_null (line 13) | def is_not_null(data):

FILE: utils/downloader.py
  function _download_file (line 11) | def _download_file(url, dir, headers):
  function download_file (line 45) | def download_file(url, dir, headers, trial=5):
  function _download_webpage (line 58) | def _download_webpage(url, headers, encoding):
  function download_webpage (line 77) | def download_webpage(url, headers, encoding='utf-8', trial=5):
  function size_description (line 95) | def size_description(size):

FILE: utils/echo.py
  function init_subroutine (line 5) | def init_subroutine():
  function push_subroutine (line 10) | def push_subroutine(cmd_name: str):
  function pop_subroutine (line 15) | def pop_subroutine():
  function get_subroutine (line 22) | def get_subroutine():
  function _clog (line 26) | def _clog(message: str):
  function clog (line 31) | def clog(*messages):
  function _cerr (line 38) | def _cerr(message: str):
  function cerr (line 43) | def cerr(*messages):
  function _csuccess (line 50) | def _csuccess(message: str):
  function csuccess (line 55) | def csuccess(*messages):
  function _cexit (line 62) | def _cexit(message: str):
  function cexit (line 67) | def cexit(*messages):
Condensed preview — 15 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (111K chars).
[
  {
    "path": ".gitignore",
    "chars": 1985,
    "preview": "# Custom settings\r\ndump\r\n\r\n# VSCode settings\r\n.vscode\r\n\r\n# Byte-compiled / optimized / DLL files\r\n__pycache__/\r\n*.py[cod"
  },
  {
    "path": "LICENSE",
    "chars": 130,
    "preview": "MIXED LICENSE\n\nlightnovel.py and cli.py are licensed under AGPL license.\n\nOther files in the repo are licensed under MIT"
  },
  {
    "path": "LICENSE_AGPL",
    "chars": 34520,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "LICENSE_MIT",
    "chars": 1065,
    "preview": "MIT License\n\nCopyright (c) 2021 gyro永不抽风\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\no"
  },
  {
    "path": "README.md",
    "chars": 11206,
    "preview": "- [Introduction](#introduction)\n- [Supported Sites Overview](#supported-sites-overview)\n- [Requirements](#requirements)\n"
  },
  {
    "path": "cli.py",
    "chars": 6712,
    "preview": "import click\nimport sys\nimport traceback\nimport os\nimport opencc\n\nfrom lightnovel import LightNovel\nfrom utils import ec"
  },
  {
    "path": "gui.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "lightnovel.py",
    "chars": 5890,
    "preview": "import os\nimport sys\nimport traceback\nimport base64\nfrom bs4 import BeautifulSoup\nfrom ebooklib import epub\n\nfrom utils "
  },
  {
    "path": "provider/lk_mobile.py",
    "chars": 18008,
    "preview": "import uiautomator2 as u2\nfrom bs4 import BeautifulSoup\nimport cv2\nimport time\nimport numpy as np\nimport sys\nimport pick"
  },
  {
    "path": "provider/lk_new.py",
    "chars": 6506,
    "preview": "import time\nimport sys\nimport traceback\nimport os\nimport requests\nimport js2py\nfrom bs4 import BeautifulSoup\n\nfrom utils"
  },
  {
    "path": "provider/wenku8.py",
    "chars": 8345,
    "preview": "from __future__ import annotations\nimport time\nimport sys\nimport traceback\nimport os\nimport re\nfrom bs4 import Beautiful"
  },
  {
    "path": "utils/checker.py",
    "chars": 206,
    "preview": "\ndef is_null(data):\n\tif data is None:\n\t\treturn True\n\tif data == {}:\n\t\treturn True\n\tif data == []:\n\t\treturn True\n\tif data"
  },
  {
    "path": "utils/downloader.py",
    "chars": 2847,
    "preview": "import sys\nimport requests\nimport os\nimport unicodedata\nimport re\nimport click\nimport traceback\n\nfrom utils import echo\n"
  },
  {
    "path": "utils/echo.py",
    "chars": 1434,
    "preview": "import click\r\nimport sys\r\n\r\n\r\ndef init_subroutine():\r\n\tglobal subroutine_stack\r\n\tsubroutine_stack = []\r\n\r\n\r\ndef push_sub"
  }
]

// ... and 1 more files (download for full content)

About this extraction

This page contains the full source code of the JeffersonQin/lightnovel_epub GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 15 files (96.5 KB), approximately 26.4k tokens, and a symbol index with 56 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!