[
  {
    "path": ".gitignore",
    "content": "# 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]\r\n*$py.class\r\n\r\n# C extensions\r\n*.so\r\n\r\n# Distribution / packaging\r\n.Python\r\nbuild/\r\ndevelop-eggs/\r\ndist/\r\ndownloads/\r\neggs/\r\n.eggs/\r\nlib/\r\nlib64/\r\nparts/\r\nsdist/\r\nvar/\r\nwheels/\r\npip-wheel-metadata/\r\nshare/python-wheels/\r\n*.egg-info/\r\n.installed.cfg\r\n*.egg\r\nMANIFEST\r\n\r\n# PyInstaller\r\n#  Usually these files are written by a python script from a template\r\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\r\n*.manifest\r\n*.spec\r\n\r\n# Installer logs\r\npip-log.txt\r\npip-delete-this-directory.txt\r\n\r\n# Unit test / coverage reports\r\nhtmlcov/\r\n.tox/\r\n.nox/\r\n.coverage\r\n.coverage.*\r\n.cache\r\nnosetests.xml\r\ncoverage.xml\r\n*.cover\r\n*.py,cover\r\n.hypothesis/\r\n.pytest_cache/\r\n\r\n# Translations\r\n*.mo\r\n*.pot\r\n\r\n# Django stuff:\r\n*.log\r\nlocal_settings.py\r\ndb.sqlite3\r\ndb.sqlite3-journal\r\n\r\n# Flask stuff:\r\ninstance/\r\n.webassets-cache\r\n\r\n# Scrapy stuff:\r\n.scrapy\r\n\r\n# Sphinx documentation\r\ndocs/_build/\r\n\r\n# PyBuilder\r\ntarget/\r\n\r\n# Jupyter Notebook\r\n.ipynb_checkpoints\r\n\r\n# IPython\r\nprofile_default/\r\nipython_config.py\r\n\r\n# pyenv\r\n.python-version\r\n\r\n# pipenv\r\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\r\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\r\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\r\n#   install all needed dependencies.\r\n#Pipfile.lock\r\n\r\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\r\n__pypackages__/\r\n\r\n# Celery stuff\r\ncelerybeat-schedule\r\ncelerybeat.pid\r\n\r\n# SageMath parsed files\r\n*.sage.py\r\n\r\n# Environments\r\n.env\r\n.venv\r\nenv/\r\nvenv/\r\nENV/\r\nenv.bak/\r\nvenv.bak/\r\n\r\n# Spyder project settings\r\n.spyderproject\r\n.spyproject\r\n\r\n# Rope project settings\r\n.ropeproject\r\n\r\n# mkdocs documentation\r\n/site\r\n\r\n# mypy\r\n.mypy_cache/\r\n.dmypy.json\r\ndmypy.json\r\n\r\n# Pyre type checker\r\n.pyre/\r\n"
  },
  {
    "path": "LICENSE",
    "content": "MIXED LICENSE\n\nlightnovel.py and cli.py are licensed under AGPL license.\n\nOther files in the repo are licensed under MIT license.\n"
  },
  {
    "path": "LICENSE_AGPL",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<http://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "LICENSE_MIT",
    "content": "MIT License\n\nCopyright (c) 2021 gyro永不抽风\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "- [Introduction](#introduction)\n- [Supported Sites Overview](#supported-sites-overview)\n- [Requirements](#requirements)\n- [Usage Overview](#usage-overview)\n- [Usage](#usage)\n\t- [轻之国度](#轻之国度)\n\t\t- [Options](#options)\n\t\t- [高权限文章](#高权限文章)\n\t\t- [缓存相关](#缓存相关)\n\t- [轻之国度 App](#轻之国度-app)\n\t\t- [Options](#options-1)\n\t\t- [Prerequisite](#prerequisite)\n\t\t- [Background](#background)\n\t\t- [界面布局相关参数](#界面布局相关参数)\n\t\t- [旋转相关](#旋转相关)\n\t\t- [合并模式相关](#合并模式相关)\n\t\t- [Mumu 模拟器点击位置不正确解决方案](#mumu-模拟器点击位置不正确解决方案)\n\t\t- [缓存相关](#缓存相关-1)\n\t- [轻小说文库](#轻小说文库)\n\t\t- [Options](#options-2)\n\t\t- [缓存相关](#缓存相关-2)\n\t\t- [指定卷数](#指定卷数)\n- [Known Issues](#known-issues)\n- [TODO](#todo)\n- [Contribution](#contribution)\n- [LICENSE](#license)\n- [技术分析](#技术分析)\n\t- [原理概览](#原理概览)\n\t- [轻之国度网页版 合集文章](#轻之国度网页版-合集文章)\n\n# Introduction\n\n~~本工具用于基于[轻之国度](https://lightnovel.us)网页或 app 生成`epub`小说。~~\n\nUpdate [2022/01/20]: **现已升级成为轻小说 epub 生成框架，支持更多网站**~~（当年名字取得好啊！）~~\n\nUpdate [2023/09/08 (EST)]: 呃呃 LK 加了 Cloudflare 反爬，直接下载是寄了，但是还可以通过保存 `html` 然后指定 `--lk-html-dump` 参数来解决问题。\n\n**注意：本工具仅作学习交流使用，作者不对内容和使用情况付任何责任！**\n\n~~本来就是一个面向过程的小工具，怎么越发繁琐起来了。。。这里还要感慨一下LK牛逼的防御技术~~\n\n# Supported Sites Overview\n\n| 站点 | 单页 | 合集 | 详细说明 |\n| :--: | :---: | :---: | :-: |\n| [轻之国度](https://www.lightnovel.us) | ✅ | ✅ | [说明](#轻之国度) |\n| 轻之国度 App | ✅ | ❌ | [说明](#轻之国度-app) |\n| [轻小说文库](https://www.wenku8.net/index.php) | ❌ | ✅ | [说明](#轻小说文库) |\n\n# Requirements\n\n* python 3.5 +\n* click\n* beautifulsoup4\n* requests\n* ebooklib\n* uiautomator2\n* dominate\n* opencc\n* opencv\n* js2py\n\n# Usage Overview\n\n下载命令：\n\n```bash\npython3 cli.py download <options> <url>\n```\n\n下面是我写的 `--help`:\n\n```\n$ python3 cli.py download --help\nUsage: cli.py download [OPTIONS] URL\n\n  download the light novel\n\n  ARGUMENTS:\n\n  * URL: url of light novel to download\n\nOptions:\n  --dump-path PATH                directory for dumping files and caches      \n  --title TEXT                    title of light novel\n  --authors TEXT                  authors' names, separated by comma (,)      \n  --identifier TEXT               identifier of light novel\n  --cover-link TEXT               cover link of light novel. cover link can   \n                                  either be web link or file path. if it is   \n                                  not beginned with \"http\", it would be       \n                                  recognized as file path. if nothing was     \n                                  given, then it will use the first picture of\n                                  webpage.\n  --cvt TEXT                      OpenCC conversion configuration, used to    \n                                  convert between different Chinese\n                                  characters. you can choose the value from\n                                  \"s2t\", \"t2s\", \"s2tw\", \"tw2s\", \"s2hk\",\n                                  \"hk2s\", \"s2twp\", \"tw2sp\", \"t2tw\", \"hk2t\",\n                                  \"t2hk\", \"t2jp\", \"jp2t\", \"tw2t\". if nothing\n                                  is provided, no conversion would be\n                                  performed. for more information, please\n                                  visit: https://github.com/BYVoid/OpenCC\n  --path PATH                     directory for saving the light novel\n  --lk-html-dump PATH             (lightnovel.us) html content dump file path\n  --wenku8-volume INTEGER         (wenku8.net) identify the index of the\n                                  volume to generate. -1 means every volume,\n                                  which is also the default option. index\n                                  starts from 1.\n  --lk-mobile-top-area-height INTEGER\n                                  (lk mobile) the height of the top area\n  --lk-mobile-bottom-area-height INTEGER\n                                  (lk mobile) the height of the bottom area\n  --lk-mobile-image-equal-threshold INTEGER\n                                  (lk mobile) the threshold of judging whether\n                                  two images are equal\n  --lk-mobile-safe-area-padding INTEGER\n                                  (lk mobile) the padding of the safe area\n  --lk-mobile-vert-dump PATH      (lk mobile) vertical content dump file path\n  --lk-mobile-horz-dump PATH      (lk mobile) horizontal content dump file\n                                  path\n  --lk-mobile-html-dump PATH      (lk mobile) html content dump file path\n  --lk-mobile-conflict-mode BOOLEAN\n                                  (lk mobile) whether to resolve conflict\n                                  manually\n  --lk-mobile-ignore-newline BOOLEAN\n                                  (lk mobile) whether to ignore newline\n  --help                          Show this message and exit.\n```\n\n注意：\n* 书籍有关的 `options` 可以直接忽略，因为执行命令后如果发现没有 `options` 会进行第二轮询问。\n* `dump-path` 是指缓存以及其他的临时文件的输出位置，若提示找不到路径，创建即可\n* 针对每个网站，可能有自己的 `options`，具体可以参见 `help` 和下一小节\n\n# Usage\n\n## 轻之国度\n\n### Options\n\n```\n  --lk-html-dump PATH             (lightnovel.us) html content dump file path\n```\n\n### 高权限文章\n\n有部分文章会 **先显示无权限观看，后可以观看 先显示无权限观看，后可以观看**。这种情况下，浏览器保存 `HTML`，然后启用 `--lk-html-dump` 选项即可。\n\n### 缓存相关\n\n* 单页面\n  * 会缓存 HTML，每下载一张图片后会用本地路径替换掉 HTML 中的链接\n* 合集\n  * 每篇文章都会像单页面一样进行缓存\n\n| 情形 | 加载命令 | 描述 | 文件格式 | 文件名规范 |\n| :-: | :-: | :-: | :-: | :-: |\n| 单文章 | `--lk-html-dump` | 文章内容 | HTML | `<timestamp>.html` |\n| 合集内文章 | 无，但会检查 `dump-path` 内是否存在 | 文章内容 | HTML | `<article-id>.html` |\n\n## 轻之国度 App\n\n### Options\n\n由于没有 URL，所以在这种情况下 url 参数应指定为 `lk-mobile`，并打开需要处理的页面。\n\n```\n  --lk-mobile-top-area-height INTEGER\n                                  (lk mobile) the height of the top area\n  --lk-mobile-bottom-area-height INTEGER\n                                  (lk mobile) the height of the bottom area\n  --lk-mobile-image-equal-threshold INTEGER\n                                  (lk mobile) the threshold of judging whether\n                                  two images are equal\n  --lk-mobile-safe-area-padding INTEGER\n                                  (lk mobile) the padding of the safe area\n  --lk-mobile-vert-dump PATH      (lk mobile) vertical content dump file path\n  --lk-mobile-horz-dump PATH      (lk mobile) horizontal content dump file\n                                  path\n  --lk-mobile-html-dump PATH      (lk mobile) html content dump file path\n  --lk-mobile-conflict-mode BOOLEAN\n                                  (lk mobile) whether to resolve conflict\n                                  manually\n  --lk-mobile-ignore-newline BOOLEAN\n                                  (lk mobile) whether to ignore newline\n```\n\n### Prerequisite\n\n首先，不管是模拟器还是真机，都需要开启 ADB。现在的代码只适用于只有一个 ADB 设备的情况，如果有需求，请自行修改 `provider/lk_mobile.py`。\n\nTODO:\n\n- [ ] 日后为这块增加命令行参数\n\n### Background\n\n对 app 模拟手的滚动操作，同时获取元素，最后生成 epub。\n\n注意到：客户端非常恶心，每一行文本都是一个 View，所以我采用了 Portrait 和 Landscape 扫两遍，然后双指针 Merge 的思路来进行对抗，效果喜人。\n\n![](./assets/text-split.png)\n\n### 界面布局相关参数\n\n* `--lk-mobile-top-area-height`: 设备最顶端到导航栏的高度\n* `--lk-mobile-bottom-area-height`: 设备下方评论栏的高度\n* 上面两个参数默认值为分辨率是 Nox 模拟器 **3840 * 2160** 的情况\n* 其余的可以保持默认，有兴趣可以研究\n\n<div align=\"center\">\n\t<img src=\"./assets/mobile-params.png\" width=300>\n</div>\n\n### 旋转相关\n\n* 最开始进入页面之前屏幕应为 Portrait 状态，命令行会要求用户确认\n* Portrait 扫描完成之后，设备会自动进入 Landscape 状态，但是需要用户退出界面并重新进入，原因是需要 Layout 重新加载。这一步同样会要求用户确认\n* 由于图片的获取是通过截图，所以建议将分辨率调高\n* 由于整个过程耗时长，可能出现意外状况，故有若干 `dump` 命令。`--vert-dump` 可以加载之前操作获取的 Portrait (Vertical) 数据，`--horz-dump` 可以加载之前操作获取的 Landscape (Horizontal) 数据，`--html-dump` 可以加载之前导出的 `html` 数据\n\n![](assets/rotate-quit.png)\n\n### 合并模式相关\n\n`--lk-mobile-new-line` 和 `--lk-mobile-conflict-mode`这两个参数的诞生和排版有着密切的关系。举个简单的例子：\n\n<div align=\"center\">\n这是一前半段没有加粗的文字<b>这是中间加粗的文字</b>这是最后没有加粗的文字\n</div>\n\n如果上面这段话在同一行里，那么会解析成：\n\n```json\n[\n\t\"这是一前半段没有加粗的文字\\n这是中间加粗的文字\\n这是最后没有加粗的文字\"\n]\n```\n\n但是，如果排版变成了：\n\n<div align=\"center\">\n这是一前半段没有加粗的文字<b>这是中间加粗的文字</b><br/>这是最后没有加粗的文字\n</div>\n\n就会解析成：\n\n```json\n[\n\t\"这是一前半段没有加粗的文字\\n这是中间加粗的文字\", \n\t\"这是最后没有加粗的文字\"\n]\n```\n\n可以发现有一个 `\\n` 就这样凭空消失了。这就会导致一个问题：双指针扫描匹配的时候永远无法找到同样的文字内容。为了解决这个问题，我引入了两个方案：\n1. `--lk-mobile-ignore-newline`: 将文中所有出现的 `\\n` 全部忽略，效果很好。但是同时，我们也丧失了知道哪里有排版的机会。\n2. `--lk-mobile-conflict-mode`: 程序最初的版本如果遇到图片但是文字还没有合并，会直接报错。如果加上了 `--lk-mobile-conflict-mode True` 就会在这个情况下让用户选择选择 Landscape 还是 Portrait 的版本。以后可能还会加上让用户手动输入的选项。\n\n### Mumu 模拟器点击位置不正确解决方案\n\nMumu 模拟器点击可能错位，如下图所示：\n\n<div align=\"center\">\n\t<img src=\"./assets/mumu-error.png\" width=300>\n</div>\n\n这种情况下只需在设置中交换长、宽数值即可，让宽大于长。\n\n### 缓存相关\n\n上面已经提到，由于整过过程耗时很长，所以在获取完 Landscape 和 Portrait 数据后会分别写入到文件，两组数据合并完成后也会写入到 Html。\n\n| 情形 | 加载命令 | 描述 | 文件格式 | 文件名规范 |\n| :-: | :-: | :-: | :-: | :-: |\n| 单文章 | `--lk-mobile-vert-dump` | 获取到的 Portrait 数据 | Pickle 二进制数据 | `<timestamp>.out` |\n| 单文章 | `--lk-mobile-horz-dump` | 获取到的 Landscape 数据 | Pickle 二进制数据 | `<timestamp>.out` |\n| 单文章 | `--lk-mobile-html-dump` | 合并后的数据 | HTML | `<timestamp>.html` |\n\n## 轻小说文库\n\n### Options\n\n```\n  --wenku8-volume INTEGER         (wenku8.net) identify the index of the\n                                  volume to generate. -1 means every volume,\n                                  which is also the default option. index\n                                  starts from 1.\n```\n\n### 缓存相关\n\n| 情形 | 加载命令 | 描述 | 文件格式 | 文件名规范 |\n| :-: | :-: | :-: | :-: | :-: |\n| 合集内文章 | 无，但会检查 `dump-path` 内是否存在 | 文章内容 | HTML | `<article-id>.html` |\n\n### 指定卷数\n\n在轻小说文库的总览页面，一般以：卷 => 章 作为导航。而小说生成一般以卷为主。所以我们提供了指定卷数的选项：`--wenku8-volume`，来指定某一卷。若需要一并生成，参数为 -1 或保持默认。\n\n# Known Issues\n\n* 轻之国度\n  * 【已解决，见上】~~对于部分 **先显示无权限观看**，**后可以观看** 的文章无效，以后可能会写浏览器模式~~\n* 轻之国度 App\n  * HTML 排版无法获取\n  * 【已解决】 ~~排版问题可能导致 Lanscape / Portrait 信息无法 Merge，如果遇到这种情况，找到任意一个 Case 的 `dump` 文件 (这里记作 `dump-file`)，并加上命令行参数：`--vert-dump <dump-file> --horz-dump <dump-file>`~~\n\n# TODO\n\n- [x] 图片下载至临时路径\n- [ ] 用 PyQt 写 GUI ~~(基本上是不可能了，完全不想写，而且也没有意义)~~\n- [x] 为漫画提供更好的支持\n- [ ] 增加更多 `metadata` : `tags`, `publisher`, ...\n- [ ] 自动抓取标题\n- [ ] 自动生成目录，~~如果网页上有 headers 的话~~\n- [ ] 添加自定义 CSS / 字体 等支持\n- [x] 简繁自动转换\n- [x] 模拟轻国手机版\n- [ ] 增加移动端截屏图片压缩选项\n- [ ] 目录多重嵌套\n- [ ] 增加移动端 ADB 参数\n\n相关帖子：\n* https://www.v2ex.com/t/800508\n* https://www.lightnovel.us/cn/themereply/1088005\n\n# Contribution\n\n1. 在 `provider` 文件夹中新建文件，最主要实现两个方法：\n   * `get_contents(url, dump_path)` 用来获取信息。返回值可以是 `str` 或 `list`。`list` 内的数据均为 `{'title': title, 'content': content}`\n   * `get_cover(link, dump_path)` 用来获取封面。之所以有这个是因为某些站有特殊的 http header，我不说是谁\n   * 可以额外设计一些 `options`，写明即可\n2. 在 `cli.py` 内接入即可\n\n# LICENSE\n\n* `lightnovel.py`, `cli.py` 使用 AGPL License 授权（`ebooklib` 使用该协议）\n* 项目内的其他文件使用 MIT License 进行授权 \n\n# 技术分析\n\n~~以前写好了舍不得删掉所以再开一个板块，下面基本都是废话~~\n\n## 原理概览\n\n直接抓取 HTML，然后将其中的图片下载至本地，随后打包成 EPUB。\n\nEPUB 内部目录：\n\n```\n.\n├── Images               # 图片\n│   ├── ...\n│   └── ...\n└── Text                 # 文本\n    ├── about.xhtml      # 本项目自动生成\n    └── lightnovel.xhtml # 轻小说正文\n```\n\n对于合集文章：\n\n```\n.\n├── Images               # 图片\n│   ├── ...\n│   └── ...\n└── Text                 # 文本\n    ├── about.xhtml      # 本项目自动生成\n    ├── Section1.xhtml   # P1\n    ├── Section2.xhtml   # P2\n    └── ...\n```\n\nTODO: \n- [ ] 日后可能会支持多重嵌套\n\n## 轻之国度网页版 合集文章\n\n对于合集文章，解析的过程比较有趣，这里讨论一下。\n\n首先是对 HTML 的分析。\n\n![](./assets/series-inspector.png)\n\n很遗憾，并不是 `<a>` 也没有 `href`。去 `Source` 里一看，貌似框架选的是 `Vue`，不熟悉前端，不多做评价。\n\n接着查看 `event`，发现是混淆过的 `js`，放弃逆向。\n\n![](./assets/series-event.png)\n\n经观察，数据应该在文档最后的某个 `<script>` 标签内：\n\n![](./assets/series-script.png)\n\n经过分析，这个 `<script>` 只暴露了一个接口：\n\n```js\nwindow.__NUXT__ = (function(...) { ... }) (...)\n```\n\n故我们只需要 evaluate 这个脚本，然后获取 `window.__NUXT__` 的值即可。\n"
  },
  {
    "path": "cli.py",
    "content": "import click\nimport sys\nimport traceback\nimport os\nimport opencc\n\nfrom lightnovel import LightNovel\nfrom utils import echo\nfrom provider import lk_new\nfrom provider import wenku8\nfrom provider import lk_mobile\n\n\necho.init_subroutine()\n\n\n@click.group()\ndef cli():\n\tpass\n\n\n@cli.command()\n# general options\n@click.option('--dump-path', type=click.Path(), default='./dump', \n\thelp='directory for dumping files and caches')\n@click.option('--title', default=None, \n\thelp='title of light novel')\n@click.option('--authors', default=None, \n\thelp='authors\\' names, separated by comma (,)')\n@click.option('--identifier', default=None, \n\thelp='identifier of light novel')\n@click.option('--cover-link', default=None, \n\thelp='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.')\n@click.option('--cvt', default=None, \n\thelp='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')\n@click.option('--path', type=click.Path(exists=True), default='./', \n\thelp='directory for saving the light novel')\n# lightnovel.us\n@click.option('--lk-html-dump', type=click.Path(exists=True), default=None, \n\thelp='(lightnovel.us) html content dump file path')\n# wenku8.net\n@click.option('--wenku8-volume', default=-1,\n\thelp='(wenku8.net) identify the index of the volume to generate. -1 means every volume, which is also the default option. index starts from 1.')\n# lk mobile\n@click.option('--lk-mobile-top-area-height', default=325, \n\thelp='(lk mobile) the height of the top area')\n@click.option('--lk-mobile-bottom-area-height', default=200, \n\thelp='(lk mobile) the height of the bottom area')\n@click.option('--lk-mobile-image-equal-threshold', default=1, \n\thelp='(lk mobile) the threshold of judging whether two images are equal')\n@click.option('--lk-mobile-safe-area-padding', default=20, \n\thelp='(lk mobile) the padding of the safe area')\n@click.option('--lk-mobile-vert-dump', type=click.Path(exists=True), default=None, \n\thelp='(lk mobile) vertical content dump file path')\n@click.option('--lk-mobile-horz-dump', type=click.Path(exists=True), default=None, \n\thelp='(lk mobile) horizontal content dump file path')\n@click.option('--lk-mobile-html-dump', type=click.Path(exists=True), default=None, \n\thelp='(lk mobile) html content dump file path')\n@click.option('--lk-mobile-conflict-mode', type=bool, default=False, \n\thelp='(lk mobile) whether to resolve conflict manually')\n@click.option('--lk-mobile-ignore-newline', type=bool, default=True, \n\thelp='(lk mobile) whether to ignore newline')\n# general arguments\n@click.argument('url')\ndef download(\n\tdump_path, \n\ttitle: str, \n\tauthors: str, \n\tidentifier: str, \n\tcover_link: str, \n\tcvt: str, \n\tpath: str, \n\tlk_html_dump, \n\twenku8_volume: int, \n\tlk_mobile_top_area_height: int, \n\tlk_mobile_bottom_area_height: int, \n\tlk_mobile_image_equal_threshold: int, \n\tlk_mobile_safe_area_padding: int, \n\tlk_mobile_vert_dump, \n\tlk_mobile_horz_dump,\n\tlk_mobile_html_dump,\n\tlk_mobile_conflict_mode: bool,\n\tlk_mobile_ignore_newline: bool, \n\turl: str):\n\t'''\n\tdownload the light novel\n\n\tARGUMENTS:\n\n\t* URL: url of light novel to download\n\t'''\n\tdef convert_str(content, cvt):\n\t\t# chinese conversion\n\t\tif cvt in [\"s2t\", \"t2s\", \"s2tw\", \"tw2s\", \"s2hk\", \"hk2s\", \"s2twp\", \"tw2sp\", \"t2tw\", \"hk2t\", \"t2hk\", \"t2jp\", \"jp2t\", \"tw2t\"]:\n\t\t\tconverter = opencc.OpenCC(f'{cvt}.json')\n\t\t\treturn converter.convert(content)\n\t\treturn content\n\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\ttry:\n\t\t# init directory\n\t\tif not os.path.exists(dump_path):\n\t\t\tos.mkdir(dump_path)\n\n\t\tif cover_link is None:\n\t\t\tcover_link = input('(Optional) Input cover_link of light novel (see --help for further explanation): ')\n\n\t\tif url.startswith('https://www.lightnovel.us/'):\n\t\t\tcontents = lk_new.get_contents(url, dump_path, lk_html_dump)\n\t\t\tcover_link = lk_new.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link\n\t\telif url.startswith('https://www.wenku8.net/'):\n\t\t\tsource, authors, identifier, title, books, contents = wenku8.get_contents(url, dump_path, wenku8_volume)\n\t\t\tcover_link = wenku8.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link\n\t\telif url == 'lk-mobile':\n\t\t\tcontents = 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)\n\t\t\tcover_link = lk_mobile.get_cover(cover_link, dump_path) if cover_link.startswith('http') else cover_link\n\t\t\turl = '轻之国度 APP'\n\t\telse:\n\t\t\techo.cexit('unsupported url')\n\n\t\tif type(contents) == str:\n\t\t\tcontents = convert_str(contents, cvt)\n\t\telif type(contents) == list:\n\t\t\tfor content in contents:\n\t\t\t\tcontent['title'] = convert_str(content['title'], cvt)\n\t\t\t\tcontent['content'] = convert_str(content['content'], cvt)\n\t\telse:\n\t\t\techo.cexit('CONTENTS MUST BE STRING OR LIST')\n\n\n\t\tTITLE_INPUT_HINT = 'Input title of light novel: '\n\t\tAUTHOR_INPUT_HINT = '(Optional) Input authors\\' names, separated by comma (,): '\n\t\tIDENTIFIER_INPUT_HINT = '(Optional) Input identifier of light novel: '\n\n\t\tdef isempty(instr) -> bool:\n\t\t\tif instr is None:\n\t\t\t\treturn True\n\t\t\tif len(instr) == 0 or str.isspace(instr):\n\t\t\t\treturn True\n\t\t\treturn False\n\t\t\n\t\tif isempty(title):\n\t\t\ttitle = input(TITLE_INPUT_HINT)\n\t\telse:\n\t\t\tuser_title = input(f'Current Title: {title}. (Optional) {TITLE_INPUT_HINT}')\n\t\t\ttitle = title if isempty(user_title) else user_title\n\t\tif isempty(authors):\n\t\t\tauthors = input(AUTHOR_INPUT_HINT)\n\t\telse:\n\t\t\tuser_authors = input(f'Current Authors: {authors}. {AUTHOR_INPUT_HINT}')\n\t\t\tauthors = authors if isempty(user_authors) else user_authors\n\t\tif isempty(identifier):\n\t\t\tidentifier = input(IDENTIFIER_INPUT_HINT)\n\t\telse:\n\t\t\tuser_identifier = input(f'Current identifier: {identifier}. {IDENTIFIER_INPUT_HINT}')\n\t\t\tidentifier = identifier if isempty(user_identifier) else user_identifier\n\n\t\tnovel = LightNovel(source=url, authors=authors.split(','), identifier=identifier, title=title, cover_link=cover_link)\n\t\tnovel.contents = contents\n\t\tnovel.write_epub(path)\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('DOWNLOAD LIGHTNOVEL FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\nif __name__ == '__main__':\n\tcli()\n"
  },
  {
    "path": "gui.py",
    "content": ""
  },
  {
    "path": "lightnovel.py",
    "content": "import os\nimport sys\nimport traceback\nimport base64\nfrom bs4 import BeautifulSoup\nfrom ebooklib import epub\n\nfrom utils import echo\nfrom utils import downloader\nfrom utils.checker import is_not_null, is_null\n\nclass LightNovel():\n\t'''\n\tobject of light novel\n\t'''\n\t\n\tsource = ''\n\t'''\n\tsource of light novel\n\t'''\n\n\tauthors = []\n\t'''\n\tauthor (Optional)\n\t'''\n\t\n\tidentifier = None\n\t'''\n\tidentifier (Optional)\n\t'''\n\n\ttitle = ''\n\t'''\n\ttitle of the book\n\t'''\n\n\tcontents = ''\n\t'''\n\tcan be either str or list\n\tthe format of list is [{'conent': content, 'title': title}]\n\t'''\n\n\tcover_link = None\n\t'''\n\tlink of cover. if `None`, then use the first picture of webpage.\\n\n\tcover_link can either be web link or file path.\\n\n\tif it is not beginned with `http`, it would be recognized as file path.\n\t'''\n\n\tdef __init__(self, source: str, authors=None, identifier=None, title=None, cover_link=None):\n\t\t'''\n\t\tinitialize light novel object\n\t\t'''\n\t\tself.source = source\n\t\tif authors is not None: self.authors = authors\n\t\tif identifier is not None: self.identifier = identifier\n\t\tif title is not None: self.title = title\n\t\tif cover_link is not None: self.cover_link = cover_link\n\n\n\tdef process_image_content(self, content, book):\n\t\t'''\n\t\tprocess image content\n\t\t:param content: HTML content\n\t\t:return: content, first image bytes\n\t\t'''\n\t\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\t\t# parse images\n\t\ttry:\n\t\t\tsoup = BeautifulSoup(content, 'lxml')\n\t\t\timage_tags = soup.find_all('img')\n\t\texcept Exception as e:\n\t\t\techo.cerr(f'Error: {repr(e)}')\n\t\t\ttraceback.print_exc()\n\t\t\techo.cexit('PARSING HTML FAILED')\n\n\t\t# store images\n\t\tfirst_flag = True # flag for storing first image\n\t\tfirst_image = None\n\n\t\ttry:\n\t\t\ti = 0\n\t\t\tfor tag in image_tags:\n\t\t\t\ti = i + 1\n\t\t\t\techo.clog(f'Processing images: ({i} / {len(image_tags)})')\n\t\t\t\t# parse\n\t\t\t\tlink = str(tag.attrs['src'])\n\n\t\t\t\tr_image = None\n\n\t\t\t\tif link.startswith('data:'):\n\t\t\t\t\tr_image = base64.decodebytes(link.split(';')[1].split(',')[1].encode('utf-8'))\n\t\t\t\telse:\n\t\t\t\t\tfile_name = os.path.basename(link)\n\t\t\t\t\tfile_dir = link\n\t\t\t\t\t\n\t\t\t\t\t# convert href\n\t\t\t\t\ttag.attrs['src'] = f'../Images/{file_name}'\n\t\t\t\t\timage = epub.EpubImage()\n\t\t\t\t\timage.file_name = f'Images/{file_name}'\n\t\t\t\t\timage.content = open(file_dir, 'rb').read()\n\t\t\t\t\tbook.add_item(image)\n\t\t\t\t\tr_image = image.content\n\t\t\t\t\n\t\t\t\tif first_flag and r_image is not None:\n\t\t\t\t\tfirst_image = r_image\n\t\t\t\t\tfirst_flag = False\n\t\texcept Exception as e:\n\t\t\techo.cerr(f'Error: {repr(e)}')\n\t\t\ttraceback.print_exc()\n\t\t\techo.cexit('PROCESSING IMAGES FAILED')\n\t\t\n\t\treturn soup, first_image\n\n\n\tdef write_epub(self, path: str):\n\t\t'''\n\t\tgenerate the ebook to `path`\n\t\t'''\n\t\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\t\techo.clog(f'start generating...')\n\n\t\ttry:\n\t\t\t# create epub book\n\t\t\tbook = epub.EpubBook()\n\t\t\t\n\t\t\t# set metadata\n\t\t\tif is_not_null(self.authors):\n\t\t\t\tfor author in self.authors:\n\t\t\t\t\tbook.add_author(author=author)\n\t\t\t\n\t\t\tif is_not_null(self.identifier):\n\t\t\t\tbook.set_identifier(self.identifier)\n\n\t\t\tbook.set_title(self.title)\n\t\t\tbook.set_language('zh-CN')\n\t\texcept Exception as e:\n\t\t\techo.cerr(f'Error: {repr(e)}')\n\t\t\ttraceback.print_exc()\n\t\t\techo.cexit('CREATING EPUB BOOK FAILED')\n\t\t\n\t\tif type(self.contents) == str:\n\t\t\tsoup, first_image = self.process_image_content(self.contents, book)\n\t\telif type(self.contents) == list:\n\t\t\t_contents = []\n\t\t\tfirst_image = None\n\t\t\tfor content in self.contents:\n\t\t\t\tsoup, _first_image = self.process_image_content(content['content'], book)\n\t\t\t\tif first_image is None:\n\t\t\t\t\tfirst_image = _first_image\n\t\t\t\t_contents.append({\n\t\t\t\t\t'content': str(soup),\n\t\t\t\t\t'title': content['title'],\n\t\t\t\t})\n\t\telse:\n\t\t\techo.cexit('CONTENTS MUST BE STRING OR LIST')\n\t\t\n\t\t# set cover\n\t\ttry:\n\t\t\tif is_not_null(self.cover_link):\n\t\t\t\tif os.path.exists(self.cover_link):\n\t\t\t\t\tbook.set_cover(os.path.basename(self.cover_link), open(self.cover_link, 'rb').read())\n\t\t\telif first_image is not None:\n\t\t\t\tbook.set_cover('cover', first_image)\n\t\texcept Exception as e:\n\t\t\techo.cerr(f'Error: {repr(e)}')\n\t\t\ttraceback.print_exc()\n\t\t\techo.cexit('SETTING COVER IMAGE FAILED')\n\t\t\n\t\ttry:\n\t\t\t# set content\n\t\t\tabout_text = f'<p>本书由<a href=\"https://github.com/JeffersonQin/lightnovel_epub\">JeffersonQin/lightnovel_epub</a>工具自动生成。<br>仅供学习交流使用，禁作商业用途。</p><br><p>本书根据 {self.source} 生成</p>'\n\t\t\tif type(self.contents) == str:\n\t\t\t\tabout_content = epub.EpubHtml(title='关于本电子书', file_name='Text/about.xhtml', lang='zh-CN', content=about_text)\n\t\t\t\tmain_content = epub.EpubHtml(title=self.title, file_name='Text/lightnovel.xhtml', lang='zh-CN', content=str(soup))\n\n\t\t\t\tbook.add_item(about_content)\n\t\t\t\tbook.add_item(main_content)\n\n\t\t\t\t# configure book\n\t\t\t\tbook.toc = (about_content, main_content)\n\t\t\t\t# add default NCX and Nav file\n\t\t\t\tbook.add_item(epub.EpubNcx())\n\t\t\t\tbook.add_item(epub.EpubNav())\n\t\t\t\tbook.spine = ['nav', about_content, main_content]\n\t\t\telif type(self.contents) == list:\n\t\t\t\tabout_content = epub.EpubHtml(title='关于本电子书', file_name='Text/about.xhtml', lang='zh-CN', content=about_text)\n\t\t\t\ti = 0\n\t\t\t\tepub_nav = ['nav', about_content]\n\t\t\t\tepub_toc = [about_content]\n\t\t\t\tepub_contents = [about_content]\n\t\t\t\tfor content in _contents:\n\t\t\t\t\ti += 1\n\t\t\t\t\titem = (epub.EpubHtml(title=content['title'], file_name=f'Text/Section{i}.xhtml', lang='zh-CN', content=content['content']))\n\t\t\t\t\tepub_toc.append(item)\n\t\t\t\t\tepub_nav.append(item)\n\t\t\t\t\tepub_contents.append(item)\n\t\t\t\t\n\t\t\t\tfor epub_content in epub_contents:\n\t\t\t\t\tbook.add_item(epub_content)\n\n\t\t\t\t# configure book\n\t\t\t\tbook.toc = tuple(epub_toc)\n\t\t\t\t\n\t\t\t\t# add default NCX and Nav file\n\t\t\t\tbook.add_item(epub.EpubNcx())\n\t\t\t\tbook.add_item(epub.EpubNav())\n\t\t\t\t\n\t\t\t\tbook.spine = epub_nav\n\n\t\t\t# generate book\n\t\t\tepub.write_epub(os.path.join(path, f'{self.title}.epub'), book, {})\n\t\texcept Exception as e:\n\t\t\techo.cerr(f'Error: {repr(e)}')\n\t\t\ttraceback.print_exc()\n\t\t\techo.cexit('BOOK CONFIGURATION & GENERATION FAILED')\n\t\t\n\t\techo.pop_subroutine()\n"
  },
  {
    "path": "provider/lk_mobile.py",
    "content": "import uiautomator2 as u2\nfrom bs4 import BeautifulSoup\nimport cv2\nimport time\nimport numpy as np\nimport sys\nimport pickle\nimport os\nimport traceback\nimport dominate\nfrom utils import echo\nfrom utils import downloader\n\n# define constants\nTOP_AREA_HEIGHT = 325\nBOTTOM_AREA_HEIGHT = 200\nIMAGE_EQUAL_THRESHOLD = 1\nSAFE_AREA_PADDING = 20\nDUMP_PATH = './dump'\n\nd = None\n\n\nclass Image:\n\n\tfilePath: str = None\n\n\tshape = None\n\t\n\tdef __init__(self, filePath, shape):\n\t\tself.filePath = filePath\n\t\tself.shape = shape\n\n\nclass EOF:\n\tdef __init__(self):\n\t\tpass\n\n\ndef rotate2landscape():\n\t\"\"\"\n\trotate screen to landscape\n\t:return: None\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\techo.clog('Rotate screen to landscape.')\n\t\td.set_orientation('l')\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('ROTATE TO LANDSCAPE FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef rotate2portrait():\n\t\"\"\"\n\trotate screen to portrait\n\t:return: None\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\techo.clog('Rotate screen to portrait.')\n\t\td.set_orientation('n')\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('ROTATE TO PORTRAIT FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef take_screenshot():\n\t\"\"\"\n\tTake a screenshot\n\t:return: a numpy array of the screenshot\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\techo.clog('Take a screenshot.')\n\t\tscreenshot = d.screenshot(format='opencv')\n\t\tif (d.info['displayHeight'] - d.info['displayWidth']) * \\\n\t\t\t(screenshot.shape[0] - screenshot.shape[1]) < 0:\n\t\t\tscreenshot = cv2.rotate(screenshot, cv2.ROTATE_90_COUNTERCLOCKWISE)\n\t\treturn screenshot\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('TAKE SCREENSHOT FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_image(x1, y1, x2, y2) -> Image:\n\t\"\"\"\n\tGet image from device screen\n\t:param x1: top left x of image bound\n\t:param y1: top left y of image bound\n\t:param x2: bottom right x of image bound\n\t:param y2: bottom right y of image bound\n\t:return: Image object\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\t# click center of image\n\t\tclick_x = x1 * 0.7 + x2 * 0.3\n\t\tclick_y = (y1 + y2) / 2\n\t\tif click_y > d.info['displayHeight'] - BOTTOM_AREA_HEIGHT or click_y < TOP_AREA_HEIGHT: \n\t\t\tif y1 < TOP_AREA_HEIGHT:\n\t\t\t\tclick_y = (y2 + TOP_AREA_HEIGHT) / 2\n\t\t\telif y2 > d.info['displayHeight'] - BOTTOM_AREA_HEIGHT:\n\t\t\t\tclick_y = (y1 + d.info['displayHeight'] - BOTTOM_AREA_HEIGHT) / 2\n\t\t\telse:\n\t\t\t\traise Exception('Image is not in the visible area')\n\n\t\tclick_x = click_x / d.info['displayWidth']\n\t\tclick_y = click_y / d.info['displayHeight']\n\n\t\ttime.sleep(1)\n\t\techo.clog('Click at:', click_x, click_y)\n\t\td.click(click_x, click_y)\n\t\ttime.sleep(1)\n\t\t# take screenshot\n\t\tscreenshot = take_screenshot()\n\t\t# go back\n\t\techo.clog('Press back.')\n\t\td.press('back')\n\t\t# get ride of navigation bar part of image\n\t\tcropped_image = screenshot[TOP_AREA_HEIGHT:, :, :]\n\t\t# calculate pixel sum of image on vertical direction\n\t\tvert = np.sum(np.sum(cropped_image, axis=2), axis=1)\n\t\t# get black border\n\t\tu = 0\n\t\tfor i in vert:\n\t\t\tif i == 0:\n\t\t\t\tu += 1\n\t\t\telse:\n\t\t\t\tbreak\n\t\tvert = vert[::-1]\n\t\tb = 0\n\t\tfor i in vert:\n\t\t\tif i == 0:\n\t\t\t\tb += 1\n\t\t\telse:\n\t\t\t\tbreak\n\t\t# crop black border out of image\n\t\tif b == 0:\n\t\t\tvert_cropped_image = cropped_image[u:, :, :]\n\t\telse:\n\t\t\tvert_cropped_image = cropped_image[u: -b, :, :]\n\t\t# calculate pixel sum of image on horizontal direction\n\t\thorz = np.sum(np.sum(vert_cropped_image, axis=2), axis=0)\n\t\t# get black border\n\t\tl = 0\n\t\tfor i in horz:\n\t\t\tif i == 0:\n\t\t\t\tl += 1\n\t\t\telse:\n\t\t\t\tbreak\n\t\thorz = horz[::-1]\n\t\tr = 0\n\t\tfor i in horz:\n\t\t\tif i == 0:\n\t\t\t\tr += 1\n\t\t\telse:\n\t\t\t\tbreak\n\t\t# crop black border out of image\n\t\tif r == 0:\n\t\t\thorz_cropped_image = vert_cropped_image[:, l:, :]\n\t\telse:\n\t\t\thorz_cropped_image = vert_cropped_image[:, l: -r, :]\n\t\t# save image\n\t\timage_name = os.path.join(DUMP_PATH, f'./{time.time_ns()}.png')\n\t\tcv2.imwrite(image_name, horz_cropped_image)\n\t\techo.clog(\"Image saved,\", image_name)\n\t\t# return image object\n\t\treturn Image(image_name, horz_cropped_image.shape)\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET IMAGE FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_visible_elements(quick_mode=False):\n\t\"\"\"\n\tGet all visible elements on the screen\n\t:return: a list of visible elements\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tcontents = []\n\t\t# dump hierarchy\n\t\txml = d.dump_hierarchy()\n\t\tsoup = BeautifulSoup(xml, 'lxml')\n\t\t# select contents\n\t\tcontentView = 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)\n\t\tfor child in contentView:\n\t\t\tbounds_str = child.attrs['bounds']\n\t\t\tbounds = bounds_str.split('][')\n\t\t\tx1 = int(bounds[0].split(',')[0][1:])\n\t\t\ty1 = int(bounds[0].split(',')[1])\n\t\t\tx2 = int(bounds[1].split(',')[0])\n\t\t\ty2 = int(bounds[1].split(',')[1][:-1])\n\t\t\t\n\t\t\tif y1 + SAFE_AREA_PADDING > d.info['displayHeight'] - BOTTOM_AREA_HEIGHT \\\n\t\t\t\tor y2 - SAFE_AREA_PADDING < TOP_AREA_HEIGHT:\n\t\t\t\tcontinue\n\t\t\tif child.attrs['class'] == ['android.view.View']:\n\t\t\t\tif child.attrs['content-desc'] == '合集帖子\\n更多' or \\\n\t\t\t\t\tstr(child.attrs['content-desc']).startswith('全部評論'):\n\t\t\t\t\tcontents.append(EOF())\n\t\t\t\t\tbreak\n\t\t\t\tcontents.append(child.attrs['content-desc'])\n\t\t\telif child.attrs['class'] == ['android.widget.ImageView']:\n\t\t\t\tif quick_mode:\n\t\t\t\t\tcontents.append(f'Image-Placeholder-{time.time_ns()}')\n\t\t\t\telse:\n\t\t\t\t\tcontents.append(get_image(x1, y1, x2, y2))\n\t\treturn contents\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET VISIBLE ELEMENTS FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef scroll_to_top():\n\t\"\"\"\n\tscroll the page to the top\n\t:return: None\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tlast_top = None\n\t\twhile True:\n\t\t\td.swipe(0.5, 0.3, 0.5, 0.7, duration=0.1)\n\t\t\tcontents = get_visible_elements(quick_mode=True)\n\t\t\tif contents[0] == last_top:\n\t\t\t\tbreak\n\t\t\tlast_top = contents[0]\n\t\t\techo.clog('Scrolling to top... last_top:', last_top)\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('SCROLL TO TOP FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef compare_content(content1, content2):\n\t\"\"\"\n\tCompare two contents\n\t:param content1: content 1\n\t:param content2: content 2\n\t:return: True if content1 == content2, False otherwise\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tt1 = type(content1)\n\t\tt2 = type(content2)\n\t\tif t1 == str and t2 == str:\n\t\t\treturn content1 == content2\n\t\tif t1 != t2:\n\t\t\treturn False\n\t\tif t1 != Image or t2 != Image:\n\t\t\traise Exception('Unsupported type.')\n\t\timg1 = cv2.imread(content1.filePath)\n\t\timg2 = cv2.imread(content2.filePath)\n\t\t# judge whether shape of two images are same\n\t\tif img1.shape != img2.shape:\n\t\t\treturn False\n\t\t# convert image to gray scale\n\t\timg1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n\t\timg2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n\t\t# calculate diff\n\t\tdiff = cv2.absdiff(img1, img2)\n\t\techo.clog('Image Diff between', content1.filePath, 'and', content2.filePath, \":\", np.average(diff))\n\t\treturn np.average(diff) < IMAGE_EQUAL_THRESHOLD\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('COMPARE CONTENT FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_content():\n\t\"\"\"\n\tscroll the page to the bottom and return the content of the page\n\t:return: the content of the page\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tscroll_to_top()\n\t\ttime.sleep(2)\n\t\techo.clog('Already scrolled to the top')\n\t\tcontents = []\n\t\twhile True:\n\t\t\tvisible_contents = get_visible_elements()\n\n\t\t\tif contents == []:\n\t\t\t\tcontents = visible_contents\n\t\t\t\techo.clog(\"New contents:\", contents)\n\t\t\telse:\n\t\t\t\tcheck_count = min(len(contents), len(visible_contents))\n\t\t\t\t# iterate from check_count to zero\n\t\t\t\toverlap_count = 0\n\t\t\t\tfor i in range(check_count, 0, -1):\n\t\t\t\t\tflag = True\n\t\t\t\t\tfor j in range(i):\n\t\t\t\t\t\tif not compare_content(contents[-(i - j)], visible_contents[j]):\n\t\t\t\t\t\t\tflag = False\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\tif flag:\n\t\t\t\t\t\toverlap_count = i\n\t\t\t\t\t\tbreak\n\t\t\t\tif overlap_count < check_count:\n\t\t\t\t\tnew_contents = visible_contents[overlap_count:]\n\t\t\t\t\techo.clog('New contents:', new_contents)\n\t\t\t\t\tcontents.extend(new_contents)\n\t\t\t\telse:\n\t\t\t\t\techo.clog('Nothing New')\n\t\t\t# scroll down\n\t\t\td.swipe(0.5, 0.7, 0.5, 0.3, duration=0.5)\n\t\t\ttime.sleep(2)\n\t\t\techo.clog('Scrolled down.')\n\t\t\t# check whether the page is at the bottom\n\t\t\tif type(contents[-1]) == EOF:\n\t\t\t\techo.clog('Reached the end of the page.')\n\t\t\t\tbreak\n\t\treturn contents[:-1]\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET CONTENT FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef dump_contents(contents):\n\t\"\"\"\n\tdump the contents to a file\n\t:param contents: the contents to dump\n\t:return: None\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tfile_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.out')\n\t\tpickle.dump(contents, open(file_path, 'wb+'))\n\t\techo.clog('Dumped contents to', file_path)\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('DUMP CONTENT FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef load_contents(file_path):\n\t\"\"\"\n\tload the contents from a file\n\t:param file_path: the file path\n\t:return: the contents\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tcontents = pickle.load(open(file_path, 'rb'))\n\t\techo.clog('Loaded contents from', file_path)\n\t\treturn contents\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('LOAD CONTENT FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_contents(\n\ttop_area_height, \n\tbottom_area_height, \n\timage_equal_threshold, \n\tsafe_area_padding, \n\tdump_path, \n\tvert_dump, \n\thorz_dump,\n\thtml_dump,\n\tconflict_mode: bool,\n\tignore_newline: bool):\n\t\"\"\"\n\tget contents\n\t:param top_area_height: the height of the top area\n\t:param bottom_area_height: the height of the bottom area\n\t:param image_equal_threshold: the threshold of judging whether two images are equal\n\t:param safe_area_padding: the padding of the safe area\n\t:param dump_path: directory for dumping\n\t:param vert_dump: vertical content dump file path\n\t:param horz_dump: horizontal content dump file path\n\t:param html_dump: html content dump file path\n\t:param conflict_mode: whether to resolve conflict manually\n\t:param ignore_newline: whether to ignore newline\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\t\n\tglobal TOP_AREA_HEIGHT\n\tglobal BOTTOM_AREA_HEIGHT\n\tglobal IMAGE_EQUAL_THRESHOLD\n\tglobal SAFE_AREA_PADDING\n\tglobal DUMP_PATH\n\tglobal d\n\tTOP_AREA_HEIGHT = top_area_height\n\tBOTTOM_AREA_HEIGHT = bottom_area_height\n\tIMAGE_EQUAL_THRESHOLD = image_equal_threshold\n\tSAFE_AREA_PADDING = safe_area_padding\n\tDUMP_PATH = dump_path\n\n\ttry:\n\t\td = u2.connect()\n\t\techo.clog('Device Info:', d.info)\n\texcept Exception as e:\n\t\techo.cexit(\"CONNECT TO DEVICE FAILED, PLEASE ENSURE DEVICE IS CONNECTED TO ADB, AND THERE IS ONLY ONE DEVICE\")\n\n\ttry:\n\t\t# init directory\n\t\tif not os.path.exists(dump_path):\n\t\t\tos.mkdir(dump_path)\n\t\tif html_dump is not None:\n\t\t\twith open(html_dump, 'r', encoding='utf-8') as f:\n\t\t\t\thtml_content = f.read()\n\t\telse:\n\t\t\t# load and dump data\n\t\t\tif vert_dump is not None:\n\t\t\t\tvert_contents = load_contents(vert_dump)\n\t\t\t\techo.clog('Loaded vertical contents from', vert_dump)\n\t\t\t\tprint(vert_contents)\n\t\t\telse:\n\t\t\t\trotate2portrait()\n\t\t\t\techo.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 ...')\n\t\t\t\tinput()\n\t\t\t\tvert_contents = get_content()\n\t\t\t\techo.clog('Got vertical contents')\n\t\t\t\tdump_contents(vert_contents)\n\t\t\tif horz_dump is not None:\n\t\t\t\thorz_contents = load_contents(horz_dump)\n\t\t\t\techo.clog('Loaded horizontal contents from', horz_dump)\n\t\t\t\tprint(horz_contents)\n\t\t\telse:\n\t\t\t\trotate2landscape()\t\t\t\n\t\t\t\tprint('==========================')\n\t\t\t\tprint('==========================')\n\t\t\t\techo.clog('Please quit and re-enter the page. Press <Enter> when ready ...')\n\t\t\t\tinput()\n\t\t\t\thorz_contents = get_content()\n\t\t\t\techo.clog('Got horizontal contents')\n\t\t\t\tdump_contents(horz_contents)\n\t\t\t# recalculate typesettings\n\t\t\techo.clog('Recalculating typesettings ...')\n\n\t\t\tif ignore_newline:\n\t\t\t\tfor i in range(len(vert_contents)):\n\t\t\t\t\tif type(vert_contents[i]) == str:\n\t\t\t\t\t\tvert_contents[i] = vert_contents[i].replace('\\n', '')\n\t\t\t\t\t\tvert_contents[i] = vert_contents[i].replace('\\r', '')\n\t\t\t\tfor i in range(len(horz_contents)):\n\t\t\t\t\tif type(horz_contents[i]) == str:\n\t\t\t\t\t\thorz_contents[i] = horz_contents[i].replace('\\n', '')\n\t\t\t\t\t\thorz_contents[i] = horz_contents[i].replace('\\r', '')\n\n\t\t\tvert_ptr = horz_ptr = 0\n\t\t\tnew_contents = []\n\t\t\tvert_str = horz_str = ''\n\t\t\twhile horz_ptr < len(horz_contents):\n\t\t\t\tthis_horz = horz_contents[horz_ptr]\n\t\t\t\tif type(this_horz) == Image:\n\t\t\t\t\tif not horz_str.startswith(vert_str):\n\t\t\t\t\t\tif conflict_mode:\n\t\t\t\t\t\t\twhile not type(vert_contents[vert_ptr]) == Image:\n\t\t\t\t\t\t\t\tthis_vert = vert_contents[vert_ptr]\n\t\t\t\t\t\t\t\tvert_str += this_vert\n\t\t\t\t\t\t\t\tvert_ptr += 1\n\t\t\t\t\t\t\tprint('==========================')\n\t\t\t\t\t\t\techo.cerr('CONFLICT HAPPENED, choose which version to accept:')\n\t\t\t\t\t\t\techo.clog('Portrait (Vertical) Version:', vert_str)\n\t\t\t\t\t\t\techo.clog('Landscape (Horizontal) Version:', horz_str)\n\t\t\t\t\t\t\twhile True:\n\t\t\t\t\t\t\t\tc = input('Enter \"p\" or \"v\" to accept portrait version, \"l\" or \"h\" to accept landscape version, or \"q\" to quit:')\n\t\t\t\t\t\t\t\tif c == 'p' or c == 'v' or c == 'P' or c == 'V':\n\t\t\t\t\t\t\t\t\tnew_contents.append(vert_str)\n\t\t\t\t\t\t\t\t\thorz_str = vert_str = ''\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\telif c == 'l' or c == 'h' or c == 'L' or c == 'H':\n\t\t\t\t\t\t\t\t\tnew_contents.append(horz_str)\n\t\t\t\t\t\t\t\t\thorz_str = vert_str = ''\n\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\telif c == 'q' or c == 'Q':\n\t\t\t\t\t\t\t\t\techo.cexit('USER QUIT')\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\techo.cerr('Invalid input, please try again')\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\techo.cerr('vert content:', vert_str)\n\t\t\t\t\t\t\techo.cerr('horz content:', horz_str)\n\t\t\t\t\t\t\traise Exception('Unexpected content')\n\t\t\t\t\t# string cleaned up\n\t\t\t\t\tif not (horz_str == '' and vert_str == ''):\n\t\t\t\t\t\tnew_contents.append(horz_str)\n\t\t\t\t\t\thorz_str = vert_str = ''\n\t\t\t\t\twhile not type(vert_contents[vert_ptr]) == Image:\n\t\t\t\t\t\tvert_ptr += 1\n\t\t\t\t\t# compare which image is larger\n\t\t\t\t\tthis_vert = vert_contents[vert_ptr]\n\t\t\t\t\tif this_vert.shape[0] * this_vert.shape[1] > \\\n\t\t\t\t\t\tthis_horz.shape[0] * this_horz.shape[1]:\n\t\t\t\t\t\tnew_contents.append(this_vert)\n\t\t\t\t\telse:\n\t\t\t\t\t\tnew_contents.append(this_horz)\n\t\t\t\t\thorz_ptr += 1\n\t\t\t\t\tvert_ptr += 1\n\t\t\t\t\tcontinue\n\t\t\t\telif type(this_horz) == str:\n\t\t\t\t\thorz_str += this_horz\n\t\t\t\t\thorz_ptr += 1\n\n\t\t\t\t\twhile vert_ptr < len(vert_contents) and len(vert_str) < len(horz_str):\n\t\t\t\t\t\tthis_vert = vert_contents[vert_ptr]\n\t\t\t\t\t\tif type(this_vert) != str:\n\t\t\t\t\t\t\tif conflict_mode:\n\t\t\t\t\t\t\t\twhile not type(horz_contents[horz_ptr]) == Image:\n\t\t\t\t\t\t\t\t\tthis_horz = horz_contents[horz_ptr]\n\t\t\t\t\t\t\t\t\thorz_str += this_horz\n\t\t\t\t\t\t\t\t\thorz_ptr += 1\n\t\t\t\t\t\t\t\tprint('==========================')\n\t\t\t\t\t\t\t\techo.cerr('CONFLICT HAPPENED, choose which version to accept:')\n\t\t\t\t\t\t\t\techo.clog('Portrait (Vertical) Version:', vert_str)\n\t\t\t\t\t\t\t\techo.clog('Landscape (Horizontal) Version:', horz_str)\n\t\t\t\t\t\t\t\twhile True:\n\t\t\t\t\t\t\t\t\tc = input('Enter \"p\" or \"v\" to accept portrait version, \"l\" or \"h\" to accept landscape version, or \"q\" to quit:')\n\t\t\t\t\t\t\t\t\tif c == 'p' or c == 'v' or c == 'P' or c == 'V':\n\t\t\t\t\t\t\t\t\t\tnew_contents.append(vert_str)\n\t\t\t\t\t\t\t\t\t\thorz_str = vert_str = ''\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telif c == 'l' or c == 'h' or c == 'L' or c == 'H':\n\t\t\t\t\t\t\t\t\t\tnew_contents.append(horz_str)\n\t\t\t\t\t\t\t\t\t\thorz_str = vert_str = ''\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telif c == 'q' or c == 'Q':\n\t\t\t\t\t\t\t\t\t\techo.cexit('USER QUIT')\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\techo.cerr('Invalid input, please try again')\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\traise Exception('Unexpected content')\n\t\t\t\t\t\tvert_str += this_vert\n\t\t\t\t\t\tvert_ptr += 1\n\n\t\t\t\t\tif conflict_mode and horz_str == '' and vert_str == '':\n\t\t\t\t\t\tcontinue\n\n\t\t\t\t\tif horz_str == vert_str:\n\t\t\t\t\t\tnew_contents.append(horz_str)\n\t\t\t\t\t\thorz_str = vert_str = ''\n\t\t\t\t\t\tcontinue\n\t\t\t\telse:\n\t\t\t\t\traise Exception('Unknown type:', type(this_horz))\n\n\t\t\t# dump_contents(new_contents)\n\n\t\t\tdoc = dominate.document(title='HTML of LK generated by JeffersonQin/lightnovel_epub')\n\n\t\t\twith doc:\n\t\t\t\tfor content in new_contents:\n\t\t\t\t\tif isinstance(content, str):\n\t\t\t\t\t\tdominate.tags.p(content)\n\t\t\t\t\telif isinstance(content, Image):\n\t\t\t\t\t\timg = dominate.tags.img(src=os.path.abspath(content.filePath))\n\t\t\t\t\t\timg.attributes['style'] = 'width: 100%;'\n\t\t\t\t\telse:\n\t\t\t\t\t\traise Exception('Unknown type:', type(content))\n\t\t\thtml_content = doc.render()\n\n\t\t\thtml_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.html')\n\t\t\twith open(html_path, 'w+', encoding='utf-8') as f:\n\t\t\t\tf.write(html_content)\n\t\t\techo.clog('Dumped HTML to', html_path)\n\t\t\n\t\treturn html_content\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('DUMP CONTENT FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_cover(cover_link, dump_path):\n\t'''\n\tGet cover from link.\n\t:param cover_link: link to cover\n\t:param dump_path: path to dump cover\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tcover_name = cover_link.split('?')[0].split('/')[-1]\n\t\tcover_dir = os.path.join(dump_path, cover_name)\n\t\tdownloader.download_file(cover_link, cover_dir, {})\n\t\treturn cover_dir\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET COVER FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n"
  },
  {
    "path": "provider/lk_new.py",
    "content": "import time\nimport sys\nimport traceback\nimport os\nimport requests\nimport js2py\nfrom bs4 import BeautifulSoup\n\nfrom utils import downloader\nfrom utils import echo\n\n\nDUMP_PATH = './dump'\nDOCUMENT_DOWNLOAD_HEADERS = {\n\t'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',\n\t'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',\n\t'cache-control': 'no-cache',\n\t'pragma': 'no-cache',\n\t'sec-ch-ua': '\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"92\"',\n\t'sec-ch-ua-mobile': '?0',\n\t'sec-fetch-dest': 'document',\n\t'sec-fetch-mode': 'navigate',\n\t'sec-fetch-site': 'same-origin',\n\t'sec-fetch-user': '?1',\n\t'upgrade-insecure-requests': '1',\n\t'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'\n}\nIMAGE_DOWNLOAD_HEADERS = {\n\t'accept': 'image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8',\n\t'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',\n\t'cache-control': 'no-cache',\n\t'pragma': 'no-cache',\n\t'referer': 'https://www.lightnovel.us/',\n\t'sec-ch-ua': '\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"92\"',\n\t'sec-ch-ua-mobile': '?0',\n\t'sec-fetch-dest': 'image',\n\t'sec-fetch-mode': 'no-cors',\n\t'sec-fetch-site': 'same-site',\n\t'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',\n}\n\n\ndef process_series_page(url):\n\t'''\n\tProcess the series page.\n\t:param url: url to process\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\tres = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS)\n\t# parse\n\ttry:\n\t\tsoup = BeautifulSoup(res, 'lxml')\n\t\tscripts = soup.find_all('script')\n\n\t\tfor script in scripts:\n\t\t\tif script.string is not None:\n\t\t\t\tif script.string.startswith('window.__NUXT__'):\n\t\t\t\t\tcontext = js2py.EvalJs()\n\t\t\t\t\tcontext.execute(script.string)\n\t\t\t\t\t\n\t\t\t\t\tdata = context.window.__NUXT__.to_dict()\n\t\t\t\t\treturn data['data'][0]['series']['articles']\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('PARSING FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef obtain_article_content(content):\n\t'''\n\tobtain article content\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\t# parse\n\ttry:\n\t\tsoup = BeautifulSoup(content, 'lxml')\n\t\tarticle = soup.find('article', id='article-main-contents')\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('PARSING FAILED')\n\n\techo.pop_subroutine()\n\treturn str(article)\n\n\ndef download_images(content, dump_path):\n\t\"\"\"\n\tdownload images from content\n\t:param content: html content\n\t:param dump_path: path to dump updated html\n\t:return:\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\t\n\techo.clog(f'Start Parsing Images')\n\n\t# parse images\n\ttry:\n\t\tsoup = BeautifulSoup(content, 'lxml')\n\t\timages = soup.find_all('img')\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('PARSING FAILED')\n\t# download images\n\ttry:\n\t\ti = 0\n\t\tfor tag in images:\n\t\t\ti += 1\n\t\t\techo.clog(f'Processing images: ({i} / {len(images)})')\n\t\t\t# parse\n\t\t\tlink = str(tag.attrs['src'])\n\t\t\tif link.startswith('http') or link.startswith('//'):\n\t\t\t\tfile_name = link.split('?')[0].split('/')[-1]\n\t\t\t\tfile_dir = os.path.join(DUMP_PATH, file_name)\n\t\t\t\t# download\n\t\t\t\tdownloader.download_file(link, file_dir, IMAGE_DOWNLOAD_HEADERS)\n\t\t\t\t# replace src\n\t\t\t\ttag.attrs['src'] = os.path.abspath(file_dir)\n\t\t\t\t# update html\n\t\t\t\twith open(dump_path, 'w', encoding='utf-8') as f:\n\t\t\t\t\tf.write(str(soup))\n\t\treturn str(soup)\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('DOWNLOAD FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef process_article_page(url, dump_path):\n\t'''\n\tProcess the article page.\n\t:param url: url to process\n\t:param dump_path: path to dump html\n\t:return: string of html content\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\ttry:\n\t\tflag = True\n\t\t# obtain html\n\t\tif dump_path is not None:\n\t\t\tif os.path.exists(dump_path):\n\t\t\t\twith open(dump_path, 'r', encoding='utf-8') as f:\n\t\t\t\t\tcontent = f.read()\n\t\t\t\tflag = False\n\t\tif flag:\n\t\t\tcontent = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS)\n\n\t\tcontent = obtain_article_content(content)\n\n\t\tif flag:\n\t\t\tif dump_path is None:\n\t\t\t\tdump_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.html')\n\t\t\twith open(dump_path, 'w', encoding='utf-8') as f:\n\t\t\t\tf.write(content)\n\t\t\techo.clog(f'Dumped HTML to {dump_path}')\n\t\t# download images\n\t\tcontent = download_images(content, dump_path)\n\n\t\treturn content\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('PROCESS PAGE FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_contents(url, dump_path, html_dump):\n\t'''\n\tGet contents from url.\n\t:param url: url to process\n\t:param dump_path: path to dump things\n\t:param html_dump: html dump path\n\t'''\n\tglobal DUMP_PATH\n\tDUMP_PATH = dump_path\n\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tif 'series' in url:\n\t\t\tcontents = []\n\t\t\t# series\n\t\t\tarticles = process_series_page(url)\n\t\t\ti = 0\n\t\t\tfor article in articles:\n\t\t\t\ti += 1\n\t\t\t\techo.clog(f'Processing article {i} / {len(articles)}')\n\t\t\t\ta_title = article[\"title\"]\n\t\t\t\taid = article[\"aid\"]\n\t\t\t\techo.clog(f'Title: {a_title}')\n\t\t\t\techo.clog(f'Article ID: {aid}')\n\t\t\t\ta_url = f'https://www.lightnovel.us/cn/detail/{aid}/'\n\t\t\t\ta_dump_path = os.path.join(dump_path, f'{aid}.html')\n\t\t\t\ta_content = process_article_page(a_url, a_dump_path)\n\t\t\t\tcontents.append({\n\t\t\t\t\t'title': a_title,\n\t\t\t\t\t'content': a_content\n\t\t\t\t})\n\t\telse:\n\t\t\t# article\n\t\t\tcontents = process_article_page(url, html_dump)\n\t\t\n\t\treturn contents\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET CONTENTS FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_cover(cover_link, dump_path):\n\t'''\n\tGet cover from link.\n\t:param cover_link: link to cover\n\t:param dump_path: path to dump cover\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tcover_name = cover_link.split('?')[0].split('/')[-1]\n\t\tcover_dir = os.path.join(dump_path, cover_name)\n\t\tdownloader.download_file(cover_link, cover_dir, IMAGE_DOWNLOAD_HEADERS)\n\t\treturn cover_dir\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET COVER FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n"
  },
  {
    "path": "provider/wenku8.py",
    "content": "from __future__ import annotations\nimport time\nimport sys\nimport traceback\nimport os\nimport re\nfrom bs4 import BeautifulSoup\n\nfrom utils import downloader\nfrom utils import echo\n\n\nDOCUMENT_DOWNLOAD_HEADERS = {\n    'accept':\n    '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',\n    'Content-Type': 'text/html; charset=unicode',\n    'accept-language':\n    'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',\n    'cache-control':\n    'no-cache',\n    'pragma':\n    'no-cache',\n    'sec-ch-ua':\n    '\"Chromium\";v=\"92\", \" Not A;Brand\";v=\"99\", \"Microsoft Edge\";v=\"92\"',\n    'sec-ch-ua-mobile':\n    '?0',\n    'sec-fetch-dest':\n    'document',\n    'sec-fetch-mode':\n    'navigate',\n    'sec-fetch-site':\n    'same-origin',\n    'sec-fetch-user':\n    '?1',\n    'upgrade-insecure-requests':\n    '1',\n    'user-agent':\n    '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'\n}\n\nIMAGE_DOWNLOAD_HEADERS = {\n    'Accept':\n    'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',\n    'Accept-Language':\n    'zh-CN,zh;q=0.9,en;q=0.8',\n    'Host':\n    'pic.wenku8.com',\n    'Proxy-Connection':\n    'keep-alive',\n    'User-Agent':\n    'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',\n}\n\nDECODE = 'gbk'\nENCODE = 'utf-8'\n\nclass BookInfo:\n\tdef __init__(self, aid, cid, title, content=None, href=None) -> None:\n\t\tself.aid: str = aid\n\t\tself.cid: str = cid\n\t\tself.title: str = title\n\t\tself.content: str = content\n\t\tself.href: str = href\n\n\ndef obtain_article_content(url):\n\t'''\n\tdownload web content\n\t:param url: url to download\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\tres = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS, DECODE)\n\t# parse\n\ttry:\n\t\tsoup = BeautifulSoup(res, 'lxml')\n\t\tarticle = soup.find('article', id='article-main-contents')\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('PARSING FAILED')\n\n\techo.pop_subroutine()\n\treturn str(article)\n\n\ndef download_images(content, dump_path):\n\t\"\"\"\n\tdownload images from content\n\t:param content: html content\n\t:param dump_path: path to dump updated html\n\t:return:\n\t\"\"\"\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\techo.clog(f'Start Parsing Images')\n\n\t# parse images\n\ttry:\n\t\tsoup = BeautifulSoup(content, 'lxml')\n\t\timages = soup.find_all('img')\n\texcept Exception as e:\n\t\techo.cerr(f'Error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('PARSING FAILED')\n\t# download images\n\ttry:\n\t\ti = 0\n\t\tfor tag in images:\n\t\t\ti += 1\n\t\t\techo.clog(f'Processing images: ({i} / {len(images)})')\n\t\t\t# parse\n\t\t\tlink = str(tag.attrs['src'])\n\t\t\tif link.startswith('http') or link.startswith('//'):\n\t\t\t\tfile_name = link.split('?')[0].split('/')[-1]\n\t\t\t\tfile_dir = os.path.join(DUMP_PATH, file_name)\n\t\t\t\t# download\n\t\t\t\tdownloader.download_file(link, file_dir, IMAGE_DOWNLOAD_HEADERS)\n\t\t\t\t# replace src\n\t\t\t\ttag.attrs['src'] = os.path.abspath(file_dir)\n\t\t\t\t# update html\n\t\t\t\twith open(dump_path, 'w', encoding=ENCODE) as f:\n\t\t\t\t\tf.write(str(soup))\n\t\treturn str(soup)\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('DOWNLOAD FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\ndef process_article_page(url, dump_path, cvt=None):\n    '''\n        Process the article page.\n        :param url: url to process\n        :param dump_path: path to dump html\n        :return: string of html content\n        '''\n    echo.push_subroutine(sys._getframe().f_code.co_name)\n\n    try:\n        flag = True\n        # obtain html\n        if dump_path is not None:\n            if os.path.exists(dump_path):\n                with open(dump_path, 'r', encoding=ENCODE) as f:\n                    content = f.read()\n                flag = False\n        if flag:\n            content = obtain_article_content(url)\n            if dump_path is None:\n                dump_path = os.path.join(DUMP_PATH, f'./{time.time_ns()}.html')\n            with open(dump_path, 'w', encoding=ENCODE) as f:\n                f.write(content)\n            echo.clog(f'Dumped HTML to {dump_path}')\n        # download images\n        content = download_images(content, dump_path)\n\n        return content\n    except Exception as e:\n        echo.cerr(f'error: {repr(e)}')\n        traceback.print_exc()\n        echo.cexit('PROCESS PAGE FAILED')\n    finally:\n        echo.pop_subroutine()\n\ndef getBookStructure(source: str, content: str):\n\tsoup = BeautifulSoup(content, 'lxml')\n\ttitle = soup.find(id='title').text\n\tauthor = soup.find(id='info').text.replace('作者：', '')\n\ttable = soup.find('table')\n\tunits = table.find_all('td')\n\tbookId = re.search(r'var article_id = \"(\\S+)\"', content)[1]\n\tbooks = {}\n\tcurBook = None\n\tfor unit in units:\n\t\t# print(unit.prettify())\n\t\tcl = unit.get('class')[0]\n\t\tif cl == 'vcss':\n\t\t\tcurBook = unit.text\n\t\t\tbooks[curBook] = []\n\t\telif cl == 'ccss':\n\t\t\tatag = unit.find('a')\n\t\t\tif atag is None:\n\t\t\t\tcontinue\n\t\t\taid = re.search(r'var article_id = \"(\\S+)\"', content)[1]\n\t\t\tcid = re.search(r'var chapter_id = \"(\\S+)\"', content)[1]\n\t\t\tcurChapter = BookInfo(aid,\n\t\t\t\t\t\tcid,\n\t\t\t\t\t\thref=atag.attrs['href'],\n\t\t\t\t\t\ttitle=atag.text)\n\t\t\tif curBook not in books:\n\t\t\t\techo.cexit(f'No current book specified: {curChapter}')\n\t\t\tbooks[curBook].append(curChapter)\n\treturn (source, author, bookId, title, books)\n\n\ndef getContent(content: str) -> BookInfo:\n\taid = re.search(r'var article_id = \"(\\S+)\"', content)[1]\n\tcid = re.search(r'var chapter_id = \"(\\S+)\"', content)[1]\n\tsoup = BeautifulSoup(content, 'lxml')\n\ttitle = soup.find('div', id='title').text\n\tcontent = soup.find('div', id='contentmain').prettify()\n\treturn BookInfo(aid, cid, title, content)\n\ndef get_contents(url, dump_path, volume_index):\n\t'''\n\tGet contents from url.\n\t:param url: url to process\n\t:param dump_path: path to dump things\n\t:param volume_index: index of volume to generate\n\t:returns: LightNovel class\n\t'''\n\tglobal DUMP_PATH\n\tDUMP_PATH = dump_path\n\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\ttry:\n\t\tassert ('novel' in url) and ('index.htm' in url), 'not wenku8 novel toc page'\n\t\trelative = url.replace('index.htm', '')\n\t\tcontent = downloader.download_webpage(url, DOCUMENT_DOWNLOAD_HEADERS, DECODE)\n\t\t(source, author, bookId, title, books) = getBookStructure(url, content)\n\t\tcontents = []\n\t\tbook_titles = books.keys()\n\t\tvolume_count = len(book_titles)\n\n\t\tif volume_index > volume_count:\n\t\t\techo.cexit(\"ERROR: VOLUME INDEX OUT OF RANGE, TOTAL VOLUME:\", volume_count)\n\n\t\t# series\n\t\tcur_volume_index = 0\n\t\tfor book_title in book_titles:\n\t\t\tcur_volume_index += 1\n\t\t\techo.clog(f'Processing volume {book_title} {cur_volume_index} / {volume_count}')\n\n\t\t\tif volume_index != -1 and volume_index != cur_volume_index: continue\n\n\t\t\tch_index = 0\n\t\t\tfor chapter in books[book_title]:\n\t\t\t\taddr = relative + '/' + chapter.href\n\t\t\t\tchWeb = downloader.download_webpage(addr, DOCUMENT_DOWNLOAD_HEADERS, DECODE)\n\t\t\t\tchContent = getContent(chWeb)\n\t\t\t\ta_title = chContent.title\n\t\t\t\taid = chContent.cid\n\n\t\t\t\tch_index += 1\n\t\t\t\techo.clog(f'Processing chapter {ch_index} / {len(books[book_title])}')\n\t\t\t\techo.clog(f'Title: {a_title}')\n\t\t\t\techo.clog(f'Article ID: {aid}')\n\n\t\t\t\ta_dump_path = os.path.join(dump_path, f'{aid}.html')\n\t\t\t\twith open(a_dump_path, 'w', encoding=ENCODE) as f:\n\t\t\t\t\techo.clog(f'Save content to {a_dump_path}')\n\t\t\t\t\tf.write(chContent.content)\n\t\t\t\t# to call download images\n\t\t\t\timg_content = process_article_page(None, a_dump_path)\n\t\t\t\tcontents.append({'title': a_title, 'content': img_content})\n\n\t\treturn source, author, bookId, title, books, contents\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET CONTENTS FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef get_cover(cover_link, dump_path):\n\t'''\n\tGet cover from link.\n\t:param cover_link: link to cover\n\t:param dump_path: path to dump cover\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\ttry:\n\t\tcover_name = cover_link.split('?')[0].split('/')[-1]\n\t\tcover_dir = os.path.join(dump_path, cover_name)\n\t\tdownloader.download_file(cover_link, cover_dir, IMAGE_DOWNLOAD_HEADERS)\n\t\treturn cover_dir\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\techo.cexit('GET COVER FAILED')\n\tfinally:\n\t\techo.pop_subroutine()\n"
  },
  {
    "path": "utils/checker.py",
    "content": "\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 == \"\":\n\t\treturn True\n\treturn False\n\ndef is_not_null(data):\n\treturn not is_null(data)\n"
  },
  {
    "path": "utils/downloader.py",
    "content": "import sys\nimport requests\nimport os\nimport unicodedata\nimport re\nimport click\nimport traceback\n\nfrom utils import echo\n\ndef _download_file(url, dir, headers):\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\techo.clog(f'start downloading: {url} => {dir}')\n\tret = 0\n\ttry:\n\t\t# start and block request\n\t\tr = requests.get(url, stream=True, headers=headers, timeout=3000)\n\t\t# obtain content length\n\t\tlength = int(r.headers['content-length'])\n\t\techo.clog(f'file size: {size_description(length)}')\n\t\tTHRESHOLD = 32\n\t\tif os.path.exists(dir) and abs(os.path.getsize(dir) - length) < THRESHOLD:\n\t\t\techo.clog(f'file already exists {dir}')\n\t\telse:\n\t\t\t# start writing\n\t\t\tf = open(dir, 'wb+')\n\t\t\t# show in progressbar\n\t\t\twith click.progressbar(label=\"Downloading from remote: \", length=length) as bar:\n\t\t\t\tfor chunk in r.iter_content(chunk_size = 512):\n\t\t\t\t\tif chunk:\n\t\t\t\t\t\tf.write(chunk)\n\t\t\t\t\t\tbar.update(len(chunk))\n\t\t\techo.csuccess('Download Complete.')\n\t\t\tf.close()\n\texcept Exception as err:\n\t\techo.cerr(f'Error: {repr(err)}')\n\t\ttraceback.print_exc()\n\t\tret = 1\n\tfinally:\n\t\techo.pop_subroutine()\n\t\treturn ret\n\n\ndef download_file(url, dir, headers, trial=5):\n\tfail_count = 0\n\twhile True:\n\t\tret = _download_file(url, dir, headers)\n\t\tif ret == 0:\n\t\t\treturn\n\t\tif fail_count < trial:\n\t\t\tfail_count += 1\n\t\t\techo.cerr(f'Download failed, Trial {fail_count}/{trial}')\n\t\telse:\n\t\t\techo.cexit('Download failed. Exceeded trial limit.')\n\n\ndef _download_webpage(url, headers, encoding):\n\t'''\n\tDownload webpage from url.\n\t:param url: url to download\n\t'''\n\techo.push_subroutine(sys._getframe().f_code.co_name)\n\n\techo.clog(f'start downloading: {url} => memory')\n\t# download\n\ttry:\n\t\treturn requests.get(url=url, headers=headers).content.decode(encoding)\n\texcept Exception as e:\n\t\techo.cerr(f'error: {repr(e)}')\n\t\ttraceback.print_exc()\n\t\treturn -1\n\tfinally:\n\t\techo.pop_subroutine()\n\n\ndef download_webpage(url, headers, encoding='utf-8', trial=5):\n\t'''\n\tDownload webpage from url.\n\t:param url: url to download\n\t:param trial: number of trials\n\t'''\n\tfail_count = 0\n\twhile True:\n\t\tret = _download_webpage(url, headers, encoding)\n\t\tif ret != -1:\n\t\t\treturn ret\n\t\tif fail_count < trial:\n\t\t\tfail_count += 1\n\t\t\techo.cerr(f'Download failed, Trial {fail_count}/{trial}')\n\t\telse:\n\t\t\techo.cexit('Download failed. Exceeded trial limit.')\n\n\ndef size_description(size):\n\t'''\n\tTaken and modified from https://blog.csdn.net/wskzgz/article/details/99293181\n\t'''\n\tdef strofsize(integer, remainder, level):\n\t\tif integer >= 1024:\n\t\t\tremainder = integer % 1024\n\t\t\tinteger //= 1024\n\t\t\tlevel += 1\n\t\t\treturn strofsize(integer, remainder, level)\n\t\telse:\n\t\t\treturn integer, remainder, level\n\n\tunits = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']\n\tinteger, remainder, level = strofsize(size, 0, 0)\n\tif level + 1 > len(units):\n\t\tlevel = -1\n\treturn ( '{}.{:>03d} {}'.format(integer, remainder, units[level]) )\n"
  },
  {
    "path": "utils/echo.py",
    "content": "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_subroutine(cmd_name: str):\r\n\tglobal subroutine_stack\r\n\tsubroutine_stack.append(cmd_name)\r\n\r\n\r\ndef pop_subroutine():\r\n\tglobal subroutine_stack\r\n\tlast = subroutine_stack[-1]\r\n\tsubroutine_stack = subroutine_stack[:-1]\r\n\treturn last\r\n\r\n\r\ndef get_subroutine():\r\n\treturn subroutine_stack[-1]\r\n\r\n\r\ndef _clog(message: str):\r\n\tclick.echo(click.style(f\"[{get_subroutine()}]\", bg='magenta', fg='white'), nl=False)\r\n\tclick.echo(message)\r\n\r\n\r\ndef clog(*messages):\r\n\tval = ''\r\n\tfor message in messages:\r\n\t\tval = val + ' ' + str(message)\r\n\t_clog(val)\r\n\r\n\r\ndef _cerr(message: str):\r\n\tclick.echo(click.style(f\"[{get_subroutine()}]\", bg='magenta', fg='white'), nl=False)\r\n\tclick.echo(click.style(f\" {message}\", fg = 'bright_red'))\r\n\r\n\r\ndef cerr(*messages):\r\n\tval = ''\r\n\tfor message in messages:\r\n\t\tval = val + ' ' + str(message)\r\n\t_cerr(val)\r\n\r\n\r\ndef _csuccess(message: str):\r\n\tclick.echo(click.style(f\"[{get_subroutine()}]\", bg='magenta', fg='white'), nl=False)\r\n\tclick.echo(click.style(f\" {message}\", fg = 'green'))\r\n\r\n\r\ndef csuccess(*messages):\r\n\tval = ''\r\n\tfor message in messages:\r\n\t\tval = val + ' ' + str(message)\r\n\t_csuccess(val)\r\n\r\n\r\ndef _cexit(message: str):\r\n\tcerr(f'{message}, exiting program.')\r\n\tsys.exit(1)\r\n\r\n\r\ndef cexit(*messages):\r\n\tval = ''\r\n\tfor message in messages:\r\n\t\tval = val + ' ' + str(message)\r\n\t_cexit(val)\r\n"
  }
]