commit fa9294b1d8c3fc87d76a4b9c5f1b28d4f575e75a Author: lifegpc Date: Fri May 19 11:57:36 2023 +0800 Upload files diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..11c55d8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.vscode/ +config.json +test/ +downloads/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/client.ts b/client.ts new file mode 100644 index 0000000..cf310ef --- /dev/null +++ b/client.ts @@ -0,0 +1,125 @@ +import { Config } from "./config.ts"; +import { load_gallery_metadata } from "./page/GalleryMetadata.ts"; +import { load_gallery_page } from "./page/GalleryPage.ts"; +import { load_single_page } from "./page/SinglePage.ts"; + +export type GID = [number, string]; + +export class Client { + cookies; + host; + ua; + constructor(cfg: Config) { + this.cookies = cfg.cookies; + this.ua = cfg.ua || + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36"; + this.host = cfg.ex ? "exhentai.org" : "e-hentai.org"; + } + get( + url: string | Request | URL, + options: RequestInit | undefined = undefined, + ) { + return this.request(url, "GET", options); + } + post( + url: string | Request | URL, + options: RequestInit | undefined = undefined, + ) { + return this.request(url, "POST", options); + } + request( + url: string | Request | URL, + method: string | undefined = undefined, + options: RequestInit | undefined = undefined, + ) { + const headers = new Headers(); + headers.set("User-Agent", this.ua); + if (this.cookies) { + if (typeof url === "string") { + const u = new URL(url); + if ( + u.hostname == "e-hentai.org" || u.hostname == "exhentai.org" + ) { + headers.set("Cookie", this.cookies); + } + } else if (url instanceof Request) { + const u = new URL(url.url); + if ( + u.hostname == "e-hentai.org" || u.hostname == "exhentai.org" + ) { + headers.set("Cookie", this.cookies); + } + } else if (url instanceof URL) { + if ( + url.hostname == "e-hentai.org" || + url.hostname == "exhentai.org" + ) { + headers.set("Cookie", this.cookies); + } + } + } + if (url instanceof Request) { + for (const v of headers) { + url.headers.set(v[0], v[1]); + } + return fetch(url); + } else { + return fetch( + url, + Object.assign({ headers, method: method || "GET" }, options), + ); + } + } + /** + * Fetch a single page (use HTML) + * @param gid Gallery ID + * @param page_token Page token + * @param index Page index + * @returns + */ + async fetchSignlePage(gid: number, page_token: string, index: number) { + const url = `https://${this.host}/s/${page_token}/${gid}-${index}`; + const re = await this.get(url); + if (re.status != 200) { + throw new Error( + `Fetch ${url} failed, status ${re.status} ${re.statusText}`, + ); + } + return load_single_page(await re.text(), this); + } + /** + * Fetch metadata via API + * @param gids A list of Gallery ID and token + * @returns + */ + async fetchGalleryMetadataByAPI(...gids: GID[]) { + if (gids.length > 25) throw Error("Load limiting is reached."); + const data = { method: "gdata", gidlist: gids, namespace: 1 }; + const re = await this.post(`https://${this.host}/api.php`, { + body: JSON.stringify(data), + headers: { "content-type": "application/json" }, + }); + if (re.status != 200) { + throw new Error( + `Fetch api.php failed, status ${re.status} ${re.statusText}`, + ); + } + return load_gallery_metadata(await re.text()); + } + /** + * Fetch a gallery page (use HTML) + * @param gid Gallery ID + * @param token Token + * @returns + */ + async fetchGalleryPage(gid: number, token: string) { + const url = `https://${this.host}/g/${gid}/${token}/`; + const re = await this.get(url); + if (re.status != 200) { + throw new Error( + `Fetch ${url} failed, status ${re.status} ${re.statusText}`, + ); + } + return load_gallery_page(await re.text(), this); + } +} diff --git a/config.ts b/config.ts new file mode 100644 index 0000000..e39faad --- /dev/null +++ b/config.ts @@ -0,0 +1,59 @@ +export class Config { + _data; + constructor(data: { [x: string]: unknown }) { + this._data = Object.assign({}, data); + } + _return_string(key: string) { + const v = this._data[key]; + if (v === undefined || typeof v === "string") { + return v; + } + throw new Error(`Config ${key} value ${v} is not a string`); + } + _return_number(key: string) { + const v = this._data[key]; + if (v === undefined) return undefined; + if (typeof v === "number") { + return v; + } + throw new Error(`Config ${key} value ${v} is not a number`); + } + _return_bool(key: string) { + const v = this._data[key]; + if (v === undefined) { + return v; + } + if (typeof v === "boolean") { + return v; + } else if (typeof v === "string") { + if (v === "true") { + return true; + } else if (v === "false") { + return false; + } + } else if (typeof v === "number") { + return v != 0; + } + throw new Error(`Config ${key} value ${v} is not a boolean`); + } + get cookies() { + return this._return_string("cookies"); + } + get ua() { + return this._return_string("ua"); + } + get ex() { + return this._return_bool("ex") || false; + } + get base() { + return this._return_string("base") || "./downloads"; + } + get max_task_count() { + return this._return_number("max_task_count") || 1; + } +} + +export async function load_settings(path: string) { + const s = (new TextDecoder()).decode(await Deno.readFile(path)); + return new Config(JSON.parse(s)); +} diff --git a/db.ts b/db.ts new file mode 100644 index 0000000..737d49c --- /dev/null +++ b/db.ts @@ -0,0 +1,224 @@ +const { DB } = await import("https://deno.land/x/sqlite@v3.7.2/mod.ts"); +import { SemVer } from "https://deno.land/std@0.188.0/semver/mod.ts"; +import { join } from "https://deno.land/std@0.188.0/path/mod.ts"; +import { SqliteError } from "https://deno.land/x/sqlite@v3.7.2/mod.ts"; +import { Status } from "https://deno.land/x/sqlite@v3.7.2/src/constants.ts"; +import { sleep } from "./utils.ts"; +import { Task, TaskType } from "./task.ts"; + +type SqliteMaster = { + type: string; + name: string; + tbl_name: string; + rootpage: number; + sql: string; +}; +export enum SqliteTransactionType { + DEFERRED = "DEFERRED", + IMMEDIATE = "IMMEDIATE", + EXCLUSIVE = "EXCLUSIVE", +} +const ALL_TABLES = ["version"]; +const VERSION_TABLE = `CREATE TABLE version ( + id TEXT, + ver TEXT, + PRIMARY KEY (id) +);`; +const TASK_TABLE = `CREATE TABLE task ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + type INT, + gid INT, + token TEXT, + pn INT, + pid INT +);`; + +export class EhDb { + db; + flock_enabled: boolean = eval('typeof Deno.flock !== "undefined"'); + file: Deno.FsFile | undefined; + _exist_table: Set = new Set(); + readonly version = new SemVer("1.0.0-0"); + constructor(base_path: string) { + this.db = new DB(join(base_path, "data.db")); + this.db.execute("PRAGMA main.locking_mode=EXCLUSIVE;"); + if (!this._check_database()) this._create_table(); + if (this.flock_enabled) { + this.file = Deno.openSync(join(base_path, "db.lock"), { + create: true, + write: true, + }); + } else { + console.log( + "%cFile locking is disabled. Use --unstable to enable file locking.", + "color: yellow;", + ); + } + } + _check_database() { + this._updateExistsTable(); + const v = this._read_version(); + if (!v) return false; + if ( + ALL_TABLES.length !== this._exist_table.size || + !ALL_TABLES.every((x) => this._exist_table.has(x)) + ) return false; + return true; + } + _create_table() { + if (!this._exist_table.has("version")) { + this.db.execute(VERSION_TABLE); + this._write_version(); + } + if (!this._exist_table.has("task")) { + this.db.execute(TASK_TABLE); + } + this._updateExistsTable(); + } + _read_version() { + if (!this._exist_table.has("version")) return null; + const cur = this.db.query<[string]>( + "SELECT ver FROM version WHERE id = ?;", + ["eh"], + ); + for (const i of cur) { + return new SemVer(i[0]); + } + return null; + } + _updateExistsTable() { + const cur = this.db.queryEntries( + "SELECT * FROM main.sqlite_master;", + ); + this._exist_table.clear(); + for (const i of cur) { + if (i.type == "table") { + this._exist_table.add(i.name); + } + } + } + _write_version() { + this.db.transaction(() => { + this.db.query("INSERT OR REPLACE INTO version VALUES (?, ?);", [ + "eh", + this.version.toString(), + ]); + }); + } + add_task(task: Task) { + return this.transaction(() => { + this.db.query( + "INSERT INTO task (type, gid, token, pn, pid) VALUES (?, ?, ?, ?, ?);", + [task.type, task.gid, task.token, task.pn, task.pid], + ); + return this.db.queryEntries( + "SELECT * FROM task WHERE type = ? AND gid = ? AND token = ? AND pn = ? AND pid = ?;", + [task.type, task.gid, task.token, task.pn, task.pid], + )[0]; + }); + } + begin(type: SqliteTransactionType) { + try { + this.db.execute(`BEGIN ${type} TRANSACTION;`); + return true; + } catch (e) { + if (e instanceof SqliteError) { + if (e.code == Status.SqliteBusy) return false; + } + throw e; + } + } + check_download_task(gid: number, token: string) { + return this.transaction(() => { + const r = this.db.queryEntries( + "SELECT * FROM task WHERE type = ? AND gid = ? AND token = ?;", + [TaskType.Download, gid, token], + ); + return r.length ? r[0] : undefined; + }); + } + close() { + this.db.close(); + if (this.file) this.file.close(); + } + async commit() { + while (1) { + try { + this.db.execute("COMMIT TRANSACTION;"); + break; + } catch (e) { + if (e instanceof SqliteError) { + if (e.code == Status.SqliteBusy) { + await sleep(1000); + continue; + } + } + throw e; + } + } + } + delete_task(task: Task) { + return this.transaction(() => { + this.db.query("DELETE FROM task WHERE id = ?;", [task.id]); + }); + } + async flock() { + if (!this.file) return; + await eval(`Deno.flock(${this.file.rid}, true);`); + } + async funlock() { + if (!this.file) return; + await eval(`Deno.funlock(${this.file.rid});`); + } + get_tasks_by_pid(pid: number) { + return this.transaction(() => + this.db.queryEntries("SELECT * FROM task WHERE pid = ?;", [ + pid, + ]) + ); + } + get_other_pid_tasks() { + return this.transaction(() => + this.db.queryEntries("SELECT * FROM task WHERE pid != ?;", [ + Deno.pid, + ]) + ); + } + rollback() { + this.db.execute("ROLLBACK TRANSACTION;"); + } + set_task_pid(task: Task) { + return this.transaction(() => { + const t = this.db.queryEntries( + "SELECT * FROM task WHERE id = ?;", + [task.id], + ); + if (!t.length) return null; + if (t[0].pid != task.pid) return null; + task.pid = Deno.pid; + this.db.query("UPDATE task SET pid = ? WHERE id = ?;", [ + task.pid, + task.id, + ]); + return task; + }); + } + async transaction( + cb: () => T | Promise, + type = SqliteTransactionType.EXCLUSIVE, + ) { + this.begin(type); + await this.flock(); + try { + let re = cb(); + if (re instanceof Promise) re = await re; + await this.commit(); + await this.funlock(); + return re; + } catch (e) { + this.rollback(); + await this.funlock(); + throw e; + } + } +} diff --git a/db_test.ts b/db_test.ts new file mode 100644 index 0000000..a8fe66f --- /dev/null +++ b/db_test.ts @@ -0,0 +1,21 @@ +import { EhDb } from "./db.ts"; +import { TaskType } from "./task.ts"; +import { remove_if_exists } from "./test_base.ts"; +import { sure_dir } from "./utils.ts"; + +Deno.test("DbTest", async () => { + await sure_dir("./test/db"); + await remove_if_exists("./test/db/data.db"); + const db = new EhDb("./test/db"); + console.log( + await db.add_task({ + gid: 1, + token: "dd", + pid: 1, + pn: 1, + type: TaskType.Download, + id: 0, + }), + ); + db.close(); +}); diff --git a/deno.jsonc b/deno.jsonc new file mode 100644 index 0000000..6bed7c3 --- /dev/null +++ b/deno.jsonc @@ -0,0 +1,11 @@ +{ + "tasks": { + "dev": "deno run --watch main.ts", + "test": "deno test --allow-read=./config.json,./test --allow-net --allow-write=./test --allow-run=tasklist.exe --unstable", + "run": "deno run --allow-read=./config.json,./downloads --allow-write=./downloads --allow-run=tasklist.exe --unstable" + }, + "fmt": { + "indentWidth": 4, + "exclude": ["config.json"] + } +} diff --git a/deno.lock b/deno.lock new file mode 100644 index 0000000..40059fb --- /dev/null +++ b/deno.lock @@ -0,0 +1,55 @@ +{ + "version": "2", + "remote": { + "https://deno.land/std@0.188.0/_util/asserts.ts": "178dfc49a464aee693a7e285567b3d0b555dc805ff490505a8aae34f9cfb1462", + "https://deno.land/std@0.188.0/_util/os.ts": "d932f56d41e4f6a6093d56044e29ce637f8dcc43c5a90af43504a889cf1775e3", + "https://deno.land/std@0.188.0/fmt/colors.ts": "d67e3cd9f472535241a8e410d33423980bec45047e343577554d3356e1f0ef4e", + "https://deno.land/std@0.188.0/fs/exists.ts": "29c26bca8584a22876be7cb8844f1b6c8fc35e9af514576b78f5c6884d7ed02d", + "https://deno.land/std@0.188.0/path/_constants.ts": "e49961f6f4f48039c0dfed3c3f93e963ca3d92791c9d478ac5b43183413136e0", + "https://deno.land/std@0.188.0/path/_interface.ts": "6471159dfbbc357e03882c2266d21ef9afdb1e4aa771b0545e90db58a0ba314b", + "https://deno.land/std@0.188.0/path/_util.ts": "d7abb1e0dea065f427b89156e28cdeb32b045870acdf865833ba808a73b576d0", + "https://deno.land/std@0.188.0/path/common.ts": "ee7505ab01fd22de3963b64e46cff31f40de34f9f8de1fff6a1bd2fe79380000", + "https://deno.land/std@0.188.0/path/glob.ts": "d479e0a695621c94d3fd7fe7abd4f9499caf32a8de13f25073451c6ef420a4e1", + "https://deno.land/std@0.188.0/path/mod.ts": "ee161baec5ded6510ee1d1fb6a75a0f5e4b41f3f3301c92c716ecbdf7dae910d", + "https://deno.land/std@0.188.0/path/posix.ts": "8b7c67ac338714b30c816079303d0285dd24af6b284f7ad63da5b27372a2c94d", + "https://deno.land/std@0.188.0/path/separator.ts": "0fb679739d0d1d7bf45b68dacfb4ec7563597a902edbaf3c59b50d5bcadd93b1", + "https://deno.land/std@0.188.0/path/win32.ts": "d186344e5583bcbf8b18af416d13d82b35a317116e6460a5a3953508c3de5bba", + "https://deno.land/std@0.188.0/semver/mod.ts": "200f50cf6872212667df532fb09f0b1a33d3427a5201f75fad30a0d0c6dbcce3", + "https://deno.land/std@0.188.0/testing/_diff.ts": "1a3c044aedf77647d6cac86b798c6417603361b66b54c53331b312caeb447aea", + "https://deno.land/std@0.188.0/testing/_format.ts": "a69126e8a469009adf4cf2a50af889aca364c349797e63174884a52ff75cf4c7", + "https://deno.land/std@0.188.0/testing/asserts.ts": "e16d98b4d73ffc4ed498d717307a12500ae4f2cbe668f1a215632d19fcffc22f", + "https://deno.land/x/deno_dom@v0.1.38/build/deno-wasm/deno-wasm.js": "98b1ad24a1c13284557917659402202e5c5258ab1431b3f3a82434ad36ffa05a", + "https://deno.land/x/deno_dom@v0.1.38/deno-dom-wasm-noinit.ts": "f8798dbf3b3c54d16ec4d22c16e3c63e17f012b6b360179275b1999d8947182f", + "https://deno.land/x/deno_dom@v0.1.38/deno-dom-wasm.ts": "bfd999a493a6974e9fca4d331bee03bfb68cfc600c662cd0b48b21d67a2a8ba0", + "https://deno.land/x/deno_dom@v0.1.38/src/api.ts": "0ff5790f0a3eeecb4e00b7d8fbfa319b165962cf6d0182a65ba90f158d74f7d7", + "https://deno.land/x/deno_dom@v0.1.38/src/constructor-lock.ts": "59714df7e0571ec7bd338903b1f396202771a6d4d7f55a452936bd0de9deb186", + "https://deno.land/x/deno_dom@v0.1.38/src/deserialize.ts": "f4d34514ca00473ca428b69ad437ba345925744b5d791cb9552e2d7a0e7b0439", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/document-fragment.ts": "a40c6e18dd0efcf749a31552c1c9a6f7fa614452245e86ee38fc92ba0235e5ae", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/document.ts": "b8f4e4ccabaaa063d6562a0f2f8dea9c0419515d63d8bd79bfde95f7cd64bd93", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/dom-parser.ts": "609097b426f8c2358f3e5d2bca55ed026cf26cdf86562e94130dfdb0f2537f92", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/element.ts": "77c454e228dfeb5c570da5aa61d91850400116bfa0f5a85505acdd3c667171a4", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/elements/html-template-element.ts": "127bb291bb08afeb7e9a66294a5aa6ff2780f4eb4601fa6f7869fe8b70a81472", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/html-collection.ts": "ae90197f5270c32074926ad6cf30ee07d274d44596c7e413c354880cebce8565", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/node-list.ts": "4c6e4b4585301d4147addaccd90cb5f5a80e8d6290a1ba7058c5e3dfea16e15d", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/node.ts": "3069e6fc93ac4111a136ed68199d76673339842b9751610ba06f111ba7dc10a7", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/selectors/custom-api.ts": "852696bd58e534bc41bd3be9e2250b60b67cd95fd28ed16b1deff1d548531a71", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/selectors/nwsapi-types.ts": "c43b36c36acc5d32caabaa54fda8c9d239b2b0fcbce9a28efb93c84aa1021698", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/selectors/nwsapi.js": "985d7d8fc1eabbb88946b47a1c44c1b2d4aa79ff23c21424219f1528fa27a2ff", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/selectors/selectors.ts": "83eab57be2290fb48e3130533448c93c6c61239f2a2f3b85f1917f80ca0fdc75", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/selectors/sizzle-types.ts": "78149e2502409989ce861ed636b813b059e16bc267bb543e7c2b26ef43e4798b", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/selectors/sizzle.js": "c3aed60c1045a106d8e546ac2f85cc82e65f62d9af2f8f515210b9212286682a", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/utils-types.ts": "96db30e3e4a75b194201bb9fa30988215da7f91b380fca6a5143e51ece2a8436", + "https://deno.land/x/deno_dom@v0.1.38/src/dom/utils.ts": "55f3e9dc71d6c4a54605888d3f99d26fb0cf9973924709f159252a6933ceeabe", + "https://deno.land/x/deno_dom@v0.1.38/src/parser.ts": "b65eb7e673fa7ca611de871de109655f0aa9fa35ddc1de73df1a5fc2baafc332", + "https://deno.land/x/sqlite@v3.7.2/build/sqlite.d.ts": "d724a21a588a0e19ae46a3476349fe5d75e896735e7362ea8cf997ffad35d0f9", + "https://deno.land/x/sqlite@v3.7.2/build/sqlite.js": "c59f109f100c2bae0b9342f04e0d400583e2e3211d08bb71095177a4109ee5bf", + "https://deno.land/x/sqlite@v3.7.2/build/vfs.js": "08533cc78fb29b9d9bd62f6bb93e5ef333407013fed185776808f11223ba0e70", + "https://deno.land/x/sqlite@v3.7.2/mod.ts": "e09fc79d8065fe222578114b109b1fd60077bff1bb75448532077f784f4d6a83", + "https://deno.land/x/sqlite@v3.7.2/src/constants.ts": "90f3be047ec0a89bcb5d6fc30db121685fc82cb00b1c476124ff47a4b0472aa9", + "https://deno.land/x/sqlite@v3.7.2/src/db.ts": "62f3ad4d593c07e7c64fbbd97da6b4579ea695f8d11d52d899661e9d42a400fd", + "https://deno.land/x/sqlite@v3.7.2/src/error.ts": "f7a15cb00d7c3797da1aefee3cf86d23e0ae92e73f0ba3165496c3816ab9503a", + "https://deno.land/x/sqlite@v3.7.2/src/function.ts": "e4c83b8ec64bf88bafad2407376b0c6a3b54e777593c70336fb40d43a79865f2", + "https://deno.land/x/sqlite@v3.7.2/src/query.ts": "d58abda928f6582d77bad685ecf551b1be8a15e8e38403e293ec38522e030cad", + "https://deno.land/x/sqlite@v3.7.2/src/wasm.ts": "e79d0baa6e42423257fb3c7cc98091c54399254867e0f34a09b5bdef37bd9487" + } +} diff --git a/main.ts b/main.ts new file mode 100644 index 0000000..8f26a1c --- /dev/null +++ b/main.ts @@ -0,0 +1,74 @@ +import { parse } from "https://deno.land/std@0.188.0/flags/mod.ts"; +import { load_settings } from "./config.ts"; +import { check_file_permissions } from "./permissons.ts"; +import { TaskManager } from "./task_manager.ts"; +import { ParsedUrl, parseUrl, UrlType } from "./url.ts"; +import { sure_dir } from "./utils.ts"; + +function show_help() { + console.log("Usage: main.ts [options]"); + console.log("Options:"); + console.log(" -h, --help Show this help"); + console.log(" -c, --config Specify config file path."); + console.log(" -a, --add-only Just add task to task list."); +} + +enum CMD { + Unknown, + Download, + Run, +} + +const args = parse(Deno.args, { + alias: { config: ["c"], help: ["h"], add_only: ["a", "add-only"] }, + boolean: ["help", "add_only"], + string: ["config"], + default: { config: "./config.json" }, + negatable: ["add_only"], +}); + +if (!args._.length || args.help) { + show_help(); + Deno.exit(0); +} +const rcmd = args._[0]; +let cmd = CMD.Unknown; +if (rcmd == "d" || rcmd == "download") cmd = CMD.Download; +if (rcmd == "r" || rcmd == "run") cmd = CMD.Run; +if (cmd == CMD.Unknown) { + throw Error(`Unknown command: ${rcmd}`); +} + +const settings = await load_settings(args.config); +if (!check_file_permissions(settings.base)) { + throw Error("Can not aceess download loaction."); +} +async function download() { + const manager = new TaskManager(settings); + const urls: ParsedUrl[] = []; + for (const i of args._.slice(1)) { + const r = parseUrl(i.toString()); + if (r) urls.push(r); + } + for (const u of urls) { + if (u.type == UrlType.Gallery || u.type == UrlType.MPV) { + await manager.add_download_task(u.gid, u.token); + } + } + if (args.add_only) return; + await manager.run(); +} +async function run() { + const manager = new TaskManager(settings); + await manager.run(); +} +async function main() { + await sure_dir(settings.base); + if (cmd == CMD.Download) { + download(); + } else if (cmd == CMD.Run) { + run(); + } +} + +main(); diff --git a/page/GalleryMetadata.ts b/page/GalleryMetadata.ts new file mode 100644 index 0000000..38fbaaf --- /dev/null +++ b/page/GalleryMetadata.ts @@ -0,0 +1,41 @@ +export type GalleryMetadataTorrentInfo = { + hash: string; + added: string; + name: string; + tsize: string; + fsize: string; +} + +export type GalleryMetadataSingle = { + gid: number; + token: string; + archiver_key: string; + title: string; + title_jpn: string; + category: string; + thumb: string; + uploader: string; + posted: string; + filecount: string; + filesize: number; + expunged: boolean; + rating: string; + torrentcount: string; + torrents: GalleryMetadataTorrentInfo[]; + tags: string[]; + parent_gid: string | undefined; + parent_key: string | undefined; + first_gid: string | undefined; + first_key: string | undefined; +} + +class GalleryMetadata { + obj; + constructor(text: string) { + this.obj = JSON.parse(text); + } +} + +export function load_gallery_metadata(text: string) { + return new GalleryMetadata(text); +} diff --git a/page/GalleryMetadata_test.ts b/page/GalleryMetadata_test.ts new file mode 100644 index 0000000..daaa4fe --- /dev/null +++ b/page/GalleryMetadata_test.ts @@ -0,0 +1,13 @@ +import { Client } from "../client.ts"; +import { load_settings } from "../config.ts"; +import { API_PERMISSION } from "../test_base.ts"; + +Deno.test({ + name: "GalleryMetadata_test", + permissions: API_PERMISSION, +}, async () => { + const cfg = await load_settings("./config.json"); + const client = new Client(cfg); + const re = await client.fetchGalleryMetadataByAPI([2552611, "3132307627"]); + console.log(re.obj); +}); diff --git a/page/GalleryPage.ts b/page/GalleryPage.ts new file mode 100644 index 0000000..f1b6c06 --- /dev/null +++ b/page/GalleryPage.ts @@ -0,0 +1,91 @@ +import { + DOMParser, + Element, +} from "https://deno.land/x/deno_dom@v0.1.38/deno-dom-wasm-noinit.ts"; +import { Client } from "../client.ts"; +import { initDOMParser, parse_bool } from "../utils.ts"; + +class GalleryPage { + dom; + doc; + client; + #tags: Set | undefined = undefined; + #gdd_data: Map | undefined = undefined; + constructor(html: string, client: Client) { + const dom = (new DOMParser()).parseFromString(html, "text/html"); + if (!dom) { + throw Error("Failed to parse HTML document."); + } + this.dom = dom; + const doc = this.dom.documentElement; + if (!doc) { + throw Error("HTML document don't have a document element."); + } + this.doc = doc; + this.client = client; + } + get favorited() { + const o = this.gdd_data.get("Favorited")?.innerText; + if (!o) return undefined; + const p = o.slice(0, o.length - 6); + return parseInt(p); + } + get file_size() { + return this.gdd_data.get("File Size")?.innerText; + } + get gdd_data() { + if (this.#gdd_data === undefined) { + const g = new Map(); + const t = Array.from( + this.doc.querySelectorAll("#gdd > table tr"), + ); + for (const e of t) { + const k = e.children[0].innerText; + g.set(k.slice(0, k.length - 1), e.children[1]); + } + this.#gdd_data = g; + return g; + } else return this.#gdd_data; + } + get language() { + const o = this.gdd_data.get("Language")?.innerText; + if (!o) return undefined; + if (o.endsWith("TR")) { + return o.slice(0, o.length - 2).trim(); + } else return o.trim(); + } + get length() { + const o = this.gdd_data.get("Length")?.innerText; + if (!o) throw Error("Unknown length."); + const p = o.slice(0, o.length - 6); + return parseInt(p); + } + get name() { + const ele = this.doc.getElementById("gn"); + if (!ele) throw Error("Failed to find gallery's name."); + return ele.innerText; + } + get japanese_name() { + return this.doc.getElementById("gj")?.innerText; + } + get tags() { + if (this.#tags === undefined) { + const eles = Array.from( + this.doc.querySelectorAll("[id^=td_]"), + ); + const tags = new Set(eles.map((e) => e.id.slice(3))); + this.#tags = tags; + return tags; + } else return this.#tags; + } + get visible() { + const s = this.gdd_data.get("Visible")?.innerText; + if (s === undefined) return undefined; + return parse_bool(s); + } +} + +export async function load_gallery_page(html: string, client: Client) { + await initDOMParser(); + return new GalleryPage(html, client); +} diff --git a/page/GalleryPage_test.ts b/page/GalleryPage_test.ts new file mode 100644 index 0000000..82dbae3 --- /dev/null +++ b/page/GalleryPage_test.ts @@ -0,0 +1,40 @@ +import { + assert, + assertEquals, +} from "https://deno.land/std@0.188.0/testing/asserts.ts"; +import { Client } from "../client.ts"; +import { load_settings } from "../config.ts"; +import { API_PERMISSION } from "../test_base.ts"; + +Deno.test({ + name: "GalleryPage_test", + permissions: API_PERMISSION, +}, async () => { + const cfg = await load_settings("./config.json"); + const client = new Client(cfg); + const re = await client.fetchGalleryPage(2552611, "3132307627"); + assertEquals( + re.name, + "(C101) [Shiratamaco (Shiratama)] Étude 30 (Various) [Chinese] [白玉症候群汉化]", + ); + assertEquals( + re.japanese_name, + "(C101) [しらたまこ (しらたま)] Étude 27 (よろず) [中国翻訳]", + ); + assertEquals( + re.tags, + new Set([ + "language:chinese", + "language:translated", + "group:shiratamaco", + "artist:shiratama", + "female:kemonomimi", + ]), + ); + assertEquals(re.length, 19); + assertEquals(re.file_size, "58.20 MB"); + assertEquals(re.visible, true); + console.log(re.favorited); + assert(typeof re.favorited === "number"); + assertEquals(re.language, "Chinese"); +}); diff --git a/page/SinglePage.ts b/page/SinglePage.ts new file mode 100644 index 0000000..1dc989c --- /dev/null +++ b/page/SinglePage.ts @@ -0,0 +1,105 @@ +import { + DOMParser, +} from "https://deno.land/x/deno_dom@v0.1.38/deno-dom-wasm-noinit.ts"; +import { Client } from "../client.ts"; +import { initDOMParser } from "../utils.ts"; + +class SinglePage { + dom; + doc; + client; + _meta: string | undefined; + _gid: number | undefined; + constructor(html: string, client: Client) { + const dom = (new DOMParser()).parseFromString(html, "text/html"); + if (!dom) { + throw Error("Failed to parse HTML document."); + } + this.dom = dom; + const doc = this.dom.documentElement; + if (!doc) { + throw Error("HTML document don't have a document element."); + } + this.doc = doc; + this.client = client; + this._meta = undefined; + this._gid = undefined; + } + async load_image(url: string) { + const re = await this.client.get(url); + if (re.status != 200) { + throw new Error( + `Fetch ${url} failed, status ${re.status} ${re.statusText}`, + ); + } + return new SinglePage(await re.text(), this.client); + } + get currentIndex() { + const span = this.doc.querySelector("#i2>div span"); + if (!span) throw Error("Can not find currentIndex."); + return parseInt(span.innerHTML); + } + get gid() { + if (this._gid === undefined) { + this._gid = eval(`${this.meta};gid`); + if (typeof this._gid != "number") throw Error("Unknown gid"); + } + return this._gid; + } + get img_url() { + const img = this.doc.querySelector("#img"); + if (!img) throw Error("Unknown image url."); + const url = img.getAttribute("src"); + if (!url) throw Error("Unknown image url."); + return url; + } + get meta() { + if (this._meta === undefined) { + const scripts = this.doc.getElementsByTagName("script"); + for (const script of scripts) { + if (script.innerHTML.startsWith("var")) { + this._meta = script.innerHTML; + break; + } + } + } + return this._meta; + } + async nextPage() { + const url = this.nextPageUrl; + if (!url) return null; + return await this.load_image(url); + } + get nextPageUrl() { + if (this.currentIndex == this.pageCount) return null; + const a = this.doc.getElementById("next"); + if (a === null) return null; + return a.getAttribute("href"); + } + get original_url() { + const a = this.doc.querySelector("#i7 a"); + if (a == null) return null; + return a.getAttribute("href"); + } + get pageCount() { + const e = this.doc.querySelector("#i2>div span:last-child"); + if (!e) throw Error("Failed to find page count element."); + return parseInt(e.innerHTML); + } + async prevPage() { + const url = this.prevPageUrl; + if (!url) return null; + return await this.load_image(url); + } + get prevPageUrl() { + if (this.currentIndex == this.pageCount) return null; + const a = this.doc.getElementById("prev"); + if (a === null) return null; + return a.getAttribute("href"); + } +} + +export async function load_single_page(html: string, client: Client) { + await initDOMParser(); + return new SinglePage(html, client); +} diff --git a/page/SinglePage_test.ts b/page/SinglePage_test.ts new file mode 100644 index 0000000..a782f7e --- /dev/null +++ b/page/SinglePage_test.ts @@ -0,0 +1,22 @@ +import { + assert, + assertEquals, +} from "https://deno.land/std@0.188.0/testing/asserts.ts"; +import { Client } from "../client.ts"; +import { load_settings } from "../config.ts"; +import { API_PERMISSION } from "../test_base.ts"; + +Deno.test({ + name: "SinglePage_test", + permissions: API_PERMISSION, +}, async () => { + const cfg = await load_settings("./config.json"); + const client = new Client(cfg); + const re = await client.fetchSignlePage(2552611, "30d3bd7940", 1); + assertEquals(re.currentIndex, 1); + assertEquals(re.nextPageUrl, "https://e-hentai.org/s/8216544b21/2552611-2"); + const np = await re.nextPage(); + assert(np); + assertEquals(np.currentIndex, 2); + assertEquals(np.gid, re.gid); +}); diff --git a/permissons.ts b/permissons.ts new file mode 100644 index 0000000..1f6f79a --- /dev/null +++ b/permissons.ts @@ -0,0 +1,5 @@ +export async function check_file_permissions(path: string) { + const status1 = await Deno.permissions.request({ name: "read", path }); + const status2 = await Deno.permissions.request({ name: "write", path }); + return status1.state == "granted" && status2.state == "granted"; +} diff --git a/pid_check.ts b/pid_check.ts new file mode 100644 index 0000000..c74a68b --- /dev/null +++ b/pid_check.ts @@ -0,0 +1,13 @@ +export async function check_running(pid: number) { + if (Deno.build.os == "windows") { + const cmd = new Deno.Command("tasklist.exe", { + args: ["/NH", "/FI", `pid eq ${pid}`], + stdout: "piped", + }); + const c = cmd.spawn(); + const o = await c.output(); + if (o.code !== 0) return; + const s = (new TextDecoder()).decode(o.stdout); + return s.indexOf(`${pid}`) !== -1; + } +} diff --git a/task.ts b/task.ts new file mode 100644 index 0000000..781ee68 --- /dev/null +++ b/task.ts @@ -0,0 +1,12 @@ +export enum TaskType { + Download, +} + +export type Task = { + id: number; + type: TaskType; + gid: number; + token: string; + pn: number; + pid: number; +}; diff --git a/task_manager.ts b/task_manager.ts new file mode 100644 index 0000000..9d3d91c --- /dev/null +++ b/task_manager.ts @@ -0,0 +1,101 @@ +import { Client } from "./client.ts"; +import { Config } from "./config.ts"; +import { EhDb } from "./db.ts"; +import { check_running } from "./pid_check.ts"; +import { Task, TaskType } from "./task.ts"; +import { download_task } from "./tasks/download.ts"; +import { promiseState, PromiseStatus, sleep } from "./utils.ts"; + +export class TaskManager { + client; + db; + running_tasks: Map>; + max_task_count; + constructor(cfg: Config) { + this.client = new Client(cfg); + this.db = new EhDb(cfg.base); + this.running_tasks = new Map(); + this.max_task_count = cfg.max_task_count; + } + async add_download_task(gid: number, token: string) { + const otask = await this.db.check_download_task(gid, token); + if (otask !== undefined) { + console.log("The task is already in list."); + return otask; + } + const task: Task = { + gid, + token, + id: 0, + pid: Deno.pid, + pn: 1, + type: TaskType.Download, + }; + return await this.db.add_task(task); + } + async check_task(task: Task) { + if (await this.check_task_is_running(task)) return; + let t = task; + if (task.pid !== Deno.pid) { + const p = await this.db.set_task_pid(t); + if (p == null) return; + t = p; + } + return t; + } + async check_task_is_running(task: Task) { + if (task.pid == Deno.pid) { + return this.running_tasks.has(task.id); + } else { + const r = await check_running(task.pid); + return r === true; + } + } + async check_running_tasks() { + const removed_task: number[] = []; + for (const [id, task] of this.running_tasks) { + const status = await promiseState(task); + if (status.status == PromiseStatus.Fulfilled && status.value) { + removed_task.push(id); + await this.db.delete_task(status.value); + } else if (status.status == PromiseStatus.Rejected) { + if (status.reason) console.log(status.reason); + removed_task.push(id); + } + } + for (const id of removed_task) { + this.running_tasks.delete(id); + } + } + async run() { + while (1) { + await this.check_running_tasks(); + if (this.running_tasks.size == this.max_task_count) { + await sleep(1000); + continue; + } + const my_tasks = await this.db.get_tasks_by_pid(Deno.pid); + for (const task of my_tasks) { + if (this.running_tasks.size == this.max_task_count) break; + const checked = await this.check_task(task); + if (checked) this.run_task(checked); + } + if (this.running_tasks.size == this.max_task_count) continue; + const otasks = await this.db.get_other_pid_tasks(); + for (const task of otasks) { + if (this.running_tasks.size == this.max_task_count) break; + const checked = await this.check_task(task); + if (checked) this.run_task(checked); + } + if (this.running_tasks.size == 0) break; + } + } + run_task(task: Task) { + if (task.type == TaskType.Download) { + this.running_tasks.set( + task.id, + download_task(task, this.client, this.db), + ); + } + } +} diff --git a/tasks/download.ts b/tasks/download.ts new file mode 100644 index 0000000..5a624a9 --- /dev/null +++ b/tasks/download.ts @@ -0,0 +1,8 @@ +import { Client } from "../client.ts"; +import { EhDb } from "../db.ts"; +import { Task } from "../task.ts"; + +export async function download_task(task: Task, client: Client, db: EhDb) { + console.log("Started to download gallery", task.gid); + return task; +} diff --git a/test_base.ts b/test_base.ts new file mode 100644 index 0000000..aab5739 --- /dev/null +++ b/test_base.ts @@ -0,0 +1,10 @@ +import { exists } from "https://deno.land/std@0.188.0/fs/exists.ts"; + +export const API_PERMISSION: Deno.PermissionOptions = { + read: ["./config.json"], + net: ["e-hentai.org", "exhentai.org"], +}; + +export async function remove_if_exists(f: string) { + if (await exists(f)) await Deno.remove(f, { "recursive": true }); +} diff --git a/url.ts b/url.ts new file mode 100644 index 0000000..5f9d8e9 --- /dev/null +++ b/url.ts @@ -0,0 +1,36 @@ +export enum UrlType { + Gallery, + MPV, + Single, +} + +export type ParsedUrl = { + type: UrlType; + gid: number; + token: string; + index: number | undefined; +}; + +export function parseUrl(url: string) { + const u = new URL(url, "https://e-hentai.org/"); + if (u.hostname != "e-hentai.org" && u.hostname != "exhentai.org") { + return undefined; + } + let re = u.pathname.match(/s\/([^\/]+)\/(\d+)-(\d+)/); + if (re != null) { + return { + type: UrlType.Single, + gid: parseInt(re[2]), + token: re[1], + index: parseInt(re[3]), + } as ParsedUrl; + } + re = u.pathname.match(/(g|mpv)\/(\d+)\/([^\/]+)/); + if (re != null) { + return { + type: re[1] == "g" ? UrlType.Gallery : UrlType.MPV, + gid: parseInt(re[2]), + token: re[3], + } as ParsedUrl; + } +} diff --git a/utils.ts b/utils.ts new file mode 100644 index 0000000..18a0d18 --- /dev/null +++ b/utils.ts @@ -0,0 +1,62 @@ +import { exists } from "https://deno.land/std@0.188.0/fs/exists.ts"; +import { initParser } from "https://deno.land/x/deno_dom@v0.1.38/deno-dom-wasm-noinit.ts"; + +export function sleep(time: number): Promise { + return new Promise((r) => { + setTimeout(() => { + r(undefined); + }, time); + }); +} + +export async function sure_dir(f = "./test") { + if (!await exists(f)) { + await Deno.mkdir(f, { "recursive": true }); + } +} + +export enum PromiseStatus { + Pending, + Fulfilled, + Rejected, +} + +export type PromiseState = { + status: PromiseStatus; + value: Awaited | undefined; + reason: unknown; +}; + +export function promiseState(p: Promise): Promise> { + const pe = { status: PromiseStatus.Pending }; + return new Promise((resolve) => { + Promise.race([p, pe]).then((v) => { + v === pe ? resolve(pe as PromiseState) : resolve( + { + status: PromiseStatus.Fulfilled, + value: v, + } as PromiseState, + ); + }).catch((e) => { + resolve( + { status: PromiseStatus.Rejected, reason: e } as PromiseState< + T + >, + ); + }); + }); +} + +let inited_parser = false; + +export async function initDOMParser() { + if (!inited_parser) { + await initParser(); + inited_parser = true; + } +} + +export function parse_bool(s: string) { + const l = s.toLowerCase(); + return l === "true" || l === "yes"; +} diff --git a/utils_test.ts b/utils_test.ts new file mode 100644 index 0000000..e9bba89 --- /dev/null +++ b/utils_test.ts @@ -0,0 +1,28 @@ +import { assertEquals } from "https://deno.land/std@0.188.0/testing/asserts.ts"; +import { check_running } from "./pid_check.ts"; +import { promiseState, sleep } from "./utils.ts"; + +Deno.test("promiseState_test", async () => { + const p1 = new Promise((res) => setTimeout(() => res(100), 100)); + const p2 = new Promise((res) => setTimeout(() => res(200), 200)); + const p3 = new Promise((_res, rej) => setTimeout(() => rej(300), 100)); + + async function getStates() { + console.log(await promiseState(p1)); + console.log(await promiseState(p2)); + console.log(await promiseState(p3)); + } + + console.log("Immediately after initiation:"); + await getStates(); + await sleep(100); + console.log("After waiting for 100ms:"); + await getStates(); + await Promise.allSettled([p1, p2, p3]); +}); + +Deno.test("Pid_Test", async () => { + if (Deno.build.os == "windows") { + assertEquals(await check_running(Deno.pid), true); + } +});