From 82b1fcc4097b5e3d148af8c54f0f7127b794ca5d Mon Sep 17 00:00:00 2001 From: Twiddly Date: Mon, 26 Jun 2017 23:33:06 +0200 Subject: [PATCH 01/68] Initial commit --- .gitignore | 101 ++++++++ LICENSE | 674 +++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 2 + 3 files changed, 777 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7bbc71c --- /dev/null +++ b/.gitignore @@ -0,0 +1,101 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# dotenv +.env + +# virtualenv +.venv +venv/ +ENV/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..9cecc1d --- /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. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +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: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..b1de0d7 --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# plugins +Plugins for Happypanda X From 4f1e3a7164bd80e3c8d4ed21026327112d210593 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sun, 1 Jul 2018 17:19:21 +0200 Subject: [PATCH 02/68] update --- README.md | 17 ++++++- build.py | 49 +++++++++++++++++++ {version => plugins}/File Metadata/common.py | 0 .../File Metadata/extractors.py | 0 .../File Metadata/hplugin.json | 0 {version => plugins}/File Metadata/main.py | 0 6 files changed, 64 insertions(+), 2 deletions(-) create mode 100644 build.py rename {version => plugins}/File Metadata/common.py (100%) rename {version => plugins}/File Metadata/extractors.py (100%) rename {version => plugins}/File Metadata/hplugin.json (100%) rename {version => plugins}/File Metadata/main.py (100%) diff --git a/README.md b/README.md index b1de0d7..1b1d119 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,15 @@ -# plugins -Plugins for Happypanda X + +In this repository resides plugins for HappyPanda X + +# How to install + +Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. + +# Be careful about plugins + +Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in documentation + +# Plugins + +- File Metadata -- Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin + diff --git a/build.py b/build.py new file mode 100644 index 0000000..fd6e2a5 --- /dev/null +++ b/build.py @@ -0,0 +1,49 @@ +import json +import glob +import pathlib + +readme = """ +In this repository resides plugins for HappyPanda X + +# How to install + +Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. + +# Be careful about plugins + +Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in documentation + +# Plugins + +{} +""" + +plugins_dir = "plugins" +readme_file = "README.md" +desc_max_length = 200 + +def main(): + print("Building...") + plugin_readme = "" + + for p in sorted(glob.glob(f"{plugins_dir}/**/hplugin.json")): + with open(p, 'r', encoding="utf-8") as f: + d = json.load(f) + dir_name = pathlib.Path(p).parent.name + plugin_desc = d.get("description") + plugin_ver = d.get("version") + + if plugin_desc and plugin_ver: + plugin_desc = plugin_desc.split('\n')[0] + if len(plugin_desc) > desc_max_length: + plugin_desc = plugin_desc[:desc_max_length] + '...' + plugin_readme += f"- {dir_name} `{plugin_ver}` -- {plugin_desc}\n" + + txt = readme.format(plugin_readme) + + with open(readme_file, 'w', encoding="utf-8") as f: + f.write(txt) + print("Done!") + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/version/File Metadata/common.py b/plugins/File Metadata/common.py similarity index 100% rename from version/File Metadata/common.py rename to plugins/File Metadata/common.py diff --git a/version/File Metadata/extractors.py b/plugins/File Metadata/extractors.py similarity index 100% rename from version/File Metadata/extractors.py rename to plugins/File Metadata/extractors.py diff --git a/version/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json similarity index 100% rename from version/File Metadata/hplugin.json rename to plugins/File Metadata/hplugin.json diff --git a/version/File Metadata/main.py b/plugins/File Metadata/main.py similarity index 100% rename from version/File Metadata/main.py rename to plugins/File Metadata/main.py From 5e10e13f18c7f22b3f5c3b8845aa6a7a2f7b4c05 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sun, 1 Jul 2018 17:20:20 +0200 Subject: [PATCH 03/68] update --- README.md | 2 +- build.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 1b1d119..535d2a1 100644 --- a/README.md +++ b/README.md @@ -11,5 +11,5 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- File Metadata -- Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin +- **File Metadata** `0.1.0b` -- *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* diff --git a/build.py b/build.py index fd6e2a5..eba1885 100644 --- a/build.py +++ b/build.py @@ -37,7 +37,7 @@ def main(): plugin_desc = plugin_desc.split('\n')[0] if len(plugin_desc) > desc_max_length: plugin_desc = plugin_desc[:desc_max_length] + '...' - plugin_readme += f"- {dir_name} `{plugin_ver}` -- {plugin_desc}\n" + plugin_readme += f"- **{dir_name}** `{plugin_ver}` -- *{plugin_desc}*\n" txt = readme.format(plugin_readme) From 1e99eafb28fabb79b76d5b378cd02c699002efdd Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sun, 1 Jul 2018 17:44:17 +0200 Subject: [PATCH 04/68] update --- README.md | 10 +++++++++- build.py | 16 +++++++++++++--- 2 files changed, 22 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 535d2a1..2bb4895 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,14 @@ In this repository resides plugins for HappyPanda X +# How to download + +I recommend these tools to download a single directory from this repo: +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* +- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* +- [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) +- [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) + # How to install Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. @@ -11,5 +19,5 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- **File Metadata** `0.1.0b` -- *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* +- [**File Metadata**](plugins/File Metadata) `0.1.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* diff --git a/build.py b/build.py index eba1885..335c6da 100644 --- a/build.py +++ b/build.py @@ -5,6 +5,14 @@ readme = """ In this repository resides plugins for HappyPanda X +# How to download + +I recommend these tools to download a single directory from this repo: +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* +- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* +- [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) +- [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) + # How to install Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. @@ -29,15 +37,17 @@ def main(): for p in sorted(glob.glob(f"{plugins_dir}/**/hplugin.json")): with open(p, 'r', encoding="utf-8") as f: d = json.load(f) - dir_name = pathlib.Path(p).parent.name + plugin_dir = pathlib.Path(p).parent + dir_name = plugin_dir.name + plugin_dir = str(plugin_dir).replace('\\', '/') plugin_desc = d.get("description") plugin_ver = d.get("version") if plugin_desc and plugin_ver: plugin_desc = plugin_desc.split('\n')[0] if len(plugin_desc) > desc_max_length: - plugin_desc = plugin_desc[:desc_max_length] + '...' - plugin_readme += f"- **{dir_name}** `{plugin_ver}` -- *{plugin_desc}*\n" + plugin_desc = plugin_desc[:desc_max_length] + '…' + plugin_readme += f"- [**{dir_name}**]({plugin_dir}) `{plugin_ver}` ᠁ *{plugin_desc}*\n" txt = readme.format(plugin_readme) From fc9ce06dea55f6c24e1c2753a74994d1aee7c964 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sun, 1 Jul 2018 17:58:37 +0200 Subject: [PATCH 05/68] add plugin links; --- README.md | 4 ++-- build.py | 9 +++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 2bb4895..f458f09 100644 --- a/README.md +++ b/README.md @@ -4,8 +4,8 @@ In this repository resides plugins for HappyPanda X # How to download I recommend these tools to download a single directory from this repo: -- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* - https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) @@ -19,5 +19,5 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- [**File Metadata**](plugins/File Metadata) `0.1.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* +- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.1.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* diff --git a/build.py b/build.py index 335c6da..cb1b0fd 100644 --- a/build.py +++ b/build.py @@ -1,6 +1,7 @@ import json import glob import pathlib +from urllib.parse import quote readme = """ In this repository resides plugins for HappyPanda X @@ -8,8 +9,8 @@ # How to download I recommend these tools to download a single directory from this repo: -- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* - https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) @@ -29,6 +30,8 @@ plugins_dir = "plugins" readme_file = "README.md" desc_max_length = 200 +repo_user = "happypandax" +repo_name = "plugins" def main(): print("Building...") @@ -43,11 +46,13 @@ def main(): plugin_desc = d.get("description") plugin_ver = d.get("version") + gh_url = f"https://github.com/{repo_user}/{repo_name}/tree/master/{quote(plugin_dir)}" + if plugin_desc and plugin_ver: plugin_desc = plugin_desc.split('\n')[0] if len(plugin_desc) > desc_max_length: plugin_desc = plugin_desc[:desc_max_length] + '…' - plugin_readme += f"- [**{dir_name}**]({plugin_dir}) `{plugin_ver}` ᠁ *{plugin_desc}*\n" + plugin_readme += f"- [**{dir_name}**]({gh_url}) `{plugin_ver}` ᠁ *{plugin_desc}*\n" txt = readme.format(plugin_readme) From 82685e126594bee4955cefb833b6affead75375f Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 24 Jul 2018 18:59:14 +0200 Subject: [PATCH 06/68] update file metadata plugin to 0.2.0b; --- Example Plugin/tests.py | 1 - build.py | 7 ++-- plugins/File Metadata/common.py | 49 ++++++++++++---------- plugins/File Metadata/extractors.py | 65 +++++++++++++++++++++++++++++ plugins/File Metadata/hplugin.json | 6 +-- plugins/File Metadata/main.py | 56 +++++++++++++------------ plugins/File Metadata/readme.md | 28 +++++++++++++ 7 files changed, 157 insertions(+), 55 deletions(-) delete mode 100644 Example Plugin/tests.py create mode 100644 plugins/File Metadata/readme.md diff --git a/Example Plugin/tests.py b/Example Plugin/tests.py deleted file mode 100644 index 36a317e..0000000 --- a/Example Plugin/tests.py +++ /dev/null @@ -1 +0,0 @@ -# test.py \ No newline at end of file diff --git a/build.py b/build.py index cb1b0fd..a4ba1c9 100644 --- a/build.py +++ b/build.py @@ -4,13 +4,14 @@ from urllib.parse import quote readme = """ -In this repository resides plugins for HappyPanda X +In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to +[the docs](https://happypandax.github.io/plugin.html#plugins). # How to download I recommend these tools to download a single directory from this repo: -- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* -- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* +- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder in this repo* - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) diff --git a/plugins/File Metadata/common.py b/plugins/File Metadata/common.py index 4a065c9..bdcdf72 100644 --- a/plugins/File Metadata/common.py +++ b/plugins/File Metadata/common.py @@ -4,14 +4,15 @@ log = hpx.get_logger(__name__) -class DataType(enum.Enum): - eze = 1 - hdoujin = 2 +class DataType(enum.Flag): + eze = enum.auto() + hdoujin = enum.auto() + e_hentai_downloader = enum.auto() filetypes = ('.json', '.txt') filenames = { - "info.json": (DataType.eze, DataType.hdoujin), - "info.txt": (DataType.hdoujin,) + "info.json": DataType.eze | DataType.hdoujin, + "info.txt": DataType.hdoujin | DataType.e_hentai_downloader, } common_data = { @@ -44,23 +45,27 @@ class Extractor: def file_to_dict(self, fs: hpx.command.CoreFS) -> dict: """ """ - d = {} - log.debug(f"File ext: {fs.ext}") - kw = {} - if not fs.inside_archive: - kw['encoding'] = 'utf-8' - if fs.ext.lower() == '.json': - with fs.open("r", **kw) as f: - d = json.load(f) - elif fs.ext.lower() == '.txt': - with fs.open("r", **kw) as f: - for line in f.readlines(): - l = line.strip() - k, v = l.split(':', 1) - if k.strip(): - d[k.strip()] = v.strip() - else: - raise NotImplementedError(f"{fs.ext} filetype not supported yet") + try: + d = {} + log.debug(f"File ext: {fs.ext}") + kw = {} + if not fs.inside_archive: + kw['encoding'] = 'utf-8' + if fs.ext.lower() == '.json': + with fs.open("r", **kw) as f: + d = json.load(f) + elif fs.ext.lower() == '.txt': + with fs.open("r", **kw) as f: + for line in f.readlines(): + l = line.strip() + k, v = l.split(b':' if fs.inside_archive else ':', 1 ) + if k.strip(): + d[k.strip()] = v.strip() + else: + raise NotImplementedError(f"{fs.ext} filetype not supported yet") + except Exception: + log.warning("An error occured while trying to parse file into a dict") + raise ValueError return d def extract(self, filedata: dict) -> dict: diff --git a/plugins/File Metadata/extractors.py b/plugins/File Metadata/extractors.py index a2f1f4b..c26252a 100644 --- a/plugins/File Metadata/extractors.py +++ b/plugins/File Metadata/extractors.py @@ -128,3 +128,68 @@ def extract(self, filedata): return d common.register_extractor(HDoujin, common.DataType.hdoujin) + +class EHentaiDownloader(common.Extractor): + + def file_to_dict(self, fs): + """ + File is formatted weirdly so we just return {linenumber : line} + """ + d = {} + log.debug(f"File ext: {fs.ext}") + kw = {} + if not fs.inside_archive: + kw['encoding'] = "utf-8" + with fs.open("r", **kw) as f: + for num, line in enumerate(f.readlines(), 1): + if isinstance(line, bytes): + line = line.decode("utf-8") + d[num] = line + + # confirm it's the right file + if d and not "generated by e-hentai downloader" in d[len(d)].lower(): + d = None + return d + + def extract(self, filedata): + d = {} + if filedata: + log.debug("Expecting e-hentai downloader metadata file") + for linenum in sorted(filedata): + line = filedata[linenum].strip() + if not line: + continue + + if line.startswith("Language:"): + line = line.split(':', 1)[1] + d['language'] = common.capitalize_text(line.lower().split()[0]) + continue + + if line.startswith("Category:"): + line = line.split(':', 1)[1] + d['category'] = common.capitalize_text(line.lower()) + continue + + if line.startswith("> "): # tags + line = line[2:] # remove > + ns, tags = line.split(':', 1) + tags = tags.split(",") + d.setdefault("tags", {})[ns.strip()] = [t.strip() for t in tags] + continue + + if linenum in (1, 2, 3): # most likely a title or url, must be last because maybe it wasn't included + # ensure + if not filedata.get(3, "").startswith("http"): + continue + + if linenum == 3: + d.setdefault('urls', []).append(line) + else: + title_lang = "english" if linenum == 1 else "japanese" + nameparser = hpx.command.NameParser(line) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) + continue + return d + +common.register_extractor(EHentaiDownloader, common.DataType.e_hentai_downloader) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index 3d9b165..70e5908 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,12 +2,12 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "0.1.0b", + "version": "0.2.0b", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin", "author": "Twiddly", - "website": "https://github.com/happypandax/plugins", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", "entry": "main.py", "require": [ - "happypandax >= 0.1.2" + "happypandax >= 0.2.0" ] } \ No newline at end of file diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index e20214b..c1a5d83 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -11,29 +11,33 @@ } def get_common_data(datatypes, fpath): - assert isinstance(datatypes, tuple) + assert isinstance(datatypes, common.DataType) d = {} fpath = hpx.command.CoreFS(fpath) - for datatype in datatypes: - md = {} - - ex = common.extractors.get(datatype, None) - if ex: - fdata = ex.file_to_dict(fpath) - if fdata: - md.update(ex.extract(fdata)) - if md: - d.update(md) - break + for datatype in common.DataType: + if datatype & datatypes: + log.info(f"Attempting with {datatype}") + md = {} + + ex = common.extractors.get(datatype, None) + if ex: + try: + fdata = ex.file_to_dict(fpath) + except ValueError: + log.info(f"Skipping {datatype}") + continue + if fdata: + md.update(ex.extract(fdata)) + if md: + d.update(md) + break return d language_model = hpx.command.GetModelClass("Language") title_model = hpx.command.GetModelClass("Title") artist_model = hpx.command.GetModelClass("Artist") circle_model = hpx.command.GetModelClass("Circle") -category_model = hpx.command.GetModelClass("Category") -artistname_model = hpx.command.GetModelClass("ArtistName") url_model = hpx.command.GetModelClass("Url") namespacetags_model = hpx.command.GetModelClass("NamespaceTags") @@ -45,11 +49,13 @@ def apply_metadata(data, gallery): if isinstance(data['titles'], (list, tuple)): for t, l in data['titles']: + gtitle = None if t: gtitle = title_model(name=t) - gallery.titles.append(gtitle) if t and l: gtitle.language = language_model.as_unique(name=l) + if gtitle: + gallery.update("titles", gtitle) applied = True if isinstance(data['artists'], (list, tuple)): @@ -57,22 +63,20 @@ def apply_metadata(data, gallery): if a: gartist = artist_model.as_unique(name=a) if not gartist in gallery.artists: - gallery.artists.append(gartist) + gallery.update("artists", gartist) if a and c: for circlename in [x for x in c if x]: gcircle = circle_model.as_unique(name=circlename) if not gcircle in gartist.circles: - gartist.circles.append(gcircle) + gartist.update("circles", gcircle) applied = True if data['category']: - gcat = category_model.as_unique(name=data['category']) - gallery.category = gcat + gallery.update("category", name=data['category']) applied = True if data['language']: - glang = language_model.as_unique(name=data['language']) - gallery.language = glang + gallery.update("language", name=data['language']) applied = True if isinstance(data['tags'], (dict, list)): @@ -89,20 +93,20 @@ def apply_metadata(data, gallery): ns_tags.append(namespacetags_model.as_unique(ns=ns, tag=t)) for nstag in ns_tags: - if not nstag in gallery.tags: + if nstag not in gallery.tags: gallery.tags.append(nstag) applied = True if isinstance(data['pub_date'], (datetime.datetime, arrow.Arrow)): pub_date = data['pub_date'] - if isinstance(pub_date, datetime.datetime): - pub_date = arrow.Arrow.fromdatetime(pub_date) - gallery.pub_date = pub_date + gallery.update("pub_date", pub_date) applied = True if isinstance(data['urls'], (list, tuple)): + urls = [] for u in data['urls']: - gallery.urls.append(url_model(name=u)) + urls.append(url_model(name=u)) + gallery.update("urls", urls) applied = True return applied diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md new file mode 100644 index 0000000..73bdbfc --- /dev/null +++ b/plugins/File Metadata/readme.md @@ -0,0 +1,28 @@ +File Metadata +---------------------------- + +> This plugin extracts and applies metadata from a file accompanying a gallery folder or archive. + +This plugin supports extracting metadata from files produced by: + +- [eze](https://dnsev-h.github.io/eze/) + > only supports JSON format and file must be named `info.json` +- [HDoujin Downloader](https://doujindownloader.com/) + > all file versions are supported + > supports both JSON and TXT formats + > file must be named `info.json` or `info.txt` + +# Extending + +... coming + +# Changelog + +- `0.2.0b` + - require HPX `0.2.0` + - use new api to update gallery data + - add support for E-Hentai-Downloader + - fix bug where `info.txt` in archive files would fail to get parsed + +- `0.1.0b` + - first version \ No newline at end of file From 9badf6dec56e8d7d76dc6008b2f99f1c9c7345d1 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 24 Jul 2018 19:04:10 +0200 Subject: [PATCH 07/68] build readme --- Example Plugin/test.py | 1 + README.md | 9 +++++---- 2 files changed, 6 insertions(+), 4 deletions(-) create mode 100644 Example Plugin/test.py diff --git a/Example Plugin/test.py b/Example Plugin/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/Example Plugin/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file diff --git a/README.md b/README.md index f458f09..aed7797 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ -In this repository resides plugins for HappyPanda X +In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to +[the docs](https://happypandax.github.io/plugin.html#plugins). # How to download I recommend these tools to download a single directory from this repo: -- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* -- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* +- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder in this repo* - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) @@ -19,5 +20,5 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.1.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* +- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* From b0064549236374c1db48d688c3e8fbfe78f69eaf Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 24 Jul 2018 19:09:30 +0200 Subject: [PATCH 08/68] update readme --- plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/readme.md | 10 ++++++---- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index 70e5908..1a8bef9 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -3,7 +3,7 @@ "shortname": "file-metadata", "name": "File Metadata", "version": "0.2.0b", - "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin", + "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", "entry": "main.py", diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 73bdbfc..1d4c774 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -6,11 +6,13 @@ File Metadata This plugin supports extracting metadata from files produced by: - [eze](https://dnsev-h.github.io/eze/) - > only supports JSON format and file must be named `info.json` + > - only supports JSON format and file must be named `info.json` - [HDoujin Downloader](https://doujindownloader.com/) - > all file versions are supported - > supports both JSON and TXT formats - > file must be named `info.json` or `info.txt` + > - all file versions are supported + > - supports both JSON and TXT formats + > - file must be named `info.json` or `info.txt` +- [E-Hentai-Downloader](https://github.com/ccloli/E-Hentai-Downloader) + > - supports only the file named `info.txt` # Extending From 7ded693e2520ffb7bfa4976c48a7c0878a24730a Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 24 Jul 2018 17:13:40 +0000 Subject: [PATCH 09/68] update file metadata plugin to 0.2.0b; (#5) - require HPX `0.2.0` - use new api to update gallery data - add support for E-Hentai-Downloader [#36](https://github.com/happypandax/happypandax/issues/36) - fix bug where `info.txt` in archive files would fail to get parsed --- Example Plugin/{tests.py => test.py} | 0 README.md | 9 ++-- build.py | 7 +-- plugins/File Metadata/common.py | 49 +++++++++++---------- plugins/File Metadata/extractors.py | 65 ++++++++++++++++++++++++++++ plugins/File Metadata/hplugin.json | 8 ++-- plugins/File Metadata/main.py | 56 +++++++++++++----------- plugins/File Metadata/readme.md | 30 +++++++++++++ 8 files changed, 165 insertions(+), 59 deletions(-) rename Example Plugin/{tests.py => test.py} (100%) create mode 100644 plugins/File Metadata/readme.md diff --git a/Example Plugin/tests.py b/Example Plugin/test.py similarity index 100% rename from Example Plugin/tests.py rename to Example Plugin/test.py diff --git a/README.md b/README.md index f458f09..aed7797 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,12 @@ -In this repository resides plugins for HappyPanda X +In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to +[the docs](https://happypandax.github.io/plugin.html#plugins). # How to download I recommend these tools to download a single directory from this repo: -- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* -- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* +- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder in this repo* - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) @@ -19,5 +20,5 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.1.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* +- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* diff --git a/build.py b/build.py index cb1b0fd..a4ba1c9 100644 --- a/build.py +++ b/build.py @@ -4,13 +4,14 @@ from urllib.parse import quote readme = """ -In this repository resides plugins for HappyPanda X +In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to +[the docs](https://happypandax.github.io/plugin.html#plugins). # How to download I recommend these tools to download a single directory from this repo: -- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder* -- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder* +- https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* +- https://kinolien.github.io/gitzip/ -- *Paste the url to the plugin folder in this repo* - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) diff --git a/plugins/File Metadata/common.py b/plugins/File Metadata/common.py index 4a065c9..bdcdf72 100644 --- a/plugins/File Metadata/common.py +++ b/plugins/File Metadata/common.py @@ -4,14 +4,15 @@ log = hpx.get_logger(__name__) -class DataType(enum.Enum): - eze = 1 - hdoujin = 2 +class DataType(enum.Flag): + eze = enum.auto() + hdoujin = enum.auto() + e_hentai_downloader = enum.auto() filetypes = ('.json', '.txt') filenames = { - "info.json": (DataType.eze, DataType.hdoujin), - "info.txt": (DataType.hdoujin,) + "info.json": DataType.eze | DataType.hdoujin, + "info.txt": DataType.hdoujin | DataType.e_hentai_downloader, } common_data = { @@ -44,23 +45,27 @@ class Extractor: def file_to_dict(self, fs: hpx.command.CoreFS) -> dict: """ """ - d = {} - log.debug(f"File ext: {fs.ext}") - kw = {} - if not fs.inside_archive: - kw['encoding'] = 'utf-8' - if fs.ext.lower() == '.json': - with fs.open("r", **kw) as f: - d = json.load(f) - elif fs.ext.lower() == '.txt': - with fs.open("r", **kw) as f: - for line in f.readlines(): - l = line.strip() - k, v = l.split(':', 1) - if k.strip(): - d[k.strip()] = v.strip() - else: - raise NotImplementedError(f"{fs.ext} filetype not supported yet") + try: + d = {} + log.debug(f"File ext: {fs.ext}") + kw = {} + if not fs.inside_archive: + kw['encoding'] = 'utf-8' + if fs.ext.lower() == '.json': + with fs.open("r", **kw) as f: + d = json.load(f) + elif fs.ext.lower() == '.txt': + with fs.open("r", **kw) as f: + for line in f.readlines(): + l = line.strip() + k, v = l.split(b':' if fs.inside_archive else ':', 1 ) + if k.strip(): + d[k.strip()] = v.strip() + else: + raise NotImplementedError(f"{fs.ext} filetype not supported yet") + except Exception: + log.warning("An error occured while trying to parse file into a dict") + raise ValueError return d def extract(self, filedata: dict) -> dict: diff --git a/plugins/File Metadata/extractors.py b/plugins/File Metadata/extractors.py index a2f1f4b..c26252a 100644 --- a/plugins/File Metadata/extractors.py +++ b/plugins/File Metadata/extractors.py @@ -128,3 +128,68 @@ def extract(self, filedata): return d common.register_extractor(HDoujin, common.DataType.hdoujin) + +class EHentaiDownloader(common.Extractor): + + def file_to_dict(self, fs): + """ + File is formatted weirdly so we just return {linenumber : line} + """ + d = {} + log.debug(f"File ext: {fs.ext}") + kw = {} + if not fs.inside_archive: + kw['encoding'] = "utf-8" + with fs.open("r", **kw) as f: + for num, line in enumerate(f.readlines(), 1): + if isinstance(line, bytes): + line = line.decode("utf-8") + d[num] = line + + # confirm it's the right file + if d and not "generated by e-hentai downloader" in d[len(d)].lower(): + d = None + return d + + def extract(self, filedata): + d = {} + if filedata: + log.debug("Expecting e-hentai downloader metadata file") + for linenum in sorted(filedata): + line = filedata[linenum].strip() + if not line: + continue + + if line.startswith("Language:"): + line = line.split(':', 1)[1] + d['language'] = common.capitalize_text(line.lower().split()[0]) + continue + + if line.startswith("Category:"): + line = line.split(':', 1)[1] + d['category'] = common.capitalize_text(line.lower()) + continue + + if line.startswith("> "): # tags + line = line[2:] # remove > + ns, tags = line.split(':', 1) + tags = tags.split(",") + d.setdefault("tags", {})[ns.strip()] = [t.strip() for t in tags] + continue + + if linenum in (1, 2, 3): # most likely a title or url, must be last because maybe it wasn't included + # ensure + if not filedata.get(3, "").startswith("http"): + continue + + if linenum == 3: + d.setdefault('urls', []).append(line) + else: + title_lang = "english" if linenum == 1 else "japanese" + nameparser = hpx.command.NameParser(line) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) + continue + return d + +common.register_extractor(EHentaiDownloader, common.DataType.e_hentai_downloader) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index 3d9b165..1a8bef9 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,12 +2,12 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "0.1.0b", - "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin", + "version": "0.2.0b", + "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", - "website": "https://github.com/happypandax/plugins", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", "entry": "main.py", "require": [ - "happypandax >= 0.1.2" + "happypandax >= 0.2.0" ] } \ No newline at end of file diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index e20214b..c1a5d83 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -11,29 +11,33 @@ } def get_common_data(datatypes, fpath): - assert isinstance(datatypes, tuple) + assert isinstance(datatypes, common.DataType) d = {} fpath = hpx.command.CoreFS(fpath) - for datatype in datatypes: - md = {} - - ex = common.extractors.get(datatype, None) - if ex: - fdata = ex.file_to_dict(fpath) - if fdata: - md.update(ex.extract(fdata)) - if md: - d.update(md) - break + for datatype in common.DataType: + if datatype & datatypes: + log.info(f"Attempting with {datatype}") + md = {} + + ex = common.extractors.get(datatype, None) + if ex: + try: + fdata = ex.file_to_dict(fpath) + except ValueError: + log.info(f"Skipping {datatype}") + continue + if fdata: + md.update(ex.extract(fdata)) + if md: + d.update(md) + break return d language_model = hpx.command.GetModelClass("Language") title_model = hpx.command.GetModelClass("Title") artist_model = hpx.command.GetModelClass("Artist") circle_model = hpx.command.GetModelClass("Circle") -category_model = hpx.command.GetModelClass("Category") -artistname_model = hpx.command.GetModelClass("ArtistName") url_model = hpx.command.GetModelClass("Url") namespacetags_model = hpx.command.GetModelClass("NamespaceTags") @@ -45,11 +49,13 @@ def apply_metadata(data, gallery): if isinstance(data['titles'], (list, tuple)): for t, l in data['titles']: + gtitle = None if t: gtitle = title_model(name=t) - gallery.titles.append(gtitle) if t and l: gtitle.language = language_model.as_unique(name=l) + if gtitle: + gallery.update("titles", gtitle) applied = True if isinstance(data['artists'], (list, tuple)): @@ -57,22 +63,20 @@ def apply_metadata(data, gallery): if a: gartist = artist_model.as_unique(name=a) if not gartist in gallery.artists: - gallery.artists.append(gartist) + gallery.update("artists", gartist) if a and c: for circlename in [x for x in c if x]: gcircle = circle_model.as_unique(name=circlename) if not gcircle in gartist.circles: - gartist.circles.append(gcircle) + gartist.update("circles", gcircle) applied = True if data['category']: - gcat = category_model.as_unique(name=data['category']) - gallery.category = gcat + gallery.update("category", name=data['category']) applied = True if data['language']: - glang = language_model.as_unique(name=data['language']) - gallery.language = glang + gallery.update("language", name=data['language']) applied = True if isinstance(data['tags'], (dict, list)): @@ -89,20 +93,20 @@ def apply_metadata(data, gallery): ns_tags.append(namespacetags_model.as_unique(ns=ns, tag=t)) for nstag in ns_tags: - if not nstag in gallery.tags: + if nstag not in gallery.tags: gallery.tags.append(nstag) applied = True if isinstance(data['pub_date'], (datetime.datetime, arrow.Arrow)): pub_date = data['pub_date'] - if isinstance(pub_date, datetime.datetime): - pub_date = arrow.Arrow.fromdatetime(pub_date) - gallery.pub_date = pub_date + gallery.update("pub_date", pub_date) applied = True if isinstance(data['urls'], (list, tuple)): + urls = [] for u in data['urls']: - gallery.urls.append(url_model(name=u)) + urls.append(url_model(name=u)) + gallery.update("urls", urls) applied = True return applied diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md new file mode 100644 index 0000000..1d4c774 --- /dev/null +++ b/plugins/File Metadata/readme.md @@ -0,0 +1,30 @@ +File Metadata +---------------------------- + +> This plugin extracts and applies metadata from a file accompanying a gallery folder or archive. + +This plugin supports extracting metadata from files produced by: + +- [eze](https://dnsev-h.github.io/eze/) + > - only supports JSON format and file must be named `info.json` +- [HDoujin Downloader](https://doujindownloader.com/) + > - all file versions are supported + > - supports both JSON and TXT formats + > - file must be named `info.json` or `info.txt` +- [E-Hentai-Downloader](https://github.com/ccloli/E-Hentai-Downloader) + > - supports only the file named `info.txt` + +# Extending + +... coming + +# Changelog + +- `0.2.0b` + - require HPX `0.2.0` + - use new api to update gallery data + - add support for E-Hentai-Downloader + - fix bug where `info.txt` in archive files would fail to get parsed + +- `0.1.0b` + - first version \ No newline at end of file From e879cfd0197967988841839e3c52c1f90dfe6b6f Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 27 Oct 2018 14:45:22 +0200 Subject: [PATCH 10/68] LGPL; --- .gitignore | 1 + Example Plugin/main.py | 3 + LICENSE | 829 +++++--------------------- plugins/EHentai Login/hplugin.json | 14 + plugins/EHentai Login/main.py | 173 ++++++ plugins/EHentai Login/test.py | 1 + plugins/EHentai Metadata/hplugin.json | 15 + plugins/EHentai Metadata/main.py | 252 ++++++++ plugins/EHentai Metadata/test.py | 1 + 9 files changed, 620 insertions(+), 669 deletions(-) create mode 100644 plugins/EHentai Login/hplugin.json create mode 100644 plugins/EHentai Login/main.py create mode 100644 plugins/EHentai Login/test.py create mode 100644 plugins/EHentai Metadata/hplugin.json create mode 100644 plugins/EHentai Metadata/main.py create mode 100644 plugins/EHentai Metadata/test.py diff --git a/.gitignore b/.gitignore index c55de92..1900a0c 100644 --- a/.gitignore +++ b/.gitignore @@ -174,6 +174,7 @@ venv.bak/ .mypy_cache/ ### VisualStudioCode ### +.vscode/ .vscode/* !.vscode/settings.json !.vscode/tasks.json diff --git a/Example Plugin/main.py b/Example Plugin/main.py index 68a8b62..30ea790 100644 --- a/Example Plugin/main.py +++ b/Example Plugin/main.py @@ -5,12 +5,15 @@ @hpx.subscribe("init") def inited(): + "Called when this plugin is initialised" pass @hpx.subscribe("disable") def disabled(): + "Called when this plugin has been disiabled" pass @hpx.subscribe("remove") def removed(): + "Called when this plugin is about to be removed" pass \ No newline at end of file diff --git a/LICENSE b/LICENSE index 9cecc1d..0a04128 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,165 @@ - GNU GENERAL PUBLIC LICENSE + GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. + 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. - - {one line to give the program's name and a brief idea of what it does.} - Copyright (C) {year} {name of author} - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -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: - - {project} Copyright (C) {year} {fullname} - 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 -. + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/plugins/EHentai Login/hplugin.json b/plugins/EHentai Login/hplugin.json new file mode 100644 index 0000000..8eae5f5 --- /dev/null +++ b/plugins/EHentai Login/hplugin.json @@ -0,0 +1,14 @@ +{ + "id": "d9b1d111-7250-4083-9efb-356fabbeada7", + "shortname": "ehentai-login", + "name": "EHentai Login", + "version": "0.0.0", + "description": "A plugin that can login to E-Hentai & ExHentai", + "author": "Twiddly", + "website": "www.pewpew.moe", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax > 0.2.0" + ] +} \ No newline at end of file diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py new file mode 100644 index 0000000..b79d0f2 --- /dev/null +++ b/plugins/EHentai Login/main.py @@ -0,0 +1,173 @@ +# main.py +from bs4 import BeautifulSoup +import __hpx__ as hpx +import gevent +import pickle +import os + +log = hpx.get_logger("main") + +current_user_name = "" +status_text = "" +response = None +user_dict = None + +save_file = os.path.join(hpx.constants.current_dir, '.info') + +default_delay = 4 + +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} + +MAIN_URLS = { + 'eh': "https://e-hentai.org", + 'ex': "https://exhentai.org" +} + +URLS = MAIN_URLS +URLS.update({ + 'login': "https://e-hentai.org/home.php" +}) + +@hpx.subscribe("init") +def inited(): + # set default delay values if not set + delays = hpx.get_setting("network", "delays", {}) + for u in MAIN_URLS.values(): + if u not in delays: + log.info(f"Setting delay on {u} requests to {default_delay}") + delays[u] = default_delay + hpx.update_setting("network", "delays", delays) + + # retrieve saved user info + if os.path.exists(save_file): + with open(save_file, "rb") as f: + user_dict = pickle.load(f) + if user_dict: + log.info(str(user_dict)) + login(user_dict, {}) + if response is not None: + log.info("Successfully re-logged in") + +@hpx.subscribe("disable") +def disabled(): + save_user_dict() + +@hpx.subscribe("remove") +def removed(): + pass + +@hpx.attach("Login.info") +def login_info(): + return hpx.command.LoginInfo( + identifier = "ehentai", + name = "EHentai", + parser = "", + sites = ("www.e-hentai.org", "www.exhentai.org"), + description = "Login to E-Hentai & ExHentai", + inputs = ( + {'name': 'IPB Member ID', 'type': str, 'mask': False}, + {'name': 'IPB Pass Hash', 'type': str, 'mask': True}, + {'name': 'ExHentai', 'type': bool} + ) + ) + +@hpx.attach("Login.login") +def login(userpass, options, capture="ehentai"): + global current_user_name + global status_text + global response + global user_dict + + user_dict = userpass + response = None + current_user_name = "" + + ipb_member = userpass.get('IPB Member ID') + ipb_pass = userpass.get('IPB Pass Hash') + if ipb_member and ipb_pass: + + cookies = {} + # get user input + cookies.update({ + 'ipb_member_id': userpass.get('IPB Member ID'), + 'ipb_pass_hash': userpass.get('IPB Pass Hash'), + }) + + # prepare request + req_props = hpx.command.RequestProperties( + session=True, + cookies=cookies, + headers=HEADERS + ) + + req = hpx.command.SingleGETRequest() + + # check ehentai.org/home.php + r = req.request(URLS['login'], req_props) + + if r.ok: + bad_access, msg = check_access(r) + status_text = msg + if not bad_access: + if userpass.get("ExHentai", True): + # check exhentai + r = req.request(URLS['ex'], req_props) + if r.ok: + bad_access, msg = check_access(r, ex=True) + else: + msg = "Could not access ExHentai" + + response = r + + current_user_name = userpass.get('IPB Member ID', "") + save_user_dict() + + else: + status_text = r.reason + + else: + status_text = "No user credentials provided" + + return response + +@hpx.attach("Login.status") +def status(options, capture="ehentai"): + return status_text + +@hpx.attach("Login.logged_in") +def logged_in(options, capture="ehentai"): + if response: + return True + return False + +@hpx.attach("Login.current_user") +def current_user(options, capture="ehentai"): + return current_user_name + +def check_access(r, ex=False): + msg = "" + bad_access = False + content_type = r.headers['content-type'] + text = r.text + if 'image/gif' in content_type: + msg = "No access to ExHentai" + elif 'text/html' and 'Your IP address has been' in text: + msg = text + bad_access = True + + if not bad_access and not ex: + soup = BeautifulSoup(text, "html.parser") + if soup.find("div", class_="homebox"): # we have access to home.php + pass + elif soup.find("form"): # login page + bad_access = True + msg = "Wrong credentials!" + return bad_access, msg + +def save_user_dict(): + global user_dict + + # save user info + if user_dict: + with open(save_file, "wb") as f: + user_dict = pickle.dump(user_dict, f) diff --git a/plugins/EHentai Login/test.py b/plugins/EHentai Login/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/EHentai Login/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json new file mode 100644 index 0000000..652dbcd --- /dev/null +++ b/plugins/EHentai Metadata/hplugin.json @@ -0,0 +1,15 @@ +{ + "id": "1572a650-5352-4d62-802f-8dfb983f9231", + "shortname": "ehentai-metadata", + "name": "EHentai Metadata", + "version": "0.0.0", + "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", + "author": "Twiddly", + "website": "www.pewpew.moe", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax > 0.2.0", + "ehentai-login" + ] +} \ No newline at end of file diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py new file mode 100644 index 0000000..19f768b --- /dev/null +++ b/plugins/EHentai Metadata/main.py @@ -0,0 +1,252 @@ +# main.py +from bs4 import BeautifulSoup +import __hpx__ as hpx +import gevent +import regex +import arrow +import datetime + +log = hpx.get_logger("main") + +match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?([^\.]?)" # http:// or https:// + www. +match_url_end = r"\/?$" + +urls_regex = { + 'eh_gallery': match_url_prefix + r"((? Date: Tue, 30 Oct 2018 22:41:00 +0100 Subject: [PATCH 11/68] finish plugins; --- plugins/EHentai Login/hplugin.json | 2 +- plugins/EHentai Login/main.py | 24 ++- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 300 ++++++++++++++++++++++---- 4 files changed, 278 insertions(+), 50 deletions(-) diff --git a/plugins/EHentai Login/hplugin.json b/plugins/EHentai Login/hplugin.json index 8eae5f5..cf054e1 100644 --- a/plugins/EHentai Login/hplugin.json +++ b/plugins/EHentai Login/hplugin.json @@ -9,6 +9,6 @@ "entry": "main.py", "test": "test.py", "require": [ - "happypandax > 0.2.0" + "happypandax >= 0.5.0" ] } \ No newline at end of file diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index b79d0f2..627422c 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -18,6 +18,11 @@ HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} +match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +match_url_end = r"\/?$" + +url_regex = match_url_prefix + r"((exhentai|(g\.)?e-hentai)\.org)" + match_url_end + MAIN_URLS = { 'eh': "https://e-hentai.org", 'ex': "https://exhentai.org" @@ -61,13 +66,13 @@ def login_info(): return hpx.command.LoginInfo( identifier = "ehentai", name = "EHentai", - parser = "", + parser = url_regex, sites = ("www.e-hentai.org", "www.exhentai.org"), - description = "Login to E-Hentai & ExHentai", + description = "Login to E-Hentai & EXHentai", inputs = ( {'name': 'IPB Member ID', 'type': str, 'mask': False}, {'name': 'IPB Pass Hash', 'type': str, 'mask': True}, - {'name': 'ExHentai', 'type': bool} + {'name': 'EXHentai', 'type': bool} ) ) @@ -109,13 +114,14 @@ def login(userpass, options, capture="ehentai"): bad_access, msg = check_access(r) status_text = msg if not bad_access: - if userpass.get("ExHentai", True): + if userpass.get("EXHentai", True): # check exhentai + req_props.session = r.session r = req.request(URLS['ex'], req_props) if r.ok: bad_access, msg = check_access(r, ex=True) else: - msg = "Could not access ExHentai" + msg = "Could not access EXHentai" response = r @@ -140,6 +146,10 @@ def logged_in(options, capture="ehentai"): return True return False +@hpx.attach("Login.response") +def response_(options, capture="ehentai"): + return response + @hpx.attach("Login.current_user") def current_user(options, capture="ehentai"): return current_user_name @@ -150,7 +160,7 @@ def check_access(r, ex=False): content_type = r.headers['content-type'] text = r.text if 'image/gif' in content_type: - msg = "No access to ExHentai" + msg = "No access to EXHentai" elif 'text/html' and 'Your IP address has been' in text: msg = text bad_access = True @@ -162,6 +172,8 @@ def check_access(r, ex=False): elif soup.find("form"): # login page bad_access = True msg = "Wrong credentials!" + if msg: + log.info(f"MSG: {msg}") return bad_access, msg def save_user_dict(): diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index 652dbcd..54f2673 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -9,7 +9,7 @@ "entry": "main.py", "test": "test.py", "require": [ - "happypandax > 0.2.0", + "happypandax >= 0.5.0", "ehentai-login" ] } \ No newline at end of file diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 19f768b..0a11b81 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -1,14 +1,19 @@ # main.py -from bs4 import BeautifulSoup import __hpx__ as hpx import gevent import regex import arrow import datetime +import os +import urllib +import html + +from bs4 import BeautifulSoup +from PIL import Image, ImageChops log = hpx.get_logger("main") -match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?([^\.]?)" # http:// or https:// + www. +match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. match_url_end = r"\/?$" urls_regex = { @@ -17,14 +22,27 @@ } urls = { - 'api': 'https://api.e-hentai.org/api.php' + 'eh': 'https://e-hentai.org', + 'ex': 'https://exhentai.org', + 'api': 'https://api.e-hentai.org/api.php', + 'title_search': '{url}/?f_doujinshi=1&f_manga=1&f_artistcg=1&f_gamecg=1&f_western=1&f_non-h=1&f_imageset=1&f_cosplay=1&f_asianporn=1&f_misc=1&f_search={title}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_srdd=2&f_sfl=on&f_sfu=on', + 'title_search_exp': '{url}/?f_doujinshi=1&f_manga=1&f_artistcg=1&f_gamecg=1&f_western=1&f_non-h=1&f_imageset=1&f_cosplay=1&f_asianporn=1&f_misc=1&f_search={title}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_sh=on&f_srdd=2&f_sfl=on&f_sfu=on' } HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} +plugin_config = { + 'filename_search': True, # use the filename/folder-name for searching instead of gallery title + 'expunged_galleries': False, # enable expunged galleries in results + 'remove_namespaces': True, # remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX + 'gallery_results_limit': 10, # maximum amount of galleries to return + 'blacklist_tags': [], # tags to ignore when updating tags + 'add_gallery_url': True, # add ehentai url to gallery +} + @hpx.subscribe("init") def inited(): - pass + plugin_config.update(hpx.get_plugin_config()) @hpx.subscribe("disable") def disabled(): @@ -73,30 +91,109 @@ def apply_eh(datatuple, item, options, capture="ehentai"): @hpx.attach("Metadata.query") def query_ex(item, url, options, capture="exhentai"): log.info("Querying exhentai for metadata") - return query(item, url, options, 'exhentai') + if not hpx.command.GetLoginStatus(urls['ex']): + log.info("Not logged in to exhentai, aborting...") + return tuple() + return query(item, url, options, urls['ex']) @hpx.attach("Metadata.apply") def apply_ex(datatuple, item, options, capture="exhentai"): log.info("Applying metadata from exhentai") return apply(datatuple, item, options) -def query(item, url, options, login_id='ehentai'): +def query(item, url, options, login_site=urls['eh']): + "Looks up on ehentai for matching item" mdata = [] + gurls = [] # url was provided if url: - log.info(f"Url provided: {url}") - g_id, g_token = parse_url(url) + log.info(f"url provided: {url} for {item}") + gurls.append(url) + else: # manually search for id + log.info(f"url not provided for {item}") + ex_login = hpx.command.GetLoginStatus(login_site) if "exhentai" in login_site else False + login_session = None + if ex_login: + login_session = hpx.command.GetLoginSession(login_site) + if login_site == 'exhentai': + log.info(f"logged in to exhentai: {ex_login}") + if (ex_login if "exhentai" in login_site else True): + # search with title + i_title = "" + i_hash = "" + if plugin_config.get("filename_search"): + sources = item.get_sources() + if sources: + # get folder/file name + i_title = os.path.split(sources[0])[1] + # remove ext + i_title = os.path.splitext(i_title)[0] + else: + if item.titles: + i_title = item.titles[0].name # make user choice + if i_title: + gurls = title_search(i_title, ex='exhentai' in login_site, session=login_session) + + # search with hash + if not gurls: + pass + + log.info(f"found {len(gurls)} urls for item: {item}") + log.debug(f"{gurls}") + for u in gurls: + g_id, g_token = parse_url(u) if g_id and g_token: mdata.append(hpx.command.MetadataData( data={ 'gallery': [g_id, g_token], - 'apply_url': False, + 'gallery_url': u, + 'apply_url': True, })) - else: # manually search for id - if (hpx.command.GetLoginStatus(login_id) if login_id == 'exhentai' else True): - pass return tuple(mdata) +def title_search(title, ex=True, session=None): + "Searches on ehentai for galleries with given title, returns a list of matching gallery urls" + if plugin_config.get("expunged_galleries"): + eh_url = urls['title_search_exp'] + else: + eh_url = urls['title_search'] + log.debug(f"searching with title: {title}") + f_eh_url = eh_url.format( + url=urls['ex'] if ex else urls['eh'], + title=urllib.parse.quote_plus(title) + ) + log.debug(f"final url: {f_eh_url}") + return eh_page_results(f_eh_url, session=session) + +def eh_page_results(eh_page_url, limit=None, session=None): + "Opens eh page, parses for results, and then returns found urls" + found_urls = [] + if limit is None: + limit = plugin_config.get("gallery_results_limit") + + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + if session: + req_props.session = session + log.debug(f"COOKIES: {session.cookies}") + r = hpx.command.SingleGETRequest().request(eh_page_url, req_props) + soup = BeautifulSoup(r.text, "html.parser") + thumb_view = False + dmi_div = soup.find("div", id="dmi") + if dmi_div and dmi_div.a and "list" in str(dmi_div.a.string).lower(): + thumb_view = True + if thumb_view: + results = soup.findAll("div", class_="id2", limit=limit) + else: + results = soup.findAll("div", class_="it5", limit=limit) + # str(x.a.string) + found_urls = [x.a['href'] for x in results] + if not found_urls: + log.debug(f"HTML: {r.text}") + return found_urls + def parse_url(url): "Parses url into a tuple of gallery id and token" gallery_id = None @@ -119,8 +216,12 @@ def apply(datatuple, item, options): 'namespace': 1 } + urls_to_apply = [] + for d in datatuple: eh_data['gidlist'].append(d.data['gallery']) + if d.data['apply_url']: + urls_to_apply.append(d.data['gallery_url']) # prepare request req_props = hpx.command.RequestProperties( @@ -132,29 +233,7 @@ def apply(datatuple, item, options): response = r.json if response and not 'error' in response: for gdata in response['gmetadata']: - mdata = {} - if hpx.get_setting('metadata', 'replace_metadata'): - item.titles = [] - item.artists = [] - item.tags = [] - - mdata['titles'] = [] - mdata['titles'].append((gdata['title'], 'english')) - mdata['titles'].append((gdata['title_jpn'], 'japanese')) - mdata['category'] = gdata['category'] - mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) - mdata['language'] = "japanese" - mdata['tags'] = {} - for nstag in gdata['tags']: - ns = None - if ':' in nstag: - ns, t = nstag.split(':', 1) - else: - t = nstag - mdata['tags'].setdefault(ns, []).append(t) - if ns == 'language' and t != 'translated': - mdata['language'] = t - + mdata = filter_metadata(gdata, item, urls_to_apply=urls_to_apply) applied = apply_metadata(mdata, item) elif response: @@ -162,18 +241,122 @@ def apply(datatuple, item, options): log.info(f"Applied: {applied}") return applied +def capitalize_text(text): + """ + better str.capitalize + """ + return " ".join(x.capitalize() for x in text.strip().split()) + +def filter_metadata(gdata, item, urls_to_apply=None): + mdata = {} + replace_metadata = hpx.get_setting('metadata', 'replace_metadata') + if replace_metadata: + item.titles = [] + item.artists = [] + item.tags = [] + + if replace_metadata: + mdata['titles'] = [] + mdata['titles'].append((gdata['title'], 'english')) + mdata['titles'].append((gdata['title_jpn'], 'japanese')) + else: + t = [] + if not item.title_by_language("english"): + t.append((gdata['title'], 'english')) + if not item.title_by_language("japanese"): + t.append((gdata['title_jpn'], 'japanese')) + if t: + mdata['titles'] = t + + if replace_metadata: + mdata['category'] = gdata['category'] + elif not item.category: + mdata['category'] = gdata['category'] + + if replace_metadata: + mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + elif not item.pub_date: + mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + + lang = "english" + if item.language: + lang = item.language.name + + artists = [] + circles = [] + parodies = [] + + extra_namespaces = ("artist", "parody", "group", "language") + mdata['tags'] = {} + for nstag in gdata['tags']: + + blacklist_tags = plugin_config.get("blacklist_tags") + if blacklist_tags and nstag in blacklist_tags: + continue + + ns = None + if ':' in nstag: + ns, t = nstag.split(':', 1) + else: + t = nstag + + if ns == 'language' and t != 'translated': + lang = t + elif ns == "artist": + artists.append(t) + elif ns == "group": + circles.append(t) + elif ns == "parody": + parodies.append(t) + + if not (plugin_config.get("remove_namespaces") and ns in extra_namespaces): + mdata['tags'].setdefault(ns, []).append(t) + else: + log.debug(f"removing namespace {ns}") + + log.debug(f"tags: {mdata['tags']}") + + if replace_metadata: + mdata['language'] = lang + elif not item.language: + mdata['language'] = lang + + if parodies: + if replace_metadata: + item.parodies = [] + mdata['parodies'] = parodies + elif not item.parodies: + mdata['parodies'] = parodies + + if artists: + a_circles = [] + for a in artists: + a_circles.append((a, tuple(circles))) + if replace_metadata: + item.artists = [] + mdata['artists'] = a_circles + elif not item.artists: + mdata['artists'] = a_circles + + if urls_to_apply: + mdata['urls'] = urls_to_apply + + return mdata + language_model = hpx.command.GetModelClass("Language") title_model = hpx.command.GetModelClass("Title") artist_model = hpx.command.GetModelClass("Artist") +parody_model = hpx.command.GetModelClass("Parody") circle_model = hpx.command.GetModelClass("Circle") url_model = hpx.command.GetModelClass("Url") namespacetags_model = hpx.command.GetModelClass("NamespaceTags") -def apply_metadata(data, gallery): +def apply_metadata(data, gallery, replace=False): """ data = { 'titles': None, # [(title, language),...] 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] 'category': None, 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} 'pub_date': None, # DateTime object @@ -184,39 +367,53 @@ def apply_metadata(data, gallery): applied = False - log.debug("data:") - log.debug(f"{data}") + log.debug(f"data: {data}") if isinstance(data.get('titles'), (list, tuple)): for t, l in data['titles']: gtitle = None if t: + t = html.unescape(t) gtitle = title_model(name=t) if t and l: gtitle.language = language_model.as_unique(name=l) if gtitle: gallery.update("titles", gtitle) + log.debug("applied titles") applied = True if isinstance(data.get('artists'), (list, tuple)): for a, c in data['artists']: if a: - gartist = artist_model.as_unique(name=a) + gartist = artist_model.as_unique(name=capitalize_text(a)) if not gartist in gallery.artists: gallery.update("artists", gartist) if a and c: for circlename in [x for x in c if x]: - gcircle = circle_model.as_unique(name=circlename) + gcircle = circle_model.as_unique(name=capitalize_text(circlename)) if not gcircle in gartist.circles: gartist.update("circles", gcircle) + log.debug("applied artists") + applied = True + + if isinstance(data.get('parodies'), (list, tuple)): + for p in data['parodies']: + if p: + gparody = parody_model.as_unique(name=capitalize_text(p)) + if not gparody in gallery.parodies: + gallery.update("parodies", gparody) + + log.debug("applied parodies") applied = True if data.get('category'): gallery.update("category", name=data['category']) + log.debug("applied category") applied = True if data.get('language'): gallery.update("language", name=data['language']) + log.debug("applied language") applied = True if isinstance(data.get('tags'), (dict, list)): @@ -235,18 +432,37 @@ def apply_metadata(data, gallery): for nstag in ns_tags: if nstag not in gallery.tags: gallery.tags.append(nstag) + log.debug("applied tags") applied = True if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): pub_date = data['pub_date'] gallery.update("pub_date", pub_date) + log.debug("applied pub_date") applied = True if isinstance(data.get('urls'), (list, tuple)): + existing_urls = [x.name.lower() for x in gallery.urls] urls = [] for u in data['urls']: - urls.append(url_model(name=u)) + if u.lower() not in existing_urls: + urls.append(url_model(name=u)) gallery.update("urls", urls) + log.debug("applied urls") applied = True - return applied \ No newline at end of file + return applied + +def is_image_greyscale(filepath): + "Check if image is monochrome (1 channel or 3 identical channels)" + im = Image.open(filepath).convert("RGB") + if im.mode not in ("L", "RGB"): + return False + + if im.mode == "RGB": + rgb = im.split() + if ImageChops.difference(rgb[0],rgb[1]).getextrema()[1] != 0: + return False + if ImageChops.difference(rgb[0],rgb[2]).getextrema()[1] != 0: + return False + return True \ No newline at end of file From 87b8797e7bba632d04e9116d7079666cb10f0002 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 30 Oct 2018 23:36:05 +0100 Subject: [PATCH 12/68] add readmes; --- plugins/EHentai Login/hplugin.json | 4 ++-- plugins/EHentai Metadata/hplugin.json | 4 ++-- plugins/EHentai Metadata/main.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/plugins/EHentai Login/hplugin.json b/plugins/EHentai Login/hplugin.json index cf054e1..b462e54 100644 --- a/plugins/EHentai Login/hplugin.json +++ b/plugins/EHentai Login/hplugin.json @@ -2,10 +2,10 @@ "id": "d9b1d111-7250-4083-9efb-356fabbeada7", "shortname": "ehentai-login", "name": "EHentai Login", - "version": "0.0.0", + "version": "0.1.0b", "description": "A plugin that can login to E-Hentai & ExHentai", "author": "Twiddly", - "website": "www.pewpew.moe", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login", "entry": "main.py", "test": "test.py", "require": [ diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index 54f2673..eb03a69 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,10 +2,10 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "0.0.0", + "version": "0.1.0b", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", - "website": "www.pewpew.moe", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", "entry": "main.py", "test": "test.py", "require": [ diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 0a11b81..54fc8df 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -147,7 +147,7 @@ def query(item, url, options, login_site=urls['eh']): data={ 'gallery': [g_id, g_token], 'gallery_url': u, - 'apply_url': True, + 'apply_url': plugin_config.get('add_gallery_url', True), })) return tuple(mdata) From 18cf3d30372637e09a11d3c563eb0857ed74ea4c Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 30 Oct 2018 23:38:46 +0100 Subject: [PATCH 13/68] EHentai Login & Ehentai Metadata (#7) * add EHentai Login and EHentai Metadata plugins; * LGPL; --- .gitignore | 1 + Example Plugin/main.py | 3 + LICENSE | 829 +++++--------------------- plugins/EHentai Login/hplugin.json | 14 + plugins/EHentai Login/main.py | 185 ++++++ plugins/EHentai Login/test.py | 1 + plugins/EHentai Metadata/hplugin.json | 15 + plugins/EHentai Metadata/main.py | 468 +++++++++++++++ plugins/EHentai Metadata/test.py | 1 + 9 files changed, 848 insertions(+), 669 deletions(-) create mode 100644 plugins/EHentai Login/hplugin.json create mode 100644 plugins/EHentai Login/main.py create mode 100644 plugins/EHentai Login/test.py create mode 100644 plugins/EHentai Metadata/hplugin.json create mode 100644 plugins/EHentai Metadata/main.py create mode 100644 plugins/EHentai Metadata/test.py diff --git a/.gitignore b/.gitignore index c55de92..1900a0c 100644 --- a/.gitignore +++ b/.gitignore @@ -174,6 +174,7 @@ venv.bak/ .mypy_cache/ ### VisualStudioCode ### +.vscode/ .vscode/* !.vscode/settings.json !.vscode/tasks.json diff --git a/Example Plugin/main.py b/Example Plugin/main.py index 68a8b62..30ea790 100644 --- a/Example Plugin/main.py +++ b/Example Plugin/main.py @@ -5,12 +5,15 @@ @hpx.subscribe("init") def inited(): + "Called when this plugin is initialised" pass @hpx.subscribe("disable") def disabled(): + "Called when this plugin has been disiabled" pass @hpx.subscribe("remove") def removed(): + "Called when this plugin is about to be removed" pass \ No newline at end of file diff --git a/LICENSE b/LICENSE index 9cecc1d..0a04128 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,165 @@ - GNU GENERAL PUBLIC LICENSE + GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 - Copyright (C) 2007 Free Software Foundation, Inc. + 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. - - {one line to give the program's name and a brief idea of what it does.} - Copyright (C) {year} {name of author} - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -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: - - {project} Copyright (C) {year} {fullname} - 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 -. + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser 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 +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/plugins/EHentai Login/hplugin.json b/plugins/EHentai Login/hplugin.json new file mode 100644 index 0000000..b462e54 --- /dev/null +++ b/plugins/EHentai Login/hplugin.json @@ -0,0 +1,14 @@ +{ + "id": "d9b1d111-7250-4083-9efb-356fabbeada7", + "shortname": "ehentai-login", + "name": "EHentai Login", + "version": "0.1.0b", + "description": "A plugin that can login to E-Hentai & ExHentai", + "author": "Twiddly", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.5.0" + ] +} \ No newline at end of file diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py new file mode 100644 index 0000000..627422c --- /dev/null +++ b/plugins/EHentai Login/main.py @@ -0,0 +1,185 @@ +# main.py +from bs4 import BeautifulSoup +import __hpx__ as hpx +import gevent +import pickle +import os + +log = hpx.get_logger("main") + +current_user_name = "" +status_text = "" +response = None +user_dict = None + +save_file = os.path.join(hpx.constants.current_dir, '.info') + +default_delay = 4 + +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} + +match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +match_url_end = r"\/?$" + +url_regex = match_url_prefix + r"((exhentai|(g\.)?e-hentai)\.org)" + match_url_end + +MAIN_URLS = { + 'eh': "https://e-hentai.org", + 'ex': "https://exhentai.org" +} + +URLS = MAIN_URLS +URLS.update({ + 'login': "https://e-hentai.org/home.php" +}) + +@hpx.subscribe("init") +def inited(): + # set default delay values if not set + delays = hpx.get_setting("network", "delays", {}) + for u in MAIN_URLS.values(): + if u not in delays: + log.info(f"Setting delay on {u} requests to {default_delay}") + delays[u] = default_delay + hpx.update_setting("network", "delays", delays) + + # retrieve saved user info + if os.path.exists(save_file): + with open(save_file, "rb") as f: + user_dict = pickle.load(f) + if user_dict: + log.info(str(user_dict)) + login(user_dict, {}) + if response is not None: + log.info("Successfully re-logged in") + +@hpx.subscribe("disable") +def disabled(): + save_user_dict() + +@hpx.subscribe("remove") +def removed(): + pass + +@hpx.attach("Login.info") +def login_info(): + return hpx.command.LoginInfo( + identifier = "ehentai", + name = "EHentai", + parser = url_regex, + sites = ("www.e-hentai.org", "www.exhentai.org"), + description = "Login to E-Hentai & EXHentai", + inputs = ( + {'name': 'IPB Member ID', 'type': str, 'mask': False}, + {'name': 'IPB Pass Hash', 'type': str, 'mask': True}, + {'name': 'EXHentai', 'type': bool} + ) + ) + +@hpx.attach("Login.login") +def login(userpass, options, capture="ehentai"): + global current_user_name + global status_text + global response + global user_dict + + user_dict = userpass + response = None + current_user_name = "" + + ipb_member = userpass.get('IPB Member ID') + ipb_pass = userpass.get('IPB Pass Hash') + if ipb_member and ipb_pass: + + cookies = {} + # get user input + cookies.update({ + 'ipb_member_id': userpass.get('IPB Member ID'), + 'ipb_pass_hash': userpass.get('IPB Pass Hash'), + }) + + # prepare request + req_props = hpx.command.RequestProperties( + session=True, + cookies=cookies, + headers=HEADERS + ) + + req = hpx.command.SingleGETRequest() + + # check ehentai.org/home.php + r = req.request(URLS['login'], req_props) + + if r.ok: + bad_access, msg = check_access(r) + status_text = msg + if not bad_access: + if userpass.get("EXHentai", True): + # check exhentai + req_props.session = r.session + r = req.request(URLS['ex'], req_props) + if r.ok: + bad_access, msg = check_access(r, ex=True) + else: + msg = "Could not access EXHentai" + + response = r + + current_user_name = userpass.get('IPB Member ID', "") + save_user_dict() + + else: + status_text = r.reason + + else: + status_text = "No user credentials provided" + + return response + +@hpx.attach("Login.status") +def status(options, capture="ehentai"): + return status_text + +@hpx.attach("Login.logged_in") +def logged_in(options, capture="ehentai"): + if response: + return True + return False + +@hpx.attach("Login.response") +def response_(options, capture="ehentai"): + return response + +@hpx.attach("Login.current_user") +def current_user(options, capture="ehentai"): + return current_user_name + +def check_access(r, ex=False): + msg = "" + bad_access = False + content_type = r.headers['content-type'] + text = r.text + if 'image/gif' in content_type: + msg = "No access to EXHentai" + elif 'text/html' and 'Your IP address has been' in text: + msg = text + bad_access = True + + if not bad_access and not ex: + soup = BeautifulSoup(text, "html.parser") + if soup.find("div", class_="homebox"): # we have access to home.php + pass + elif soup.find("form"): # login page + bad_access = True + msg = "Wrong credentials!" + if msg: + log.info(f"MSG: {msg}") + return bad_access, msg + +def save_user_dict(): + global user_dict + + # save user info + if user_dict: + with open(save_file, "wb") as f: + user_dict = pickle.dump(user_dict, f) diff --git a/plugins/EHentai Login/test.py b/plugins/EHentai Login/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/EHentai Login/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json new file mode 100644 index 0000000..eb03a69 --- /dev/null +++ b/plugins/EHentai Metadata/hplugin.json @@ -0,0 +1,15 @@ +{ + "id": "1572a650-5352-4d62-802f-8dfb983f9231", + "shortname": "ehentai-metadata", + "name": "EHentai Metadata", + "version": "0.1.0b", + "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", + "author": "Twiddly", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.5.0", + "ehentai-login" + ] +} \ No newline at end of file diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py new file mode 100644 index 0000000..54fc8df --- /dev/null +++ b/plugins/EHentai Metadata/main.py @@ -0,0 +1,468 @@ +# main.py +import __hpx__ as hpx +import gevent +import regex +import arrow +import datetime +import os +import urllib +import html + +from bs4 import BeautifulSoup +from PIL import Image, ImageChops + +log = hpx.get_logger("main") + +match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +match_url_end = r"\/?$" + +urls_regex = { + 'eh_gallery': match_url_prefix + r"((? Date: Tue, 30 Oct 2018 23:40:23 +0100 Subject: [PATCH 14/68] update readme; --- README.md | 4 +++- plugins/EHentai Login/readme.md | 22 +++++++++++++++++++ plugins/EHentai Metadata/readme.md | 35 ++++++++++++++++++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 plugins/EHentai Login/readme.md create mode 100644 plugins/EHentai Metadata/readme.md diff --git a/README.md b/README.md index aed7797..124f73a 100644 --- a/README.md +++ b/README.md @@ -20,5 +20,7 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze and hdoujin* +- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.1.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* +- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* +- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* diff --git a/plugins/EHentai Login/readme.md b/plugins/EHentai Login/readme.md new file mode 100644 index 0000000..25aaf7b --- /dev/null +++ b/plugins/EHentai Login/readme.md @@ -0,0 +1,22 @@ +EHentai Login +---------------------------- + +> This plugin can log-in to E-Hentai & ExHentai + +Set the **EXHentai** option to true through your client when logging in to also check for ExHentai access. + +The user has access to both E-Hentai and ExHentai if no message is displayed on a succesful log-in. +Else the message `No access to EXHentai` will be displayed. + +To find your **IPB Member ID** and **IPB Pass Hash**, follow these steps (should work on all browsers): +1. Navigate to e-hentai.org (needs to be logged in) or exhentai.org +2. Right click on page => Inpect element +3. Go on **Console** tab +4. Write: `document.cookie` +5. A line of values should appear that correspond to active cookies +6. Look for the `ipb_member_id` and `ipb_pass_hash` values + +# Changelog + +- `0.1.0b` + - first version \ No newline at end of file diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md new file mode 100644 index 0000000..e8008d7 --- /dev/null +++ b/plugins/EHentai Metadata/readme.md @@ -0,0 +1,35 @@ +EHentai Metadata +---------------------------- + +> This plugin fetches metadata from E-Hentai & ExHentai + +**IMPORTANT:** This plugin requires the [EHentai Login](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) plugin to be present + +## Configuration + +Configure this plugin by adding `ehentai-metadata` to the `plugin.config` namespace in your `config.yaml`: +```yaml +plugin: + config: + ehentai-metadata: + option1: True + option2: + - item 1 + - item 2 +``` + +#### Available options + +Name | Default | Description +--- | --- | --- +`filename_search` | `true` | use the filename/folder-name for searching instead of gallery title +`expunged_galleries` | `false` | enable expunged galleries in results +`remove_namespaces` | `true` | remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX +`gallery_results_limit` | `10` | maximum amount of galleries to return +`blacklist_tags` | `[]` | tags to ignore when updating tags +`add_gallery_url` | `true` | add ehentai url to gallery + +# Changelog + +- `0.1.0b` + - first version \ No newline at end of file From 57863524f15ce7283b5285effa5bb81bc59a726b Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 30 Oct 2018 23:46:45 +0100 Subject: [PATCH 15/68] update readme; --- plugins/EHentai Metadata/readme.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index e8008d7..ecae80d 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -26,7 +26,7 @@ Name | Default | Description `expunged_galleries` | `false` | enable expunged galleries in results `remove_namespaces` | `true` | remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX `gallery_results_limit` | `10` | maximum amount of galleries to return -`blacklist_tags` | `[]` | tags to ignore when updating tags +`blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` strings `add_gallery_url` | `true` | add ehentai url to gallery # Changelog From 078dafcf51f876e63c10d464060b6c0bbb59920d Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 30 Oct 2018 23:52:05 +0100 Subject: [PATCH 16/68] update readme; --- plugins/EHentai Metadata/readme.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index ecae80d..962c344 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -29,6 +29,10 @@ Name | Default | Description `blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` strings `add_gallery_url` | `true` | add ehentai url to gallery +## Things yet to be implemented + +- File similarity search + # Changelog - `0.1.0b` From 1f57f277a94cd61b3b3c9dbfc87c9ecf0b284fae Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 1 Nov 2018 00:23:02 +0100 Subject: [PATCH 17/68] add option --- plugins/EHentai Metadata/main.py | 35 +++++++++++++++++++++++------- plugins/EHentai Metadata/readme.md | 2 ++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 54fc8df..4a307e1 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -38,6 +38,7 @@ 'gallery_results_limit': 10, # maximum amount of galleries to return 'blacklist_tags': [], # tags to ignore when updating tags 'add_gallery_url': True, # add ehentai url to gallery + 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default } @hpx.subscribe("init") @@ -104,11 +105,11 @@ def apply_ex(datatuple, item, options, capture="exhentai"): def query(item, url, options, login_site=urls['eh']): "Looks up on ehentai for matching item" mdata = [] - gurls = [] + gurls = [] # tuple of (title, url) # url was provided if url: log.info(f"url provided: {url} for {item}") - gurls.append(url) + gurls.append((url, url)) else: # manually search for id log.info(f"url not provided for {item}") ex_login = hpx.command.GetLoginStatus(login_site) if "exhentai" in login_site else False @@ -139,8 +140,23 @@ def query(item, url, options, login_site=urls['eh']): pass log.info(f"found {len(gurls)} urls for item: {item}") + + # list is sorted by date added so we reverse it + gurls.reverse() + log.debug(f"{gurls}") - for u in gurls: + final_gurls = [] + pref_lang = plugin_config.get('preferred_language') + if pref_lang: + for t in gurls: + if pref_lang.lower() in t[0].lower(): + final_gurls.insert(0, t) + continue + final_gurls.append(t) + else: + final_gurls = gurls + + for t, u in final_gurls: g_id, g_token = parse_url(u) if g_id and g_token: mdata.append(hpx.command.MetadataData( @@ -152,7 +168,7 @@ def query(item, url, options, login_site=urls['eh']): return tuple(mdata) def title_search(title, ex=True, session=None): - "Searches on ehentai for galleries with given title, returns a list of matching gallery urls" + "Searches on ehentai for galleries with given title, returns a list of (title, matching gallery urls)" if plugin_config.get("expunged_galleries"): eh_url = urls['title_search_exp'] else: @@ -166,7 +182,7 @@ def title_search(title, ex=True, session=None): return eh_page_results(f_eh_url, session=session) def eh_page_results(eh_page_url, limit=None, session=None): - "Opens eh page, parses for results, and then returns found urls" + "Opens eh page, parses for results, and then returns list of (title, url)" found_urls = [] if limit is None: limit = plugin_config.get("gallery_results_limit") @@ -189,7 +205,8 @@ def eh_page_results(eh_page_url, limit=None, session=None): else: results = soup.findAll("div", class_="it5", limit=limit) # str(x.a.string) - found_urls = [x.a['href'] for x in results] + found_urls = [(str(x.a.string), x.a['href']) for x in results] # title, url + if not found_urls: log.debug(f"HTML: {r.text}") return found_urls @@ -254,6 +271,8 @@ def filter_metadata(gdata, item, urls_to_apply=None): item.titles = [] item.artists = [] item.tags = [] + # flush is required so items are removed from the db + hpx.command.GetSession().flush() if replace_metadata: mdata['titles'] = [] @@ -278,8 +297,8 @@ def filter_metadata(gdata, item, urls_to_apply=None): elif not item.pub_date: mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) - lang = "english" - if item.language: + lang = "japanese" # def lang + if not replace_metadata and item.language: lang = item.language.name artists = [] diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index 962c344..845b787 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -28,6 +28,8 @@ Name | Default | Description `gallery_results_limit` | `10` | maximum amount of galleries to return `blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` strings `add_gallery_url` | `true` | add ehentai url to gallery +`preferred_language` | `english` | preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default + ## Things yet to be implemented From 3665a2ed11fc1b68295d968ee6f259ea7092aea4 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 1 Nov 2018 00:56:05 +0100 Subject: [PATCH 18/68] bump to 0.2.0b; --- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/readme.md | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index eb03a69..b7e754c 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "0.1.0b", + "version": "0.2.0b", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index 845b787..84391aa 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -37,5 +37,7 @@ Name | Default | Description # Changelog +- `0.2.0b` + - added `preferred_language` option - `0.1.0b` - first version \ No newline at end of file From e79884001505b78a0d82f0139b42af471525cee1 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 1 Nov 2018 10:41:19 +0100 Subject: [PATCH 19/68] increase default delay limit; --- plugins/EHentai Login/hplugin.json | 2 +- plugins/EHentai Login/main.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugins/EHentai Login/hplugin.json b/plugins/EHentai Login/hplugin.json index b462e54..ffba242 100644 --- a/plugins/EHentai Login/hplugin.json +++ b/plugins/EHentai Login/hplugin.json @@ -2,7 +2,7 @@ "id": "d9b1d111-7250-4083-9efb-356fabbeada7", "shortname": "ehentai-login", "name": "EHentai Login", - "version": "0.1.0b", + "version": "0.2.0b", "description": "A plugin that can login to E-Hentai & ExHentai", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login", diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 627422c..53e7887 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -14,7 +14,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 4 +default_delay = 7 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} @@ -37,7 +37,7 @@ def inited(): # set default delay values if not set delays = hpx.get_setting("network", "delays", {}) - for u in MAIN_URLS.values(): + for u in (MAIN_URLS['ex'], MAIN_URLS['eh'])): if u not in delays: log.info(f"Setting delay on {u} requests to {default_delay}") delays[u] = default_delay From e07a524b9450521340e95c13e7f0670bea1c3d79 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 3 Nov 2018 11:01:23 +0100 Subject: [PATCH 20/68] increase default delay to 9; --- plugins/EHentai Login/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 53e7887..086c3b6 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -14,7 +14,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 7 +default_delay = 9 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} @@ -37,7 +37,7 @@ def inited(): # set default delay values if not set delays = hpx.get_setting("network", "delays", {}) - for u in (MAIN_URLS['ex'], MAIN_URLS['eh'])): + for u in (MAIN_URLS['ex'], MAIN_URLS['eh']): if u not in delays: log.info(f"Setting delay on {u} requests to {default_delay}") delays[u] = default_delay From f3e221e03547cc6592717f92219fbee4a34a3ab8 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 3 Nov 2018 11:06:33 +0100 Subject: [PATCH 21/68] update readme; --- README.md | 2 +- plugins/EHentai Login/readme.md | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 124f73a..842d56c 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.1.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* +- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* - [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* - [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* diff --git a/plugins/EHentai Login/readme.md b/plugins/EHentai Login/readme.md index 25aaf7b..e28aba8 100644 --- a/plugins/EHentai Login/readme.md +++ b/plugins/EHentai Login/readme.md @@ -18,5 +18,8 @@ To find your **IPB Member ID** and **IPB Pass Hash**, follow these steps (should # Changelog +- `0.2.0b` + - increase default delay limit on EH requests to `9` from `4` secs, this value can be tweaked in `network.delays` inside your`config.yaml` + - `0.1.0b` - first version \ No newline at end of file From fa5903c53fe4393a76b8d0c41edc3105a11ddfc9 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 3 Nov 2018 11:07:19 +0100 Subject: [PATCH 22/68] Update File Metadata & EHentai Login plugins (#9) Update EHentai Login plugin --- README.md | 2 +- plugins/EHentai Login/hplugin.json | 2 +- plugins/EHentai Login/main.py | 4 ++-- plugins/EHentai Login/readme.md | 3 +++ 4 files changed, 7 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 124f73a..842d56c 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.1.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* +- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* - [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* - [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* diff --git a/plugins/EHentai Login/hplugin.json b/plugins/EHentai Login/hplugin.json index b462e54..ffba242 100644 --- a/plugins/EHentai Login/hplugin.json +++ b/plugins/EHentai Login/hplugin.json @@ -2,7 +2,7 @@ "id": "d9b1d111-7250-4083-9efb-356fabbeada7", "shortname": "ehentai-login", "name": "EHentai Login", - "version": "0.1.0b", + "version": "0.2.0b", "description": "A plugin that can login to E-Hentai & ExHentai", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login", diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 627422c..086c3b6 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -14,7 +14,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 4 +default_delay = 9 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} @@ -37,7 +37,7 @@ def inited(): # set default delay values if not set delays = hpx.get_setting("network", "delays", {}) - for u in MAIN_URLS.values(): + for u in (MAIN_URLS['ex'], MAIN_URLS['eh']): if u not in delays: log.info(f"Setting delay on {u} requests to {default_delay}") delays[u] = default_delay diff --git a/plugins/EHentai Login/readme.md b/plugins/EHentai Login/readme.md index 25aaf7b..e28aba8 100644 --- a/plugins/EHentai Login/readme.md +++ b/plugins/EHentai Login/readme.md @@ -18,5 +18,8 @@ To find your **IPB Member ID** and **IPB Pass Hash**, follow these steps (should # Changelog +- `0.2.0b` + - increase default delay limit on EH requests to `9` from `4` secs, this value can be tweaked in `network.delays` inside your`config.yaml` + - `0.1.0b` - first version \ No newline at end of file From 42d58af8aa305b48486d8119c18734eb33b6888a Mon Sep 17 00:00:00 2001 From: Twiddly Date: Mon, 5 Nov 2018 03:21:56 +0100 Subject: [PATCH 23/68] change default delay to 6 secs; update ehentai metadata; --- plugins/EHentai Login/main.py | 2 +- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 10 ++++++++++ plugins/EHentai Metadata/readme.md | 3 +++ 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 086c3b6..510b1f1 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -14,7 +14,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 9 +default_delay = 6 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index eb03a69..b7e754c 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "0.1.0b", + "version": "0.2.0b", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 54fc8df..7018085 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -16,6 +16,8 @@ match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. match_url_end = r"\/?$" +default_delay = 6 + urls_regex = { 'eh_gallery': match_url_prefix + r"((? Date: Mon, 5 Nov 2018 03:30:14 +0100 Subject: [PATCH 24/68] build --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 842d56c..b85d162 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,8 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins +- [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from Panda.Chaika* - [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* -- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* +- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* - [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* From e1995fb91f3ae3e92f23cef4a5e1e692dc575208 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Mon, 5 Nov 2018 03:32:51 +0100 Subject: [PATCH 25/68] Update EHentai Metadata plugin (#11) * add delay on `https://api.e-hentai.org` requests * change default delay to 6 secs --- README.md | 6 ++++++ plugins/EHentai Login/main.py | 2 +- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 10 ++++++++++ plugins/EHentai Metadata/readme.md | 4 ++++ 5 files changed, 22 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 842d56c..88f5f55 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,13 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins +<<<<<<< HEAD +- [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from Panda.Chaika* +- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* +- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* +======= - [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* - [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* +>>>>>>> master - [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 086c3b6..510b1f1 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -14,7 +14,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 9 +default_delay = 6 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index b7e754c..8ad7059 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "0.2.0b", + "version": "0.3.0b", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 4a307e1..19211ed 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -16,6 +16,8 @@ match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. match_url_end = r"\/?$" +default_delay = 6 + urls_regex = { 'eh_gallery': match_url_prefix + r"((? Date: Mon, 5 Nov 2018 03:34:39 +0100 Subject: [PATCH 26/68] fix readme; --- README.md | 5 ----- 1 file changed, 5 deletions(-) diff --git a/README.md b/README.md index 88f5f55..b85d162 100644 --- a/README.md +++ b/README.md @@ -20,13 +20,8 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -<<<<<<< HEAD - [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from Panda.Chaika* - [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* - [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* -======= -- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* -- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* ->>>>>>> master - [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* From df0e2ac4b0ec94c98d28aed01e60f8341799b8ed Mon Sep 17 00:00:00 2001 From: Twiddly Date: Mon, 5 Nov 2018 03:35:43 +0100 Subject: [PATCH 27/68] fix readme; --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index b85d162..c7bd680 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,6 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github # Plugins -- [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) `0.1.0b` ᠁ *A plugin that can fetch metadata from Panda.Chaika* - [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* - [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* - [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* From 60aeb5d16b9dd93e053cd6044aab646aca1b07e4 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 6 Nov 2018 23:56:09 +0100 Subject: [PATCH 28/68] update file metadata to 0.3.0b; --- plugins/EHentai Metadata/main.py | 4 +- plugins/File Metadata/extractors.py | 195 ------------------ plugins/File Metadata/extractors/__init__.py | 3 + .../File Metadata/{ => extractors}/common.py | 35 +++- .../extractors/ehentaidownloader.py | 69 +++++++ plugins/File Metadata/extractors/eze.py | 50 +++++ plugins/File Metadata/extractors/hdoujin.py | 96 +++++++++ plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/main.py | 64 ++++-- plugins/File Metadata/readme.md | 33 ++- 10 files changed, 337 insertions(+), 214 deletions(-) delete mode 100644 plugins/File Metadata/extractors.py create mode 100644 plugins/File Metadata/extractors/__init__.py rename plugins/File Metadata/{ => extractors}/common.py (58%) create mode 100644 plugins/File Metadata/extractors/ehentaidownloader.py create mode 100644 plugins/File Metadata/extractors/eze.py create mode 100644 plugins/File Metadata/extractors/hdoujin.py diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 19211ed..1bd5ff7 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -380,7 +380,7 @@ def filter_metadata(gdata, item, urls_to_apply=None): url_model = hpx.command.GetModelClass("Url") namespacetags_model = hpx.command.GetModelClass("NamespaceTags") -def apply_metadata(data, gallery, replace=False): +def apply_metadata(data, gallery): """ data = { 'titles': None, # [(title, language),...] @@ -388,7 +388,7 @@ def apply_metadata(data, gallery, replace=False): 'parodies': None, # [parody, ...] 'category': None, 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} - 'pub_date': None, # DateTime object + 'pub_date': None, # DateTime object or Arrow object 'language': None, 'urls': None # [url, ...] } diff --git a/plugins/File Metadata/extractors.py b/plugins/File Metadata/extractors.py deleted file mode 100644 index c26252a..0000000 --- a/plugins/File Metadata/extractors.py +++ /dev/null @@ -1,195 +0,0 @@ -import __hpx__ as hpx -import common - -log = hpx.get_logger(__name__) - -class Eze(common.Extractor): - - def file_to_dict(self, fs): - d = super().file_to_dict(fs) - k = ('gallery_info', 'image_info') - if d and not all(map(lambda x: x in d, k)): # make sure all keys are present - d = None - return d - - def extract(self, filedata): - d = {} - filedata = filedata.get('gallery_info') - if filedata: - log.debug("Expecting eze metadata file") - mtitle = filedata.get('title') - mtitle_jp = filedata.get('title_original') - - mcat = filedata.get("category") - if mcat: - d['category'] = common.capitalize_text(mcat) - - for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): - if t: - nameparser = hpx.command.NameParser(t) - parsed_title = nameparser.extract_title() - d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) - - mtags = filedata.get("tags") - - if mtags: - d['tags'] = {} - for ns, t in mtags.items(): - d['tags'].setdefault(common.capitalize_text(ns), t) - - mlang = filedata.get("language") - if mlang: - d['language'] = common.capitalize_text(mlang) - - msource = filedata.get('source') - if msource: - d.setdefault('urls', []).append(f"https://{msource['site']}.org/g/{msource['gid']}/{msource['token']}") - - return d - -common.register_extractor(Eze, common.DataType.eze) - -class HDoujin(common.Extractor): - - def file_to_dict(self, fs): - d = super().file_to_dict(fs) - if d: - if fs.ext.lower() == '.txt': - k = ('TITLE', 'ARTIST') - else: - k = ('manga_info',) - if not all(map(lambda x: x in d, k)): # make sure all keys are present - d = None - else: - if fs.ext.lower() == '.txt': - new_d = {} - for k, v in d.items(): - if k == "AUTHOR/CIRCLE": - k = "CIRCLE" - new_d[k.lower().replace(' ', '_')] = v - d = new_d - else: - d = d.get('manga_info') - return d - - def extract(self, filedata): - d = {} - if filedata: - log.debug("Expecting hdoujin metadata file") - mtitle = filedata.get('title') - mtitle_jp = filedata.get('original_title') - - for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): - if t: - nameparser = hpx.command.NameParser(t) - parsed_title = nameparser.extract_title() - d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) - - martists = filedata.get("artist") - mcircles = filedata.get("circle") - if martists: - if isinstance(martists, str): - martists = martists.split(',') - if isinstance(mcircles, str): - mcircles = mcircles.split(',') - for a in martists: - d.setdefault("artists", []).append((a, tuple(mcircles) if mcircles else tuple())) - - mtags = filedata.get("tags") - - if mtags: - if isinstance(mtags, str): - mtags = mtags.split(',') - nstag = {} - for x in mtags: - t = x.split(':', 1) - if len(t) == 2: - nstag.setdefault(t[0], []).append(t[1]) - if nstag: - mtags = nstag - - if isinstance(mtags, dict): - d['tags'] = {} - for ns, t in mtags.items(): - d['tags'].setdefault(common.capitalize_text(ns), t) - else: - d['tags'] = mtags - - mlang = filedata.get("language") - if mlang: - if isinstance(mlang, list): - mlang = mlang[0] - d['language'] = common.capitalize_text(mlang) - - msource = filedata.get('url') - if msource: - d.setdefault('urls', []).append(msource) - - return d - -common.register_extractor(HDoujin, common.DataType.hdoujin) - -class EHentaiDownloader(common.Extractor): - - def file_to_dict(self, fs): - """ - File is formatted weirdly so we just return {linenumber : line} - """ - d = {} - log.debug(f"File ext: {fs.ext}") - kw = {} - if not fs.inside_archive: - kw['encoding'] = "utf-8" - with fs.open("r", **kw) as f: - for num, line in enumerate(f.readlines(), 1): - if isinstance(line, bytes): - line = line.decode("utf-8") - d[num] = line - - # confirm it's the right file - if d and not "generated by e-hentai downloader" in d[len(d)].lower(): - d = None - return d - - def extract(self, filedata): - d = {} - if filedata: - log.debug("Expecting e-hentai downloader metadata file") - for linenum in sorted(filedata): - line = filedata[linenum].strip() - if not line: - continue - - if line.startswith("Language:"): - line = line.split(':', 1)[1] - d['language'] = common.capitalize_text(line.lower().split()[0]) - continue - - if line.startswith("Category:"): - line = line.split(':', 1)[1] - d['category'] = common.capitalize_text(line.lower()) - continue - - if line.startswith("> "): # tags - line = line[2:] # remove > - ns, tags = line.split(':', 1) - tags = tags.split(",") - d.setdefault("tags", {})[ns.strip()] = [t.strip() for t in tags] - continue - - if linenum in (1, 2, 3): # most likely a title or url, must be last because maybe it wasn't included - # ensure - if not filedata.get(3, "").startswith("http"): - continue - - if linenum == 3: - d.setdefault('urls', []).append(line) - else: - title_lang = "english" if linenum == 1 else "japanese" - nameparser = hpx.command.NameParser(line) - parsed_title = nameparser.extract_title() - d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) - continue - return d - -common.register_extractor(EHentaiDownloader, common.DataType.e_hentai_downloader) diff --git a/plugins/File Metadata/extractors/__init__.py b/plugins/File Metadata/extractors/__init__.py new file mode 100644 index 0000000..8951b5c --- /dev/null +++ b/plugins/File Metadata/extractors/__init__.py @@ -0,0 +1,3 @@ +from . import eze +from . import ehentaidownloader +from . import hdoujin \ No newline at end of file diff --git a/plugins/File Metadata/common.py b/plugins/File Metadata/extractors/common.py similarity index 58% rename from plugins/File Metadata/common.py rename to plugins/File Metadata/extractors/common.py index bdcdf72..8686570 100644 --- a/plugins/File Metadata/common.py +++ b/plugins/File Metadata/extractors/common.py @@ -5,11 +5,17 @@ log = hpx.get_logger(__name__) class DataType(enum.Flag): + """ + The available extractors. + Add your new extractor here + """ eze = enum.auto() hdoujin = enum.auto() e_hentai_downloader = enum.auto() +# The filetypes to look for, no duplicates, only add if necessary filetypes = ('.json', '.txt') +# Which filetype belongs to which extractor, use inclusive OR '|' to combine multiple extractors filenames = { "info.json": DataType.eze | DataType.hdoujin, "info.txt": DataType.hdoujin | DataType.e_hentai_downloader, @@ -18,13 +24,18 @@ class DataType(enum.Flag): common_data = { 'titles': None, # [(title, language),...] 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] 'category': None, 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} - 'pub_date': None, # DateTime object + 'pub_date': None, # DateTime object or Arrow object 'language': None, 'urls': None # [url, ...] } +plugin_config = { + 'characters_namespace': 'character', # hdoujin, which namespace to put the values in the CHARACTERS field in +} + extractors = {} def capitalize_text(text): @@ -40,10 +51,26 @@ def register_extractor(cls, type): class Extractor: """ + Base extractor """ def file_to_dict(self, fs: hpx.command.CoreFS) -> dict: """ + A subclass can choose to override or extend this method. + Should return a dict with data from the file which will be passed to the extract method. + + Below is convenience code to read and convert a file into a dict. + Supports json and txt files. + If file is a txt, will try to parse files like this: + Field A: value 1 + Field B: value 2 + -> + { + 'Field A': 'value 1', + 'Field B': 'value 2', + } + otherwise the txt file is not supported and a ValueError will be raised. + NotImplementedError will be raised if file is neither json or txt file. """ try: d = {} @@ -63,12 +90,16 @@ def file_to_dict(self, fs: hpx.command.CoreFS) -> dict: d[k.strip()] = v.strip() else: raise NotImplementedError(f"{fs.ext} filetype not supported yet") - except Exception: + except Exception: # Bad, I know, but too lazy log.warning("An error occured while trying to parse file into a dict") raise ValueError return d def extract(self, filedata: dict) -> dict: """ + A subclass must implement this method. + Should populate a dict that looks like common_data (see above) and return it + + filedata parameter is the dict created in the file_to_dict method """ raise NotImplementedError \ No newline at end of file diff --git a/plugins/File Metadata/extractors/ehentaidownloader.py b/plugins/File Metadata/extractors/ehentaidownloader.py new file mode 100644 index 0000000..7bb2cb6 --- /dev/null +++ b/plugins/File Metadata/extractors/ehentaidownloader.py @@ -0,0 +1,69 @@ +import __hpx__ as hpx +from . import common + +log = hpx.get_logger(__name__) + +class EHentaiDownloader(common.Extractor): + + def file_to_dict(self, fs): + """ + File is formatted weirdly so we just return {linenumber : line} + """ + d = {} + log.debug(f"File ext: {fs.ext}") + kw = {} + if not fs.inside_archive: + kw['encoding'] = "utf-8" + with fs.open("r", **kw) as f: + for num, line in enumerate(f.readlines(), 1): + if isinstance(line, bytes): + line = line.decode("utf-8") + d[num] = line + + # confirm it's the right file + if d and not "generated by e-hentai downloader" in d[len(d)].lower(): + d = None + return d + + def extract(self, filedata): + d = {} + if filedata: + log.debug("Expecting e-hentai downloader metadata file") + for linenum in sorted(filedata): + line = filedata[linenum].strip() + if not line: + continue + + if line.startswith("Language:"): + line = line.split(':', 1)[1] + d['language'] = common.capitalize_text(line.lower().split()[0]) + continue + + if line.startswith("Category:"): + line = line.split(':', 1)[1] + d['category'] = common.capitalize_text(line.lower()) + continue + + if line.startswith("> "): # tags + line = line[2:] # remove > + ns, tags = line.split(':', 1) + tags = tags.split(",") + d.setdefault("tags", {})[ns.strip()] = [t.strip() for t in tags] + continue + + if linenum in (1, 2, 3): # most likely a title or url, must be last because maybe it wasn't included + # ensure + if not filedata.get(3, "").startswith("http"): + continue + + if linenum == 3: + d.setdefault('urls', []).append(line) + else: + title_lang = "english" if linenum == 1 else "japanese" + nameparser = hpx.command.NameParser(line) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) + continue + return d + +common.register_extractor(EHentaiDownloader, common.DataType.e_hentai_downloader) diff --git a/plugins/File Metadata/extractors/eze.py b/plugins/File Metadata/extractors/eze.py new file mode 100644 index 0000000..4a14dec --- /dev/null +++ b/plugins/File Metadata/extractors/eze.py @@ -0,0 +1,50 @@ +import __hpx__ as hpx +from . import common + +log = hpx.get_logger(__name__) + +class Eze(common.Extractor): + + def file_to_dict(self, fs): + d = super().file_to_dict(fs) + k = ('gallery_info', 'image_info') + if d and not all(map(lambda x: x in d, k)): # make sure all keys are present + d = None + return d + + def extract(self, filedata): + d = {} + filedata = filedata.get('gallery_info') + if filedata: + log.debug("Expecting eze metadata file") + mtitle = filedata.get('title') + mtitle_jp = filedata.get('title_original') + + mcat = filedata.get("category") + if mcat: + d['category'] = common.capitalize_text(mcat) + + for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): + if t: + nameparser = hpx.command.NameParser(t) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) + + mtags = filedata.get("tags") + + if mtags: + d['tags'] = {} + for ns, t in mtags.items(): + d['tags'].setdefault(common.capitalize_text(ns), t) + + mlang = filedata.get("language") + if mlang: + d['language'] = common.capitalize_text(mlang) + + msource = filedata.get('source') + if msource: + d.setdefault('urls', []).append(f"https://{msource['site']}.org/g/{msource['gid']}/{msource['token']}") + + return d + +common.register_extractor(Eze, common.DataType.eze) \ No newline at end of file diff --git a/plugins/File Metadata/extractors/hdoujin.py b/plugins/File Metadata/extractors/hdoujin.py new file mode 100644 index 0000000..c8d1140 --- /dev/null +++ b/plugins/File Metadata/extractors/hdoujin.py @@ -0,0 +1,96 @@ +import __hpx__ as hpx +from . import common + +log = hpx.get_logger(__name__) + +class HDoujin(common.Extractor): + + def file_to_dict(self, fs): + d = super().file_to_dict(fs) + if d: + if fs.ext.lower() == '.txt': + k = ('TITLE', 'ARTIST') + else: + k = ('manga_info',) + if not all(map(lambda x: x in d, k)): # make sure all keys are present + d = None + else: + if fs.ext.lower() == '.txt': + new_d = {} + for k, v in d.items(): + if k == "AUTHOR/CIRCLE": + k = "CIRCLE" + new_d[k.lower().replace(' ', '_')] = v + d = new_d + else: + d = d.get('manga_info') + return d + + def extract(self, filedata): + d = {} + if filedata: + log.debug("Expecting hdoujin metadata file") + mtitle = filedata.get('title') + mtitle_jp = filedata.get('original_title') + + for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): + if t: + nameparser = hpx.command.NameParser(t) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) + + martists = filedata.get("artist") + mcircles = filedata.get("circle") + if martists: + if isinstance(martists, str): + martists = martists.split(',') + if isinstance(mcircles, str): + mcircles = mcircles.split(',') + for a in martists: + d.setdefault("artists", []).append((a, tuple(mcircles) if mcircles else tuple())) + + mtags = filedata.get("tags") + + if mtags: + if isinstance(mtags, str): + mtags = mtags.split(',') + nstag = {} + for x in mtags: + t = x.split(':', 1) + if len(t) == 2: + nstag.setdefault(t[0], []).append(t[1]) + if nstag: + mtags = nstag + + if isinstance(mtags, dict): + d['tags'] = {} + for ns, t in mtags.items(): + d['tags'].setdefault(common.capitalize_text(ns), t) + else: + d['tags'] = {None: mtags} # None for no namespace + + mcharacters = filedata.get("characters") + if mcharacters: + if isinstance(mcharacters, str): + mcharacters = mcharacters.split(',') + d.setdefault('tags', {})[common.plugin_config.get('characters_namespace') or 'characters'] = mcharacters + + mparody = filedata.get("parody") + if mparody: + if isinstance(mparody, str): + mparody = mparody.split(',') + d['parodies'] = mparody + + mlang = filedata.get("language") + if mlang: + if isinstance(mlang, list): + mlang = mlang[0] + d['language'] = common.capitalize_text(mlang) + + msource = filedata.get('url') + if msource: + d.setdefault('urls', []).append(msource) + + return d + +common.register_extractor(HDoujin, common.DataType.hdoujin) \ No newline at end of file diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index 1a8bef9..a7e6e04 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "0.2.0b", + "version": "0.3.0b", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index c1a5d83..4d2d19e 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -2,8 +2,9 @@ import os import arrow import datetime -import common +import html import extractors +from extractors import common log = hpx.get_logger(__name__) @@ -37,49 +38,77 @@ def get_common_data(datatypes, fpath): language_model = hpx.command.GetModelClass("Language") title_model = hpx.command.GetModelClass("Title") artist_model = hpx.command.GetModelClass("Artist") +parody_model = hpx.command.GetModelClass("Parody") circle_model = hpx.command.GetModelClass("Circle") url_model = hpx.command.GetModelClass("Url") namespacetags_model = hpx.command.GetModelClass("NamespaceTags") def apply_metadata(data, gallery): + """ + data = { + 'titles': None, # [(title, language),...] + 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] + 'category': None, + 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} + 'pub_date': None, # DateTime object or Arrow object + 'language': None, + 'urls': None # [url, ...] + } + """ + applied = False - log.debug("data:") - log.debug(f"{data}") + log.debug(f"data: {data}") - if isinstance(data['titles'], (list, tuple)): + if isinstance(data.get('titles'), (list, tuple)): for t, l in data['titles']: gtitle = None if t: + t = html.unescape(t) gtitle = title_model(name=t) if t and l: gtitle.language = language_model.as_unique(name=l) if gtitle: gallery.update("titles", gtitle) + log.debug("applied titles") applied = True - if isinstance(data['artists'], (list, tuple)): + if isinstance(data.get('artists'), (list, tuple)): for a, c in data['artists']: if a: - gartist = artist_model.as_unique(name=a) + gartist = artist_model.as_unique(name=common.capitalize_text(a)) if not gartist in gallery.artists: gallery.update("artists", gartist) if a and c: for circlename in [x for x in c if x]: - gcircle = circle_model.as_unique(name=circlename) + gcircle = circle_model.as_unique(name=common.capitalize_text(circlename)) if not gcircle in gartist.circles: gartist.update("circles", gcircle) + log.debug("applied artists") applied = True - if data['category']: + if isinstance(data.get('parodies'), (list, tuple)): + for p in data['parodies']: + if p: + gparody = parody_model.as_unique(name=common.capitalize_text(p)) + if not gparody in gallery.parodies: + gallery.update("parodies", gparody) + + log.debug("applied parodies") + applied = True + + if data.get('category'): gallery.update("category", name=data['category']) + log.debug("applied category") applied = True - if data['language']: + if data.get('language'): gallery.update("language", name=data['language']) + log.debug("applied language") applied = True - if isinstance(data['tags'], (dict, list)): + if isinstance(data.get('tags'), (dict, list)): if isinstance(data['tags'], list): data['tags'] = {None: data['tags']} ns_tags = [] @@ -95,22 +124,31 @@ def apply_metadata(data, gallery): for nstag in ns_tags: if nstag not in gallery.tags: gallery.tags.append(nstag) + log.debug("applied tags") applied = True - if isinstance(data['pub_date'], (datetime.datetime, arrow.Arrow)): + if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): pub_date = data['pub_date'] gallery.update("pub_date", pub_date) + log.debug("applied pub_date") applied = True - if isinstance(data['urls'], (list, tuple)): + if isinstance(data.get('urls'), (list, tuple)): + existing_urls = [x.name.lower() for x in gallery.urls] urls = [] for u in data['urls']: - urls.append(url_model(name=u)) + if u.lower() not in existing_urls: + urls.append(url_model(name=u)) gallery.update("urls", urls) + log.debug("applied urls") applied = True return applied +@hpx.subscribe("init") +def inited(): + common.plugin_config.update(hpx.get_plugin_config()) + @hpx.attach("GalleryFS.parse_metadata_file") def parse(path, gallery): fs = hpx.command.CoreFS(path) diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 1d4c774..4e510c0 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -14,12 +14,43 @@ This plugin supports extracting metadata from files produced by: - [E-Hentai-Downloader](https://github.com/ccloli/E-Hentai-Downloader) > - supports only the file named `info.txt` +## Configuration + +Configure this plugin by adding `file-metadata` to the `plugin.config` namespace in your `config.yaml`: +```yaml +plugin: + config: + file-metadata: + option1: True + option2: + - item 1 + - item 2 +``` + +#### Available options + +Name | Default | Description +--- | --- | --- +`characters_namespace` | `character` | which namespace to put the values in the CHARACTERS field in (applies to hdoujin) + # Extending -... coming +Follow these steps to add support for more kind of files: + +1. Create a new enum member for your extractor in `extractors.common.DataType` +2. Add a new filetype to `extractors.common.filetypes` if necessary +3. Add your new enum member to `extractors.common.filenames` +4. Create a new `.py` file in the `extractors` folder +5. Import the `common` module and create a new `common.Extractor` subclass +6. At the end of the file, register the subclass with `common.register_extractor` +7. Import your new `.py` file in `extractors.__init__` # Changelog +- `0.3.0b` + - **HDoujin**: add option `characters_namespace` + - **HDoujin**: parse `PARODY` and `CHARACTERS` fields + - `0.2.0b` - require HPX `0.2.0` - use new api to update gallery data From cb2a636fcbafb53874cd95ea2c9151051ea98699 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 6 Nov 2018 23:57:00 +0100 Subject: [PATCH 29/68] update readme --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 8523e20..b34b6b6 100644 --- a/README.md +++ b/README.md @@ -18,4 +18,9 @@ Please see [#Installing plugins](https://happypandax.github.io/usage.html#instal Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in documentation +# Plugins + +- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* +- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* +- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.3.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* From 3c46ce4fb7b3870aceb4cc9edb29823de919f3c8 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Wed, 7 Nov 2018 00:04:52 +0100 Subject: [PATCH 30/68] clarify method; --- plugins/File Metadata/extractors/common.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/plugins/File Metadata/extractors/common.py b/plugins/File Metadata/extractors/common.py index 8686570..a494f34 100644 --- a/plugins/File Metadata/extractors/common.py +++ b/plugins/File Metadata/extractors/common.py @@ -1,6 +1,7 @@ import __hpx__ as hpx import enum import json +import typing log = hpx.get_logger(__name__) @@ -54,10 +55,12 @@ class Extractor: Base extractor """ - def file_to_dict(self, fs: hpx.command.CoreFS) -> dict: + def file_to_dict(self, fs: hpx.command.CoreFS) -> typing.Union[dict, None]: """ A subclass can choose to override or extend this method. Should return a dict with data from the file which will be passed to the extract method. + If the file is not supported or should be skipped, return None. + The parameter fs is the file in question. Below is convenience code to read and convert a file into a dict. Supports json and txt files. From 98fd89f529da2be5d262864ebacb17da1a1ca28f Mon Sep 17 00:00:00 2001 From: Twiddly Date: Wed, 7 Nov 2018 00:06:51 +0100 Subject: [PATCH 31/68] Update File Metadata & files (#13) * update files * update file metadata to 0.3.0b; --- README.md | 2 +- plugins/EHentai Metadata/main.py | 4 +- plugins/File Metadata/extractors.py | 195 ------------------ plugins/File Metadata/extractors/__init__.py | 3 + .../File Metadata/{ => extractors}/common.py | 40 +++- .../extractors/ehentaidownloader.py | 69 +++++++ plugins/File Metadata/extractors/eze.py | 50 +++++ plugins/File Metadata/extractors/hdoujin.py | 96 +++++++++ plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/main.py | 64 ++++-- plugins/File Metadata/readme.md | 33 ++- 11 files changed, 342 insertions(+), 216 deletions(-) delete mode 100644 plugins/File Metadata/extractors.py create mode 100644 plugins/File Metadata/extractors/__init__.py rename plugins/File Metadata/{ => extractors}/common.py (54%) create mode 100644 plugins/File Metadata/extractors/ehentaidownloader.py create mode 100644 plugins/File Metadata/extractors/eze.py create mode 100644 plugins/File Metadata/extractors/hdoujin.py diff --git a/README.md b/README.md index c7bd680..b34b6b6 100644 --- a/README.md +++ b/README.md @@ -22,5 +22,5 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github - [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* - [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* -- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.2.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* +- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.3.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 19211ed..1bd5ff7 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -380,7 +380,7 @@ def filter_metadata(gdata, item, urls_to_apply=None): url_model = hpx.command.GetModelClass("Url") namespacetags_model = hpx.command.GetModelClass("NamespaceTags") -def apply_metadata(data, gallery, replace=False): +def apply_metadata(data, gallery): """ data = { 'titles': None, # [(title, language),...] @@ -388,7 +388,7 @@ def apply_metadata(data, gallery, replace=False): 'parodies': None, # [parody, ...] 'category': None, 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} - 'pub_date': None, # DateTime object + 'pub_date': None, # DateTime object or Arrow object 'language': None, 'urls': None # [url, ...] } diff --git a/plugins/File Metadata/extractors.py b/plugins/File Metadata/extractors.py deleted file mode 100644 index c26252a..0000000 --- a/plugins/File Metadata/extractors.py +++ /dev/null @@ -1,195 +0,0 @@ -import __hpx__ as hpx -import common - -log = hpx.get_logger(__name__) - -class Eze(common.Extractor): - - def file_to_dict(self, fs): - d = super().file_to_dict(fs) - k = ('gallery_info', 'image_info') - if d and not all(map(lambda x: x in d, k)): # make sure all keys are present - d = None - return d - - def extract(self, filedata): - d = {} - filedata = filedata.get('gallery_info') - if filedata: - log.debug("Expecting eze metadata file") - mtitle = filedata.get('title') - mtitle_jp = filedata.get('title_original') - - mcat = filedata.get("category") - if mcat: - d['category'] = common.capitalize_text(mcat) - - for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): - if t: - nameparser = hpx.command.NameParser(t) - parsed_title = nameparser.extract_title() - d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) - - mtags = filedata.get("tags") - - if mtags: - d['tags'] = {} - for ns, t in mtags.items(): - d['tags'].setdefault(common.capitalize_text(ns), t) - - mlang = filedata.get("language") - if mlang: - d['language'] = common.capitalize_text(mlang) - - msource = filedata.get('source') - if msource: - d.setdefault('urls', []).append(f"https://{msource['site']}.org/g/{msource['gid']}/{msource['token']}") - - return d - -common.register_extractor(Eze, common.DataType.eze) - -class HDoujin(common.Extractor): - - def file_to_dict(self, fs): - d = super().file_to_dict(fs) - if d: - if fs.ext.lower() == '.txt': - k = ('TITLE', 'ARTIST') - else: - k = ('manga_info',) - if not all(map(lambda x: x in d, k)): # make sure all keys are present - d = None - else: - if fs.ext.lower() == '.txt': - new_d = {} - for k, v in d.items(): - if k == "AUTHOR/CIRCLE": - k = "CIRCLE" - new_d[k.lower().replace(' ', '_')] = v - d = new_d - else: - d = d.get('manga_info') - return d - - def extract(self, filedata): - d = {} - if filedata: - log.debug("Expecting hdoujin metadata file") - mtitle = filedata.get('title') - mtitle_jp = filedata.get('original_title') - - for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): - if t: - nameparser = hpx.command.NameParser(t) - parsed_title = nameparser.extract_title() - d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) - - martists = filedata.get("artist") - mcircles = filedata.get("circle") - if martists: - if isinstance(martists, str): - martists = martists.split(',') - if isinstance(mcircles, str): - mcircles = mcircles.split(',') - for a in martists: - d.setdefault("artists", []).append((a, tuple(mcircles) if mcircles else tuple())) - - mtags = filedata.get("tags") - - if mtags: - if isinstance(mtags, str): - mtags = mtags.split(',') - nstag = {} - for x in mtags: - t = x.split(':', 1) - if len(t) == 2: - nstag.setdefault(t[0], []).append(t[1]) - if nstag: - mtags = nstag - - if isinstance(mtags, dict): - d['tags'] = {} - for ns, t in mtags.items(): - d['tags'].setdefault(common.capitalize_text(ns), t) - else: - d['tags'] = mtags - - mlang = filedata.get("language") - if mlang: - if isinstance(mlang, list): - mlang = mlang[0] - d['language'] = common.capitalize_text(mlang) - - msource = filedata.get('url') - if msource: - d.setdefault('urls', []).append(msource) - - return d - -common.register_extractor(HDoujin, common.DataType.hdoujin) - -class EHentaiDownloader(common.Extractor): - - def file_to_dict(self, fs): - """ - File is formatted weirdly so we just return {linenumber : line} - """ - d = {} - log.debug(f"File ext: {fs.ext}") - kw = {} - if not fs.inside_archive: - kw['encoding'] = "utf-8" - with fs.open("r", **kw) as f: - for num, line in enumerate(f.readlines(), 1): - if isinstance(line, bytes): - line = line.decode("utf-8") - d[num] = line - - # confirm it's the right file - if d and not "generated by e-hentai downloader" in d[len(d)].lower(): - d = None - return d - - def extract(self, filedata): - d = {} - if filedata: - log.debug("Expecting e-hentai downloader metadata file") - for linenum in sorted(filedata): - line = filedata[linenum].strip() - if not line: - continue - - if line.startswith("Language:"): - line = line.split(':', 1)[1] - d['language'] = common.capitalize_text(line.lower().split()[0]) - continue - - if line.startswith("Category:"): - line = line.split(':', 1)[1] - d['category'] = common.capitalize_text(line.lower()) - continue - - if line.startswith("> "): # tags - line = line[2:] # remove > - ns, tags = line.split(':', 1) - tags = tags.split(",") - d.setdefault("tags", {})[ns.strip()] = [t.strip() for t in tags] - continue - - if linenum in (1, 2, 3): # most likely a title or url, must be last because maybe it wasn't included - # ensure - if not filedata.get(3, "").startswith("http"): - continue - - if linenum == 3: - d.setdefault('urls', []).append(line) - else: - title_lang = "english" if linenum == 1 else "japanese" - nameparser = hpx.command.NameParser(line) - parsed_title = nameparser.extract_title() - d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) - continue - return d - -common.register_extractor(EHentaiDownloader, common.DataType.e_hentai_downloader) diff --git a/plugins/File Metadata/extractors/__init__.py b/plugins/File Metadata/extractors/__init__.py new file mode 100644 index 0000000..8951b5c --- /dev/null +++ b/plugins/File Metadata/extractors/__init__.py @@ -0,0 +1,3 @@ +from . import eze +from . import ehentaidownloader +from . import hdoujin \ No newline at end of file diff --git a/plugins/File Metadata/common.py b/plugins/File Metadata/extractors/common.py similarity index 54% rename from plugins/File Metadata/common.py rename to plugins/File Metadata/extractors/common.py index bdcdf72..a494f34 100644 --- a/plugins/File Metadata/common.py +++ b/plugins/File Metadata/extractors/common.py @@ -1,15 +1,22 @@ import __hpx__ as hpx import enum import json +import typing log = hpx.get_logger(__name__) class DataType(enum.Flag): + """ + The available extractors. + Add your new extractor here + """ eze = enum.auto() hdoujin = enum.auto() e_hentai_downloader = enum.auto() +# The filetypes to look for, no duplicates, only add if necessary filetypes = ('.json', '.txt') +# Which filetype belongs to which extractor, use inclusive OR '|' to combine multiple extractors filenames = { "info.json": DataType.eze | DataType.hdoujin, "info.txt": DataType.hdoujin | DataType.e_hentai_downloader, @@ -18,13 +25,18 @@ class DataType(enum.Flag): common_data = { 'titles': None, # [(title, language),...] 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] 'category': None, 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} - 'pub_date': None, # DateTime object + 'pub_date': None, # DateTime object or Arrow object 'language': None, 'urls': None # [url, ...] } +plugin_config = { + 'characters_namespace': 'character', # hdoujin, which namespace to put the values in the CHARACTERS field in +} + extractors = {} def capitalize_text(text): @@ -40,10 +52,28 @@ def register_extractor(cls, type): class Extractor: """ + Base extractor """ - def file_to_dict(self, fs: hpx.command.CoreFS) -> dict: + def file_to_dict(self, fs: hpx.command.CoreFS) -> typing.Union[dict, None]: """ + A subclass can choose to override or extend this method. + Should return a dict with data from the file which will be passed to the extract method. + If the file is not supported or should be skipped, return None. + The parameter fs is the file in question. + + Below is convenience code to read and convert a file into a dict. + Supports json and txt files. + If file is a txt, will try to parse files like this: + Field A: value 1 + Field B: value 2 + -> + { + 'Field A': 'value 1', + 'Field B': 'value 2', + } + otherwise the txt file is not supported and a ValueError will be raised. + NotImplementedError will be raised if file is neither json or txt file. """ try: d = {} @@ -63,12 +93,16 @@ def file_to_dict(self, fs: hpx.command.CoreFS) -> dict: d[k.strip()] = v.strip() else: raise NotImplementedError(f"{fs.ext} filetype not supported yet") - except Exception: + except Exception: # Bad, I know, but too lazy log.warning("An error occured while trying to parse file into a dict") raise ValueError return d def extract(self, filedata: dict) -> dict: """ + A subclass must implement this method. + Should populate a dict that looks like common_data (see above) and return it + + filedata parameter is the dict created in the file_to_dict method """ raise NotImplementedError \ No newline at end of file diff --git a/plugins/File Metadata/extractors/ehentaidownloader.py b/plugins/File Metadata/extractors/ehentaidownloader.py new file mode 100644 index 0000000..7bb2cb6 --- /dev/null +++ b/plugins/File Metadata/extractors/ehentaidownloader.py @@ -0,0 +1,69 @@ +import __hpx__ as hpx +from . import common + +log = hpx.get_logger(__name__) + +class EHentaiDownloader(common.Extractor): + + def file_to_dict(self, fs): + """ + File is formatted weirdly so we just return {linenumber : line} + """ + d = {} + log.debug(f"File ext: {fs.ext}") + kw = {} + if not fs.inside_archive: + kw['encoding'] = "utf-8" + with fs.open("r", **kw) as f: + for num, line in enumerate(f.readlines(), 1): + if isinstance(line, bytes): + line = line.decode("utf-8") + d[num] = line + + # confirm it's the right file + if d and not "generated by e-hentai downloader" in d[len(d)].lower(): + d = None + return d + + def extract(self, filedata): + d = {} + if filedata: + log.debug("Expecting e-hentai downloader metadata file") + for linenum in sorted(filedata): + line = filedata[linenum].strip() + if not line: + continue + + if line.startswith("Language:"): + line = line.split(':', 1)[1] + d['language'] = common.capitalize_text(line.lower().split()[0]) + continue + + if line.startswith("Category:"): + line = line.split(':', 1)[1] + d['category'] = common.capitalize_text(line.lower()) + continue + + if line.startswith("> "): # tags + line = line[2:] # remove > + ns, tags = line.split(':', 1) + tags = tags.split(",") + d.setdefault("tags", {})[ns.strip()] = [t.strip() for t in tags] + continue + + if linenum in (1, 2, 3): # most likely a title or url, must be last because maybe it wasn't included + # ensure + if not filedata.get(3, "").startswith("http"): + continue + + if linenum == 3: + d.setdefault('urls', []).append(line) + else: + title_lang = "english" if linenum == 1 else "japanese" + nameparser = hpx.command.NameParser(line) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) + continue + return d + +common.register_extractor(EHentaiDownloader, common.DataType.e_hentai_downloader) diff --git a/plugins/File Metadata/extractors/eze.py b/plugins/File Metadata/extractors/eze.py new file mode 100644 index 0000000..4a14dec --- /dev/null +++ b/plugins/File Metadata/extractors/eze.py @@ -0,0 +1,50 @@ +import __hpx__ as hpx +from . import common + +log = hpx.get_logger(__name__) + +class Eze(common.Extractor): + + def file_to_dict(self, fs): + d = super().file_to_dict(fs) + k = ('gallery_info', 'image_info') + if d and not all(map(lambda x: x in d, k)): # make sure all keys are present + d = None + return d + + def extract(self, filedata): + d = {} + filedata = filedata.get('gallery_info') + if filedata: + log.debug("Expecting eze metadata file") + mtitle = filedata.get('title') + mtitle_jp = filedata.get('title_original') + + mcat = filedata.get("category") + if mcat: + d['category'] = common.capitalize_text(mcat) + + for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): + if t: + nameparser = hpx.command.NameParser(t) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) + + mtags = filedata.get("tags") + + if mtags: + d['tags'] = {} + for ns, t in mtags.items(): + d['tags'].setdefault(common.capitalize_text(ns), t) + + mlang = filedata.get("language") + if mlang: + d['language'] = common.capitalize_text(mlang) + + msource = filedata.get('source') + if msource: + d.setdefault('urls', []).append(f"https://{msource['site']}.org/g/{msource['gid']}/{msource['token']}") + + return d + +common.register_extractor(Eze, common.DataType.eze) \ No newline at end of file diff --git a/plugins/File Metadata/extractors/hdoujin.py b/plugins/File Metadata/extractors/hdoujin.py new file mode 100644 index 0000000..c8d1140 --- /dev/null +++ b/plugins/File Metadata/extractors/hdoujin.py @@ -0,0 +1,96 @@ +import __hpx__ as hpx +from . import common + +log = hpx.get_logger(__name__) + +class HDoujin(common.Extractor): + + def file_to_dict(self, fs): + d = super().file_to_dict(fs) + if d: + if fs.ext.lower() == '.txt': + k = ('TITLE', 'ARTIST') + else: + k = ('manga_info',) + if not all(map(lambda x: x in d, k)): # make sure all keys are present + d = None + else: + if fs.ext.lower() == '.txt': + new_d = {} + for k, v in d.items(): + if k == "AUTHOR/CIRCLE": + k = "CIRCLE" + new_d[k.lower().replace(' ', '_')] = v + d = new_d + else: + d = d.get('manga_info') + return d + + def extract(self, filedata): + d = {} + if filedata: + log.debug("Expecting hdoujin metadata file") + mtitle = filedata.get('title') + mtitle_jp = filedata.get('original_title') + + for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): + if t: + nameparser = hpx.command.NameParser(t) + parsed_title = nameparser.extract_title() + d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) + + martists = filedata.get("artist") + mcircles = filedata.get("circle") + if martists: + if isinstance(martists, str): + martists = martists.split(',') + if isinstance(mcircles, str): + mcircles = mcircles.split(',') + for a in martists: + d.setdefault("artists", []).append((a, tuple(mcircles) if mcircles else tuple())) + + mtags = filedata.get("tags") + + if mtags: + if isinstance(mtags, str): + mtags = mtags.split(',') + nstag = {} + for x in mtags: + t = x.split(':', 1) + if len(t) == 2: + nstag.setdefault(t[0], []).append(t[1]) + if nstag: + mtags = nstag + + if isinstance(mtags, dict): + d['tags'] = {} + for ns, t in mtags.items(): + d['tags'].setdefault(common.capitalize_text(ns), t) + else: + d['tags'] = {None: mtags} # None for no namespace + + mcharacters = filedata.get("characters") + if mcharacters: + if isinstance(mcharacters, str): + mcharacters = mcharacters.split(',') + d.setdefault('tags', {})[common.plugin_config.get('characters_namespace') or 'characters'] = mcharacters + + mparody = filedata.get("parody") + if mparody: + if isinstance(mparody, str): + mparody = mparody.split(',') + d['parodies'] = mparody + + mlang = filedata.get("language") + if mlang: + if isinstance(mlang, list): + mlang = mlang[0] + d['language'] = common.capitalize_text(mlang) + + msource = filedata.get('url') + if msource: + d.setdefault('urls', []).append(msource) + + return d + +common.register_extractor(HDoujin, common.DataType.hdoujin) \ No newline at end of file diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index 1a8bef9..a7e6e04 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "0.2.0b", + "version": "0.3.0b", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index c1a5d83..4d2d19e 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -2,8 +2,9 @@ import os import arrow import datetime -import common +import html import extractors +from extractors import common log = hpx.get_logger(__name__) @@ -37,49 +38,77 @@ def get_common_data(datatypes, fpath): language_model = hpx.command.GetModelClass("Language") title_model = hpx.command.GetModelClass("Title") artist_model = hpx.command.GetModelClass("Artist") +parody_model = hpx.command.GetModelClass("Parody") circle_model = hpx.command.GetModelClass("Circle") url_model = hpx.command.GetModelClass("Url") namespacetags_model = hpx.command.GetModelClass("NamespaceTags") def apply_metadata(data, gallery): + """ + data = { + 'titles': None, # [(title, language),...] + 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] + 'category': None, + 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} + 'pub_date': None, # DateTime object or Arrow object + 'language': None, + 'urls': None # [url, ...] + } + """ + applied = False - log.debug("data:") - log.debug(f"{data}") + log.debug(f"data: {data}") - if isinstance(data['titles'], (list, tuple)): + if isinstance(data.get('titles'), (list, tuple)): for t, l in data['titles']: gtitle = None if t: + t = html.unescape(t) gtitle = title_model(name=t) if t and l: gtitle.language = language_model.as_unique(name=l) if gtitle: gallery.update("titles", gtitle) + log.debug("applied titles") applied = True - if isinstance(data['artists'], (list, tuple)): + if isinstance(data.get('artists'), (list, tuple)): for a, c in data['artists']: if a: - gartist = artist_model.as_unique(name=a) + gartist = artist_model.as_unique(name=common.capitalize_text(a)) if not gartist in gallery.artists: gallery.update("artists", gartist) if a and c: for circlename in [x for x in c if x]: - gcircle = circle_model.as_unique(name=circlename) + gcircle = circle_model.as_unique(name=common.capitalize_text(circlename)) if not gcircle in gartist.circles: gartist.update("circles", gcircle) + log.debug("applied artists") applied = True - if data['category']: + if isinstance(data.get('parodies'), (list, tuple)): + for p in data['parodies']: + if p: + gparody = parody_model.as_unique(name=common.capitalize_text(p)) + if not gparody in gallery.parodies: + gallery.update("parodies", gparody) + + log.debug("applied parodies") + applied = True + + if data.get('category'): gallery.update("category", name=data['category']) + log.debug("applied category") applied = True - if data['language']: + if data.get('language'): gallery.update("language", name=data['language']) + log.debug("applied language") applied = True - if isinstance(data['tags'], (dict, list)): + if isinstance(data.get('tags'), (dict, list)): if isinstance(data['tags'], list): data['tags'] = {None: data['tags']} ns_tags = [] @@ -95,22 +124,31 @@ def apply_metadata(data, gallery): for nstag in ns_tags: if nstag not in gallery.tags: gallery.tags.append(nstag) + log.debug("applied tags") applied = True - if isinstance(data['pub_date'], (datetime.datetime, arrow.Arrow)): + if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): pub_date = data['pub_date'] gallery.update("pub_date", pub_date) + log.debug("applied pub_date") applied = True - if isinstance(data['urls'], (list, tuple)): + if isinstance(data.get('urls'), (list, tuple)): + existing_urls = [x.name.lower() for x in gallery.urls] urls = [] for u in data['urls']: - urls.append(url_model(name=u)) + if u.lower() not in existing_urls: + urls.append(url_model(name=u)) gallery.update("urls", urls) + log.debug("applied urls") applied = True return applied +@hpx.subscribe("init") +def inited(): + common.plugin_config.update(hpx.get_plugin_config()) + @hpx.attach("GalleryFS.parse_metadata_file") def parse(path, gallery): fs = hpx.command.CoreFS(path) diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 1d4c774..4e510c0 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -14,12 +14,43 @@ This plugin supports extracting metadata from files produced by: - [E-Hentai-Downloader](https://github.com/ccloli/E-Hentai-Downloader) > - supports only the file named `info.txt` +## Configuration + +Configure this plugin by adding `file-metadata` to the `plugin.config` namespace in your `config.yaml`: +```yaml +plugin: + config: + file-metadata: + option1: True + option2: + - item 1 + - item 2 +``` + +#### Available options + +Name | Default | Description +--- | --- | --- +`characters_namespace` | `character` | which namespace to put the values in the CHARACTERS field in (applies to hdoujin) + # Extending -... coming +Follow these steps to add support for more kind of files: + +1. Create a new enum member for your extractor in `extractors.common.DataType` +2. Add a new filetype to `extractors.common.filetypes` if necessary +3. Add your new enum member to `extractors.common.filenames` +4. Create a new `.py` file in the `extractors` folder +5. Import the `common` module and create a new `common.Extractor` subclass +6. At the end of the file, register the subclass with `common.register_extractor` +7. Import your new `.py` file in `extractors.__init__` # Changelog +- `0.3.0b` + - **HDoujin**: add option `characters_namespace` + - **HDoujin**: parse `PARODY` and `CHARACTERS` fields + - `0.2.0b` - require HPX `0.2.0` - use new api to update gallery data From ae7b9e98da63e6da8a86b54de3a293e00aae6f42 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Wed, 28 Nov 2018 20:21:21 +0100 Subject: [PATCH 32/68] chaika metadata --- .travis.yml | 23 ++ README.md | 19 +- build.py | 14 +- plugins/Chaika Metadata/hplugin.json | 14 + plugins/Chaika Metadata/main.py | 453 +++++++++++++++++++++++++++ plugins/Chaika Metadata/readme.md | 38 +++ plugins/Chaika Metadata/test.py | 1 + 7 files changed, 547 insertions(+), 15 deletions(-) create mode 100644 .travis.yml create mode 100644 plugins/Chaika Metadata/hplugin.json create mode 100644 plugins/Chaika Metadata/main.py create mode 100644 plugins/Chaika Metadata/readme.md create mode 100644 plugins/Chaika Metadata/test.py diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..8fedbec --- /dev/null +++ b/.travis.yml @@ -0,0 +1,23 @@ +notifications: + email: + on_success: never + on_failure: always +language: python +python: 3.6 +addons: + apt: + update: true +env: + global: + - GH_USER=Twiddly + - GH_MAIL=pew@pewpew.moe + - REPOE=happypandax/plugins + - secure: XiUXHPc5pgrdIxHkYXzGRDAqdDCpuszKAJ/75+ZSjH+/Nv5uYLtP9LXzmOZm/x6rxIyNXP408sTnULm+Y+HfWoNV1sCaEwa50NniCPcbuEOtKe0N8o6VKbAmIaxyRZaThvDdIrB2U7VDI9Y+qeRuYfNEM77tEXklzu5SF2sfOAyaMQTdh1qCbGz4++EcZ2451ov8ZHTmHpEMCbUNeK9QZFSA14exFd5VlKYlDrehjoqFATR0Uypcjufh/uJluOWFpscG9duR2aChHkxZu/hH7UYNYRQG/N1VRYUR0g+tQ3CDMWBzIjbkASorZJydy1p53UVUEkTMwhSFw1SGCdAhobPUXlpeYFp9C932ODEhUkzEM3GmmEeV+53mq7nzi6bmOL3SdsWJnf5EZrPI2OOVqgkf2Nh/LkmhANlypcKDmWJOK+izUuMH6q/cl0ZnLSI+WsZU4d1WStfMrqNHE+/3fpwG8yf7CJ2788tzYHyPO9vzJvGsAoY3Z272BQ8rm6yFc/SWE6Mc93wC0vZ5Bd1WfOGMRWn6GVyvvyFKri86pgGj0N7BxXInMS4EWc/AD6r5RLc8xrTYKs0u+VHFAtWnnv7NlhXHnZUqPcSzpAvrhvc91575o7HNC2z/czJIT73eN1oXUMFqTkCvxYg2mC41VSvxf70CPYXAu/DBHLn1uio= + + +script: + - python3 build.py + - git config --local user.name "$GH_USER" + - git config --local user.email "$GH_MAIL" + - git commit -m "build" + - git push --quiet "https://$GITHUB_TOKEN@github.com/$REPO.git" master > /dev/null 2>&1 diff --git a/README.md b/README.md index b34b6b6..0d3fee2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ -In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to -[the docs](https://happypandax.github.io/plugin.html#plugins). +##### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). -# How to download +### How to download I recommend these tools to download a single directory from this repo: - https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* @@ -10,17 +9,21 @@ I recommend these tools to download a single directory from this repo: - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) -# How to install +### How to install Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. # Be careful about plugins -Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in documentation +Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in the documentation # Plugins -- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* -- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* -- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.3.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* +Name | Version | Description +--- | --- | --- +[**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `0.1.0b` | *A plugin that can fetch metadata from Panda.Chaika* +[**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `0.2.0b` | *A plugin that can login to E-Hentai & ExHentai* +[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `0.3.0b` | *A plugin that can fetch metadata from E-Hentai & ExHentai* +[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `0.3.0b` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* + diff --git a/build.py b/build.py index a4ba1c9..d207964 100644 --- a/build.py +++ b/build.py @@ -4,10 +4,9 @@ from urllib.parse import quote readme = """ -In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to -[the docs](https://happypandax.github.io/plugin.html#plugins). +##### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). -# How to download +### How to download I recommend these tools to download a single directory from this repo: - https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* @@ -15,17 +14,18 @@ - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) -# How to install +### How to install Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. # Be careful about plugins -Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in documentation +Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in the documentation # Plugins {} + """ plugins_dir = "plugins" @@ -36,7 +36,7 @@ def main(): print("Building...") - plugin_readme = "" + plugin_readme = "Name | Version | Description\n--- | --- | ---\n" for p in sorted(glob.glob(f"{plugins_dir}/**/hplugin.json")): with open(p, 'r', encoding="utf-8") as f: @@ -53,7 +53,7 @@ def main(): plugin_desc = plugin_desc.split('\n')[0] if len(plugin_desc) > desc_max_length: plugin_desc = plugin_desc[:desc_max_length] + '…' - plugin_readme += f"- [**{dir_name}**]({gh_url}) `{plugin_ver}` ᠁ *{plugin_desc}*\n" + plugin_readme += f"[**{dir_name}**]({gh_url}) | `{plugin_ver}` | *{plugin_desc}*\n" txt = readme.format(plugin_readme) diff --git a/plugins/Chaika Metadata/hplugin.json b/plugins/Chaika Metadata/hplugin.json new file mode 100644 index 0000000..661cb8e --- /dev/null +++ b/plugins/Chaika Metadata/hplugin.json @@ -0,0 +1,14 @@ +{ + "id": "55747a41-789b-43dd-964a-2a6cb1761ff4", + "shortname": "chaika-metadata", + "name": "Chaika Metadata", + "version": "0.1.0b", + "description": "A plugin that can fetch metadata from Panda.Chaika", + "author": "Twiddly", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.6.1" + ] +} \ No newline at end of file diff --git a/plugins/Chaika Metadata/main.py b/plugins/Chaika Metadata/main.py new file mode 100644 index 0000000..aaa91c4 --- /dev/null +++ b/plugins/Chaika Metadata/main.py @@ -0,0 +1,453 @@ +# main.py +import __hpx__ as hpx +import gevent +import regex +import arrow +import datetime +import os +import urllib +import html + +from bs4 import BeautifulSoup +from PIL import Image, ImageChops + +log = hpx.get_logger("main") + +match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +match_url_end = r"\/?$" + +default_delay = 0.5 + +urls_regex = { + 'gallery': match_url_prefix + r"(panda\.chaika\.moe\/(archive|gallery)\/[0-9]+)" + match_url_end, +} + +urls = { + 'ch': 'https://panda.chaika.moe', + 'gallery': 'https://panda.chaika.moe/gallery/', + 'archive': 'https://panda.chaika.moe/archive/', + 'gallery_api': 'https://panda.chaika.moe/jsearch?gallery=', + 'archive_api': 'https://panda.chaika.moe/jsearch?archive=', + 'hash_api': 'https://panda.chaika.moe/jsearch?sha1=', + 'title_search': "https://panda.chaika.moe/galleries/?title={title}&tags=&category=&provider=&uploader=&rating_from=&rating_to=&filesize_from=&filesize_to=&filecount_from=&filecount_to=&sort=posted&asc_desc=desc&apply=" +} + +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} + +plugin_config = { + 'filename_search': False, # use the filename/folder-name for searching instead of gallery title + 'remove_namespaces': True, # remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX + 'gallery_results_limit': 10, # maximum amount of galleries to return + 'blacklist_tags': [], # tags to ignore when updating tags + 'add_gallery_url': True, # add ehentai url to gallery + 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default +} + +@hpx.subscribe("init") +def inited(): + plugin_config.update(hpx.get_plugin_config()) + + # set default delay values if not set + delays = hpx.get_setting("network", "delays", {}) + for u in (urls['ch'],): + if u not in delays: + log.info(f"Setting delay on {u} requests to {default_delay}") + delays[u] = default_delay + hpx.update_setting("network", "delays", delays) + +@hpx.subscribe("disable") +def disabled(): + pass + +@hpx.subscribe("remove") +def removed(): + pass + +@hpx.attach("Metadata.info") +def metadata_info_eh(): + return hpx.command.MetadataInfo( + identifier = "chaika", + name = "Panda.Chaika", + parser = urls_regex['gallery'], + sites = ("www.panda.chaika.moe",), + description = "Fetch metadata from Panda.Chaika", + models = ( + hpx.command.GetModelClass("Gallery"), + ) + ) + +@hpx.attach("Metadata.query") +def query(item, url, options, capture="chaika"): + log.info("Querying chaika for metadata") + mdata = [] + gurls = [] # tuple of (title, url) + # url was provided + if url: + log.info(f"url provided: {url} for {item}") + gurls.append((url, url)) + else: # manually search for id + log.info(f"url not provided for {item}") + # search with title + i_title = "" + i_hash = "" + if plugin_config.get("filename_search"): + sources = item.get_sources() + if sources: + # get folder/file name + i_title = os.path.split(sources[0])[1] + # remove ext + i_title = os.path.splitext(i_title)[0] + else: + if item.titles: + i_title = item.titles[0].name # make user choice + if i_title: + gurls = title_search(i_title) + + # search with hash + if not gurls: + pass + + log.info(f"found {len(gurls)} urls for item: {item}") + + # list is sorted by date added so we reverse it + gurls.reverse() + + log.debug(f"{gurls}") + final_gurls = [] + pref_lang = plugin_config.get('preferred_language') + if pref_lang: + for t in gurls: + if pref_lang.lower() in t[0].lower(): + final_gurls.insert(0, t) + continue + final_gurls.append(t) + else: + final_gurls = gurls + + for t, u in final_gurls: + g_type, g_id = parse_url(u) + if g_type and g_id: + mdata.append(hpx.command.MetadataData( + data={ + 'type': g_type, + 'id': g_id, + 'gallery_url': u, + 'apply_url': plugin_config.get('add_gallery_url', True), + })) + return tuple(mdata) + +@hpx.attach("Metadata.apply") +def apply(datatuple, item, options, capture="chaika"): + log.info("Applying metadata from chaika") + applied = False + + for d in datatuple: + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + + api_url = urls['archive_api'] if d.data['type'] == 'archive' else urls['gallery_api'] + api_url += str(d.data['id']) + + r = hpx.command.SingleGETRequest().request(api_url, req_props) + if r.ok: + response = r.json + if response and not 'result' in response: + mdata = filter_metadata(response, item, apply_url=d.data['apply_url'], gallery_url=d.data['gallery_url']) + applied = apply_metadata(mdata, item) + elif response: + log.warning(response) + log.info(f"Applied: {applied}") + return applied + +def title_search(title, session=None, _times=0): + "Searches on chaika for galleries with given title, returns a list of (title, matching gallery urls)" + search_url = urls['title_search'] + log.debug(f"searching with title: {title}") + f_url = search_url.format( + title=urllib.parse.quote_plus(title) + ) + log.debug(f"final url: {f_url}") + r = page_results(f_url, session=session) + if not r and not _times: + title = regex.sub(r"\(.+?\)|\[.+?\]", "", title) + title = " ".join(title.split()) + r = title_search(title, session, _times=_times+1) + return r + +def page_results(page_url, limit=None, session=None): + "Opens chaika page, parses for results, and then returns list of (title, url)" + found_urls = [] + if limit is None: + limit = plugin_config.get("gallery_results_limit") + + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + if session: + req_props.session = session + log.debug(f"COOKIES: {session.cookies}") + r = hpx.command.SingleGETRequest().request(page_url, req_props) + soup = BeautifulSoup(r.text, "html.parser") + results = soup.findAll("tr", class_="result-list", limit=limit) + results = [r.findAll('td')[1] for r in results] + # str(x.a.string) + found_urls = [(str(x.a.string), urls['ch'] + x.a['href']) for x in results] # title, url + + if not found_urls: + log.warning(f"No results found on url: {page_url}") + log.debug(f"HTML: {r.text}") + return found_urls + +def parse_url(url): + "Parses url into a tuple of gallery/archive and id" + gallery_id = None + stype = "gallery" + + gallery_id = regex.search('([0-9]+)', url) + if gallery_id: + gallery_id = gallery_id.group() + else: + log.warning("Error extracting id from url: {}".format(url)) + + if 'archive' in url: + stype = 'archive' + + return stype, int(gallery_id) + +def capitalize_text(text): + """ + better str.capitalize + """ + return " ".join(x.capitalize() for x in text.strip().split()) + +def filter_metadata(gdata, item, apply_url=False, gallery_url=None): + mdata = {} + replace_metadata = hpx.get_setting('metadata', 'replace_metadata') + if replace_metadata: + item.titles = [] + item.artists = [] + item.tags = [] + # flush is required so items are removed from the db + hpx.command.GetSession().flush() + + if replace_metadata: + mdata['titles'] = [] + if gdata['title']: + mdata['titles'].append((gdata['title'], 'english')) + if gdata['title_jpn']: + mdata['titles'].append((gdata['title_jpn'], 'japanese')) + else: + t = [] + if not item.title_by_language("english") and gdata['title']: + t.append((gdata['title'], 'english')) + if not item.title_by_language("japanese") and gdata['title_jpn']: + t.append((gdata['title_jpn'], 'japanese')) + if t: + mdata['titles'] = t + + if replace_metadata: + mdata['category'] = gdata['category'] + elif not item.category: + mdata['category'] = gdata['category'] + + if gdata['posted']: + if replace_metadata: + mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + elif not item.pub_date: + mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + + lang = "japanese" # def lang + if not replace_metadata and item.language: + lang = item.language.name + + artists = [] + circles = [] + parodies = [] + + extra_namespaces = ("artist", "parody", "group", "language") + mdata['tags'] = {} + for nstag in gdata['tags']: + onstag = nstag + nstag = nstag.replace('_', ' ') + blacklist_tags = plugin_config.get("blacklist_tags") + if blacklist_tags and (nstag in blacklist_tags or onstag in blacklist_tags): + continue + + ns = None + if ':' in nstag: + ns, t = nstag.split(':', 1) + else: + t = nstag + + if ns == 'language' and t != 'translated': + lang = t + elif ns == "artist": + artists.append(t) + elif ns == "group": + circles.append(t) + elif ns == "parody": + parodies.append(t) + + if not (plugin_config.get("remove_namespaces") and ns in extra_namespaces): + mdata['tags'].setdefault(ns, []).append(t) + else: + log.debug(f"removing namespace {ns}") + + log.debug(f"tags: {mdata['tags']}") + + if replace_metadata: + mdata['language'] = lang + elif not item.language: + mdata['language'] = lang + + if parodies: + if replace_metadata: + item.parodies = [] + mdata['parodies'] = parodies + elif not item.parodies: + mdata['parodies'] = parodies + + if artists: + a_circles = [] + for a in artists: + a_circles.append((a, tuple(circles))) + if replace_metadata: + item.artists = [] + mdata['artists'] = a_circles + elif not item.artists: + mdata['artists'] = a_circles + + if apply_url: + if gdata.get('gallery', False): + mdata['urls'] = [urls['gallery']+f"{gdata['gallery']}/"] + elif gallery_url: + mdata['urls'] = [gallery_url] + + return mdata + +language_model = hpx.command.GetModelClass("Language") +title_model = hpx.command.GetModelClass("Title") +artist_model = hpx.command.GetModelClass("Artist") +parody_model = hpx.command.GetModelClass("Parody") +circle_model = hpx.command.GetModelClass("Circle") +url_model = hpx.command.GetModelClass("Url") +namespacetags_model = hpx.command.GetModelClass("NamespaceTags") + +def apply_metadata(data, gallery): + """ + data = { + 'titles': None, # [(title, language),...] + 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] + 'category': None, + 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} + 'pub_date': None, # DateTime object or Arrow object + 'language': None, + 'urls': None # [url, ...] + } + """ + + applied = False + + log.debug(f"data: {data}") + + if isinstance(data.get('titles'), (list, tuple)): + for t, l in data['titles']: + gtitle = None + if t: + t = html.unescape(t) + gtitle = title_model(name=t) + if t and l: + gtitle.language = language_model.as_unique(name=l) + if gtitle: + gallery.update("titles", gtitle) + log.debug("applied titles") + applied = True + + if isinstance(data.get('artists'), (list, tuple)): + for a, c in data['artists']: + if a: + gartist = artist_model.as_unique(name=capitalize_text(a)) + if not gartist in gallery.artists: + gallery.update("artists", gartist) + if a and c: + for circlename in [x for x in c if x]: + gcircle = circle_model.as_unique(name=capitalize_text(circlename)) + if not gcircle in gartist.circles: + gartist.update("circles", gcircle) + log.debug("applied artists") + applied = True + + if isinstance(data.get('parodies'), (list, tuple)): + for p in data['parodies']: + if p: + gparody = parody_model.as_unique(name=capitalize_text(p)) + if not gparody in gallery.parodies: + gallery.update("parodies", gparody) + + log.debug("applied parodies") + applied = True + + if data.get('category'): + gallery.update("category", name=data['category']) + log.debug("applied category") + applied = True + + if data.get('language'): + gallery.update("language", name=data['language']) + log.debug("applied language") + applied = True + + if isinstance(data.get('tags'), (dict, list)): + if isinstance(data['tags'], list): + data['tags'] = {None: data['tags']} + ns_tags = [] + for ns, tags in data['tags'].items(): + if ns is not None: + ns = ns.strip() + if ns and ns.lower() == 'misc': + ns = None + for t in tags: + t = t.strip() + ns_tags.append(namespacetags_model.as_unique(ns=ns, tag=t)) + + for nstag in ns_tags: + if nstag not in gallery.tags: + gallery.tags.append(nstag) + log.debug("applied tags") + applied = True + + if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): + pub_date = data['pub_date'] + gallery.update("pub_date", pub_date) + log.debug("applied pub_date") + applied = True + + if isinstance(data.get('urls'), (list, tuple)): + existing_urls = [x.name.lower() for x in gallery.urls] + urls = [] + for u in data['urls']: + if u.lower() not in existing_urls: + urls.append(url_model(name=u)) + gallery.update("urls", urls) + log.debug("applied urls") + applied = True + + return applied + +def is_image_greyscale(filepath): + "Check if image is monochrome (1 channel or 3 identical channels)" + im = Image.open(filepath).convert("RGB") + if im.mode not in ("L", "RGB"): + return False + + if im.mode == "RGB": + rgb = im.split() + if ImageChops.difference(rgb[0],rgb[1]).getextrema()[1] != 0: + return False + if ImageChops.difference(rgb[0],rgb[2]).getextrema()[1] != 0: + return False + return True \ No newline at end of file diff --git a/plugins/Chaika Metadata/readme.md b/plugins/Chaika Metadata/readme.md new file mode 100644 index 0000000..721415e --- /dev/null +++ b/plugins/Chaika Metadata/readme.md @@ -0,0 +1,38 @@ +EHentai Metadata +---------------------------- + +> This plugin fetches metadata from Panda.Chaika + +## Configuration + +Configure this plugin by adding `chaika-metadata` to the `plugin.config` namespace in your `config.yaml`: +```yaml +plugin: + config: + chaika-metadata: + option1: True + option2: + - item 1 + - item 2 +``` + +#### Available options + +Name | Default | Description +--- | --- | --- +`filename_search` | `false` | use the filename/folder-name for searching instead of gallery title +`remove_namespaces` | `true` | remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX +`gallery_results_limit` | `10` | maximum amount of galleries to return +`blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` or `tag` strings +`add_gallery_url` | `true` | add chaika url to gallery +`preferred_language` | `english` | preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default + + +## Things yet to be implemented + +- File similarity search + +# Changelog + +- `0.1.0b` + - first version \ No newline at end of file diff --git a/plugins/Chaika Metadata/test.py b/plugins/Chaika Metadata/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/Chaika Metadata/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file From aa2895a031c2305428d603b96d13ce8ed20106be Mon Sep 17 00:00:00 2001 From: Twiddly Date: Wed, 28 Nov 2018 20:25:35 +0100 Subject: [PATCH 33/68] Chaika Metadata * increase default delay limit; * increase default delay to 9; * update readme; * change default delay to 6 secs; update ehentai metadata; * build * update file metadata to 0.3.0b; * update readme * clarify method; * chaika metadata --- .travis.yml | 23 ++ README.md | 19 +- build.py | 14 +- plugins/Chaika Metadata/hplugin.json | 14 + plugins/Chaika Metadata/main.py | 453 +++++++++++++++++++++++++++ plugins/Chaika Metadata/readme.md | 38 +++ plugins/Chaika Metadata/test.py | 1 + 7 files changed, 547 insertions(+), 15 deletions(-) create mode 100644 .travis.yml create mode 100644 plugins/Chaika Metadata/hplugin.json create mode 100644 plugins/Chaika Metadata/main.py create mode 100644 plugins/Chaika Metadata/readme.md create mode 100644 plugins/Chaika Metadata/test.py diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..8fedbec --- /dev/null +++ b/.travis.yml @@ -0,0 +1,23 @@ +notifications: + email: + on_success: never + on_failure: always +language: python +python: 3.6 +addons: + apt: + update: true +env: + global: + - GH_USER=Twiddly + - GH_MAIL=pew@pewpew.moe + - REPOE=happypandax/plugins + - secure: XiUXHPc5pgrdIxHkYXzGRDAqdDCpuszKAJ/75+ZSjH+/Nv5uYLtP9LXzmOZm/x6rxIyNXP408sTnULm+Y+HfWoNV1sCaEwa50NniCPcbuEOtKe0N8o6VKbAmIaxyRZaThvDdIrB2U7VDI9Y+qeRuYfNEM77tEXklzu5SF2sfOAyaMQTdh1qCbGz4++EcZ2451ov8ZHTmHpEMCbUNeK9QZFSA14exFd5VlKYlDrehjoqFATR0Uypcjufh/uJluOWFpscG9duR2aChHkxZu/hH7UYNYRQG/N1VRYUR0g+tQ3CDMWBzIjbkASorZJydy1p53UVUEkTMwhSFw1SGCdAhobPUXlpeYFp9C932ODEhUkzEM3GmmEeV+53mq7nzi6bmOL3SdsWJnf5EZrPI2OOVqgkf2Nh/LkmhANlypcKDmWJOK+izUuMH6q/cl0ZnLSI+WsZU4d1WStfMrqNHE+/3fpwG8yf7CJ2788tzYHyPO9vzJvGsAoY3Z272BQ8rm6yFc/SWE6Mc93wC0vZ5Bd1WfOGMRWn6GVyvvyFKri86pgGj0N7BxXInMS4EWc/AD6r5RLc8xrTYKs0u+VHFAtWnnv7NlhXHnZUqPcSzpAvrhvc91575o7HNC2z/czJIT73eN1oXUMFqTkCvxYg2mC41VSvxf70CPYXAu/DBHLn1uio= + + +script: + - python3 build.py + - git config --local user.name "$GH_USER" + - git config --local user.email "$GH_MAIL" + - git commit -m "build" + - git push --quiet "https://$GITHUB_TOKEN@github.com/$REPO.git" master > /dev/null 2>&1 diff --git a/README.md b/README.md index b34b6b6..0d3fee2 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ -In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to -[the docs](https://happypandax.github.io/plugin.html#plugins). +##### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). -# How to download +### How to download I recommend these tools to download a single directory from this repo: - https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* @@ -10,17 +9,21 @@ I recommend these tools to download a single directory from this repo: - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) -# How to install +### How to install Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. # Be careful about plugins -Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in documentation +Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in the documentation # Plugins -- [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) `0.2.0b` ᠁ *A plugin that can login to E-Hentai & ExHentai* -- [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) `0.3.0b` ᠁ *A plugin that can fetch metadata from E-Hentai & ExHentai* -- [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) `0.3.0b` ᠁ *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* +Name | Version | Description +--- | --- | --- +[**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `0.1.0b` | *A plugin that can fetch metadata from Panda.Chaika* +[**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `0.2.0b` | *A plugin that can login to E-Hentai & ExHentai* +[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `0.3.0b` | *A plugin that can fetch metadata from E-Hentai & ExHentai* +[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `0.3.0b` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* + diff --git a/build.py b/build.py index a4ba1c9..d207964 100644 --- a/build.py +++ b/build.py @@ -4,10 +4,9 @@ from urllib.parse import quote readme = """ -In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to -[the docs](https://happypandax.github.io/plugin.html#plugins). +##### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). -# How to download +### How to download I recommend these tools to download a single directory from this repo: - https://minhaskamal.github.io/DownGit/ -- *Paste the url to the plugin folder in this repo* @@ -15,17 +14,18 @@ - [Firefox Addon](https://addons.mozilla.org/en-US/firefox/addon/gitzip/) - [Chrome Extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn) -# How to install +### How to install Please see [#Installing plugins](https://happypandax.github.io/usage.html#installing-plugins) in the documentation. # Be careful about plugins -Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in documentation +Read the relevant section [#Be careful about plugins](https://happypandax.github.io/usage.html#be-careful-about-plugins) in the documentation # Plugins {} + """ plugins_dir = "plugins" @@ -36,7 +36,7 @@ def main(): print("Building...") - plugin_readme = "" + plugin_readme = "Name | Version | Description\n--- | --- | ---\n" for p in sorted(glob.glob(f"{plugins_dir}/**/hplugin.json")): with open(p, 'r', encoding="utf-8") as f: @@ -53,7 +53,7 @@ def main(): plugin_desc = plugin_desc.split('\n')[0] if len(plugin_desc) > desc_max_length: plugin_desc = plugin_desc[:desc_max_length] + '…' - plugin_readme += f"- [**{dir_name}**]({gh_url}) `{plugin_ver}` ᠁ *{plugin_desc}*\n" + plugin_readme += f"[**{dir_name}**]({gh_url}) | `{plugin_ver}` | *{plugin_desc}*\n" txt = readme.format(plugin_readme) diff --git a/plugins/Chaika Metadata/hplugin.json b/plugins/Chaika Metadata/hplugin.json new file mode 100644 index 0000000..661cb8e --- /dev/null +++ b/plugins/Chaika Metadata/hplugin.json @@ -0,0 +1,14 @@ +{ + "id": "55747a41-789b-43dd-964a-2a6cb1761ff4", + "shortname": "chaika-metadata", + "name": "Chaika Metadata", + "version": "0.1.0b", + "description": "A plugin that can fetch metadata from Panda.Chaika", + "author": "Twiddly", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.6.1" + ] +} \ No newline at end of file diff --git a/plugins/Chaika Metadata/main.py b/plugins/Chaika Metadata/main.py new file mode 100644 index 0000000..aaa91c4 --- /dev/null +++ b/plugins/Chaika Metadata/main.py @@ -0,0 +1,453 @@ +# main.py +import __hpx__ as hpx +import gevent +import regex +import arrow +import datetime +import os +import urllib +import html + +from bs4 import BeautifulSoup +from PIL import Image, ImageChops + +log = hpx.get_logger("main") + +match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +match_url_end = r"\/?$" + +default_delay = 0.5 + +urls_regex = { + 'gallery': match_url_prefix + r"(panda\.chaika\.moe\/(archive|gallery)\/[0-9]+)" + match_url_end, +} + +urls = { + 'ch': 'https://panda.chaika.moe', + 'gallery': 'https://panda.chaika.moe/gallery/', + 'archive': 'https://panda.chaika.moe/archive/', + 'gallery_api': 'https://panda.chaika.moe/jsearch?gallery=', + 'archive_api': 'https://panda.chaika.moe/jsearch?archive=', + 'hash_api': 'https://panda.chaika.moe/jsearch?sha1=', + 'title_search': "https://panda.chaika.moe/galleries/?title={title}&tags=&category=&provider=&uploader=&rating_from=&rating_to=&filesize_from=&filesize_to=&filecount_from=&filecount_to=&sort=posted&asc_desc=desc&apply=" +} + +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} + +plugin_config = { + 'filename_search': False, # use the filename/folder-name for searching instead of gallery title + 'remove_namespaces': True, # remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX + 'gallery_results_limit': 10, # maximum amount of galleries to return + 'blacklist_tags': [], # tags to ignore when updating tags + 'add_gallery_url': True, # add ehentai url to gallery + 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default +} + +@hpx.subscribe("init") +def inited(): + plugin_config.update(hpx.get_plugin_config()) + + # set default delay values if not set + delays = hpx.get_setting("network", "delays", {}) + for u in (urls['ch'],): + if u not in delays: + log.info(f"Setting delay on {u} requests to {default_delay}") + delays[u] = default_delay + hpx.update_setting("network", "delays", delays) + +@hpx.subscribe("disable") +def disabled(): + pass + +@hpx.subscribe("remove") +def removed(): + pass + +@hpx.attach("Metadata.info") +def metadata_info_eh(): + return hpx.command.MetadataInfo( + identifier = "chaika", + name = "Panda.Chaika", + parser = urls_regex['gallery'], + sites = ("www.panda.chaika.moe",), + description = "Fetch metadata from Panda.Chaika", + models = ( + hpx.command.GetModelClass("Gallery"), + ) + ) + +@hpx.attach("Metadata.query") +def query(item, url, options, capture="chaika"): + log.info("Querying chaika for metadata") + mdata = [] + gurls = [] # tuple of (title, url) + # url was provided + if url: + log.info(f"url provided: {url} for {item}") + gurls.append((url, url)) + else: # manually search for id + log.info(f"url not provided for {item}") + # search with title + i_title = "" + i_hash = "" + if plugin_config.get("filename_search"): + sources = item.get_sources() + if sources: + # get folder/file name + i_title = os.path.split(sources[0])[1] + # remove ext + i_title = os.path.splitext(i_title)[0] + else: + if item.titles: + i_title = item.titles[0].name # make user choice + if i_title: + gurls = title_search(i_title) + + # search with hash + if not gurls: + pass + + log.info(f"found {len(gurls)} urls for item: {item}") + + # list is sorted by date added so we reverse it + gurls.reverse() + + log.debug(f"{gurls}") + final_gurls = [] + pref_lang = plugin_config.get('preferred_language') + if pref_lang: + for t in gurls: + if pref_lang.lower() in t[0].lower(): + final_gurls.insert(0, t) + continue + final_gurls.append(t) + else: + final_gurls = gurls + + for t, u in final_gurls: + g_type, g_id = parse_url(u) + if g_type and g_id: + mdata.append(hpx.command.MetadataData( + data={ + 'type': g_type, + 'id': g_id, + 'gallery_url': u, + 'apply_url': plugin_config.get('add_gallery_url', True), + })) + return tuple(mdata) + +@hpx.attach("Metadata.apply") +def apply(datatuple, item, options, capture="chaika"): + log.info("Applying metadata from chaika") + applied = False + + for d in datatuple: + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + + api_url = urls['archive_api'] if d.data['type'] == 'archive' else urls['gallery_api'] + api_url += str(d.data['id']) + + r = hpx.command.SingleGETRequest().request(api_url, req_props) + if r.ok: + response = r.json + if response and not 'result' in response: + mdata = filter_metadata(response, item, apply_url=d.data['apply_url'], gallery_url=d.data['gallery_url']) + applied = apply_metadata(mdata, item) + elif response: + log.warning(response) + log.info(f"Applied: {applied}") + return applied + +def title_search(title, session=None, _times=0): + "Searches on chaika for galleries with given title, returns a list of (title, matching gallery urls)" + search_url = urls['title_search'] + log.debug(f"searching with title: {title}") + f_url = search_url.format( + title=urllib.parse.quote_plus(title) + ) + log.debug(f"final url: {f_url}") + r = page_results(f_url, session=session) + if not r and not _times: + title = regex.sub(r"\(.+?\)|\[.+?\]", "", title) + title = " ".join(title.split()) + r = title_search(title, session, _times=_times+1) + return r + +def page_results(page_url, limit=None, session=None): + "Opens chaika page, parses for results, and then returns list of (title, url)" + found_urls = [] + if limit is None: + limit = plugin_config.get("gallery_results_limit") + + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + if session: + req_props.session = session + log.debug(f"COOKIES: {session.cookies}") + r = hpx.command.SingleGETRequest().request(page_url, req_props) + soup = BeautifulSoup(r.text, "html.parser") + results = soup.findAll("tr", class_="result-list", limit=limit) + results = [r.findAll('td')[1] for r in results] + # str(x.a.string) + found_urls = [(str(x.a.string), urls['ch'] + x.a['href']) for x in results] # title, url + + if not found_urls: + log.warning(f"No results found on url: {page_url}") + log.debug(f"HTML: {r.text}") + return found_urls + +def parse_url(url): + "Parses url into a tuple of gallery/archive and id" + gallery_id = None + stype = "gallery" + + gallery_id = regex.search('([0-9]+)', url) + if gallery_id: + gallery_id = gallery_id.group() + else: + log.warning("Error extracting id from url: {}".format(url)) + + if 'archive' in url: + stype = 'archive' + + return stype, int(gallery_id) + +def capitalize_text(text): + """ + better str.capitalize + """ + return " ".join(x.capitalize() for x in text.strip().split()) + +def filter_metadata(gdata, item, apply_url=False, gallery_url=None): + mdata = {} + replace_metadata = hpx.get_setting('metadata', 'replace_metadata') + if replace_metadata: + item.titles = [] + item.artists = [] + item.tags = [] + # flush is required so items are removed from the db + hpx.command.GetSession().flush() + + if replace_metadata: + mdata['titles'] = [] + if gdata['title']: + mdata['titles'].append((gdata['title'], 'english')) + if gdata['title_jpn']: + mdata['titles'].append((gdata['title_jpn'], 'japanese')) + else: + t = [] + if not item.title_by_language("english") and gdata['title']: + t.append((gdata['title'], 'english')) + if not item.title_by_language("japanese") and gdata['title_jpn']: + t.append((gdata['title_jpn'], 'japanese')) + if t: + mdata['titles'] = t + + if replace_metadata: + mdata['category'] = gdata['category'] + elif not item.category: + mdata['category'] = gdata['category'] + + if gdata['posted']: + if replace_metadata: + mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + elif not item.pub_date: + mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + + lang = "japanese" # def lang + if not replace_metadata and item.language: + lang = item.language.name + + artists = [] + circles = [] + parodies = [] + + extra_namespaces = ("artist", "parody", "group", "language") + mdata['tags'] = {} + for nstag in gdata['tags']: + onstag = nstag + nstag = nstag.replace('_', ' ') + blacklist_tags = plugin_config.get("blacklist_tags") + if blacklist_tags and (nstag in blacklist_tags or onstag in blacklist_tags): + continue + + ns = None + if ':' in nstag: + ns, t = nstag.split(':', 1) + else: + t = nstag + + if ns == 'language' and t != 'translated': + lang = t + elif ns == "artist": + artists.append(t) + elif ns == "group": + circles.append(t) + elif ns == "parody": + parodies.append(t) + + if not (plugin_config.get("remove_namespaces") and ns in extra_namespaces): + mdata['tags'].setdefault(ns, []).append(t) + else: + log.debug(f"removing namespace {ns}") + + log.debug(f"tags: {mdata['tags']}") + + if replace_metadata: + mdata['language'] = lang + elif not item.language: + mdata['language'] = lang + + if parodies: + if replace_metadata: + item.parodies = [] + mdata['parodies'] = parodies + elif not item.parodies: + mdata['parodies'] = parodies + + if artists: + a_circles = [] + for a in artists: + a_circles.append((a, tuple(circles))) + if replace_metadata: + item.artists = [] + mdata['artists'] = a_circles + elif not item.artists: + mdata['artists'] = a_circles + + if apply_url: + if gdata.get('gallery', False): + mdata['urls'] = [urls['gallery']+f"{gdata['gallery']}/"] + elif gallery_url: + mdata['urls'] = [gallery_url] + + return mdata + +language_model = hpx.command.GetModelClass("Language") +title_model = hpx.command.GetModelClass("Title") +artist_model = hpx.command.GetModelClass("Artist") +parody_model = hpx.command.GetModelClass("Parody") +circle_model = hpx.command.GetModelClass("Circle") +url_model = hpx.command.GetModelClass("Url") +namespacetags_model = hpx.command.GetModelClass("NamespaceTags") + +def apply_metadata(data, gallery): + """ + data = { + 'titles': None, # [(title, language),...] + 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] + 'category': None, + 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} + 'pub_date': None, # DateTime object or Arrow object + 'language': None, + 'urls': None # [url, ...] + } + """ + + applied = False + + log.debug(f"data: {data}") + + if isinstance(data.get('titles'), (list, tuple)): + for t, l in data['titles']: + gtitle = None + if t: + t = html.unescape(t) + gtitle = title_model(name=t) + if t and l: + gtitle.language = language_model.as_unique(name=l) + if gtitle: + gallery.update("titles", gtitle) + log.debug("applied titles") + applied = True + + if isinstance(data.get('artists'), (list, tuple)): + for a, c in data['artists']: + if a: + gartist = artist_model.as_unique(name=capitalize_text(a)) + if not gartist in gallery.artists: + gallery.update("artists", gartist) + if a and c: + for circlename in [x for x in c if x]: + gcircle = circle_model.as_unique(name=capitalize_text(circlename)) + if not gcircle in gartist.circles: + gartist.update("circles", gcircle) + log.debug("applied artists") + applied = True + + if isinstance(data.get('parodies'), (list, tuple)): + for p in data['parodies']: + if p: + gparody = parody_model.as_unique(name=capitalize_text(p)) + if not gparody in gallery.parodies: + gallery.update("parodies", gparody) + + log.debug("applied parodies") + applied = True + + if data.get('category'): + gallery.update("category", name=data['category']) + log.debug("applied category") + applied = True + + if data.get('language'): + gallery.update("language", name=data['language']) + log.debug("applied language") + applied = True + + if isinstance(data.get('tags'), (dict, list)): + if isinstance(data['tags'], list): + data['tags'] = {None: data['tags']} + ns_tags = [] + for ns, tags in data['tags'].items(): + if ns is not None: + ns = ns.strip() + if ns and ns.lower() == 'misc': + ns = None + for t in tags: + t = t.strip() + ns_tags.append(namespacetags_model.as_unique(ns=ns, tag=t)) + + for nstag in ns_tags: + if nstag not in gallery.tags: + gallery.tags.append(nstag) + log.debug("applied tags") + applied = True + + if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): + pub_date = data['pub_date'] + gallery.update("pub_date", pub_date) + log.debug("applied pub_date") + applied = True + + if isinstance(data.get('urls'), (list, tuple)): + existing_urls = [x.name.lower() for x in gallery.urls] + urls = [] + for u in data['urls']: + if u.lower() not in existing_urls: + urls.append(url_model(name=u)) + gallery.update("urls", urls) + log.debug("applied urls") + applied = True + + return applied + +def is_image_greyscale(filepath): + "Check if image is monochrome (1 channel or 3 identical channels)" + im = Image.open(filepath).convert("RGB") + if im.mode not in ("L", "RGB"): + return False + + if im.mode == "RGB": + rgb = im.split() + if ImageChops.difference(rgb[0],rgb[1]).getextrema()[1] != 0: + return False + if ImageChops.difference(rgb[0],rgb[2]).getextrema()[1] != 0: + return False + return True \ No newline at end of file diff --git a/plugins/Chaika Metadata/readme.md b/plugins/Chaika Metadata/readme.md new file mode 100644 index 0000000..721415e --- /dev/null +++ b/plugins/Chaika Metadata/readme.md @@ -0,0 +1,38 @@ +EHentai Metadata +---------------------------- + +> This plugin fetches metadata from Panda.Chaika + +## Configuration + +Configure this plugin by adding `chaika-metadata` to the `plugin.config` namespace in your `config.yaml`: +```yaml +plugin: + config: + chaika-metadata: + option1: True + option2: + - item 1 + - item 2 +``` + +#### Available options + +Name | Default | Description +--- | --- | --- +`filename_search` | `false` | use the filename/folder-name for searching instead of gallery title +`remove_namespaces` | `true` | remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX +`gallery_results_limit` | `10` | maximum amount of galleries to return +`blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` or `tag` strings +`add_gallery_url` | `true` | add chaika url to gallery +`preferred_language` | `english` | preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default + + +## Things yet to be implemented + +- File similarity search + +# Changelog + +- `0.1.0b` + - first version \ No newline at end of file diff --git a/plugins/Chaika Metadata/test.py b/plugins/Chaika Metadata/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/Chaika Metadata/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file From e9cd549ffc837143fd0c894ba3e0a844d97cab60 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Wed, 28 Nov 2018 20:30:40 +0100 Subject: [PATCH 34/68] small fixes; --- .travis.yml | 2 +- plugins/Chaika Metadata/readme.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 8fedbec..b567b32 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,7 +11,7 @@ env: global: - GH_USER=Twiddly - GH_MAIL=pew@pewpew.moe - - REPOE=happypandax/plugins + - REPO=happypandax/plugins - secure: XiUXHPc5pgrdIxHkYXzGRDAqdDCpuszKAJ/75+ZSjH+/Nv5uYLtP9LXzmOZm/x6rxIyNXP408sTnULm+Y+HfWoNV1sCaEwa50NniCPcbuEOtKe0N8o6VKbAmIaxyRZaThvDdIrB2U7VDI9Y+qeRuYfNEM77tEXklzu5SF2sfOAyaMQTdh1qCbGz4++EcZ2451ov8ZHTmHpEMCbUNeK9QZFSA14exFd5VlKYlDrehjoqFATR0Uypcjufh/uJluOWFpscG9duR2aChHkxZu/hH7UYNYRQG/N1VRYUR0g+tQ3CDMWBzIjbkASorZJydy1p53UVUEkTMwhSFw1SGCdAhobPUXlpeYFp9C932ODEhUkzEM3GmmEeV+53mq7nzi6bmOL3SdsWJnf5EZrPI2OOVqgkf2Nh/LkmhANlypcKDmWJOK+izUuMH6q/cl0ZnLSI+WsZU4d1WStfMrqNHE+/3fpwG8yf7CJ2788tzYHyPO9vzJvGsAoY3Z272BQ8rm6yFc/SWE6Mc93wC0vZ5Bd1WfOGMRWn6GVyvvyFKri86pgGj0N7BxXInMS4EWc/AD6r5RLc8xrTYKs0u+VHFAtWnnv7NlhXHnZUqPcSzpAvrhvc91575o7HNC2z/czJIT73eN1oXUMFqTkCvxYg2mC41VSvxf70CPYXAu/DBHLn1uio= diff --git a/plugins/Chaika Metadata/readme.md b/plugins/Chaika Metadata/readme.md index 721415e..880037b 100644 --- a/plugins/Chaika Metadata/readme.md +++ b/plugins/Chaika Metadata/readme.md @@ -1,4 +1,4 @@ -EHentai Metadata +Chaika Metadata ---------------------------- > This plugin fetches metadata from Panda.Chaika From 3008c99aad020713b95a95a562e2fd16fbc489c3 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 30 Mar 2019 22:07:50 +0100 Subject: [PATCH 35/68] update Ehentai Metadata --- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 21 +++++++++++++-------- plugins/EHentai Metadata/readme.md | 3 +++ 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index 8ad7059..92a32c2 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "0.3.0b", + "version": "0.4.0b", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 1bd5ff7..d04e23e 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -206,14 +206,19 @@ def eh_page_results(eh_page_url, limit=None, session=None): log.debug(f"COOKIES: {session.cookies}") r = hpx.command.SingleGETRequest().request(eh_page_url, req_props) soup = BeautifulSoup(r.text, "html.parser") - thumb_view = False - dmi_div = soup.find("div", id="dmi") - if dmi_div and dmi_div.a and "list" in str(dmi_div.a.string).lower(): - thumb_view = True - if thumb_view: - results = soup.findAll("div", class_="id2", limit=limit) - else: - results = soup.findAll("div", class_="it5", limit=limit) + list_style = "compact" + dmi_div = soup.find("div", id="dms") + if dmi_div: + list_style = dmi_div.find("option", selected=True).string.lower() + results = [] + if list_style == "compact": + results = soup.findAll("td", class_="gl3c glname", limit=limit) + elif list_style == "minimal": + results = soup.findAll("td", class_="gl3m glname", limit=limit) + elif list_style == "extended": + results = soup.findAll("div", class_="gl4e glname", limit=limit) + elif list_style == "thumbnail": + results = soup.findAll("div", class_="gl4t glname", limit=limit) # str(x.a.string) found_urls = [(str(x.a.string), x.a['href']) for x in results] # title, url diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index f6c964c..eeabd71 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -37,6 +37,9 @@ Name | Default | Description # Changelog +- `0.4.0b` + - updated for new EH website design changes + - `0.3.0b` - add a default delay on `https://api.e-hentai.org/` requests, this value can be tweaked in `network.delays` inside your`config.yaml` From f38a90c7a75d4120aeaa675dd27aabf9573ed9bc Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 30 Mar 2019 22:08:17 +0100 Subject: [PATCH 36/68] update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0d3fee2..5faa9f8 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Name | Version | Description --- | --- | --- [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `0.1.0b` | *A plugin that can fetch metadata from Panda.Chaika* [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `0.2.0b` | *A plugin that can login to E-Hentai & ExHentai* -[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `0.3.0b` | *A plugin that can fetch metadata from E-Hentai & ExHentai* +[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `0.4.0b` | *A plugin that can fetch metadata from E-Hentai & ExHentai* [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `0.3.0b` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* From e53065deb750624e2af899ca748cad685f5b6958 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 30 Mar 2019 21:09:18 +0000 Subject: [PATCH 37/68] Update EHentai Metadata (#19) * update Ehentai Metadata * update readme --- README.md | 2 +- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 21 +++++++++++++-------- plugins/EHentai Metadata/readme.md | 3 +++ 4 files changed, 18 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 0d3fee2..5faa9f8 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ Name | Version | Description --- | --- | --- [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `0.1.0b` | *A plugin that can fetch metadata from Panda.Chaika* [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `0.2.0b` | *A plugin that can login to E-Hentai & ExHentai* -[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `0.3.0b` | *A plugin that can fetch metadata from E-Hentai & ExHentai* +[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `0.4.0b` | *A plugin that can fetch metadata from E-Hentai & ExHentai* [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `0.3.0b` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index 8ad7059..92a32c2 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "0.3.0b", + "version": "0.4.0b", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 1bd5ff7..d04e23e 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -206,14 +206,19 @@ def eh_page_results(eh_page_url, limit=None, session=None): log.debug(f"COOKIES: {session.cookies}") r = hpx.command.SingleGETRequest().request(eh_page_url, req_props) soup = BeautifulSoup(r.text, "html.parser") - thumb_view = False - dmi_div = soup.find("div", id="dmi") - if dmi_div and dmi_div.a and "list" in str(dmi_div.a.string).lower(): - thumb_view = True - if thumb_view: - results = soup.findAll("div", class_="id2", limit=limit) - else: - results = soup.findAll("div", class_="it5", limit=limit) + list_style = "compact" + dmi_div = soup.find("div", id="dms") + if dmi_div: + list_style = dmi_div.find("option", selected=True).string.lower() + results = [] + if list_style == "compact": + results = soup.findAll("td", class_="gl3c glname", limit=limit) + elif list_style == "minimal": + results = soup.findAll("td", class_="gl3m glname", limit=limit) + elif list_style == "extended": + results = soup.findAll("div", class_="gl4e glname", limit=limit) + elif list_style == "thumbnail": + results = soup.findAll("div", class_="gl4t glname", limit=limit) # str(x.a.string) found_urls = [(str(x.a.string), x.a['href']) for x in results] # title, url diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index f6c964c..eeabd71 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -37,6 +37,9 @@ Name | Default | Description # Changelog +- `0.4.0b` + - updated for new EH website design changes + - `0.3.0b` - add a default delay on `https://api.e-hentai.org/` requests, this value can be tweaked in `network.delays` inside your`config.yaml` From ecf9c2803bd69537a79a97b2c9becfe467a18b98 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 4 Jun 2019 03:47:40 +0200 Subject: [PATCH 38/68] Updated to reflect new changes in HPX v0.10.0; --- .travis.yml.orig | 23 ++ plugins/Chaika Metadata/hplugin.json | 5 +- plugins/Chaika Metadata/main.py | 443 ++++++++++----------- plugins/Chaika Metadata/readme.md | 3 + plugins/EHentai Login/.info | Bin 0 -> 117 bytes plugins/EHentai Login/hplugin.json | 6 +- plugins/EHentai Login/main.py | 53 ++- plugins/EHentai Login/readme.md | 18 +- plugins/EHentai Login/site/index.html | 54 +++ plugins/EHentai Login/site/script.js | 124 ++++++ plugins/EHentai Metadata/hplugin.json | 6 +- plugins/EHentai Metadata/main.py | 529 ++++++++++++++------------ plugins/EHentai Metadata/readme.md | 5 +- plugins/File Metadata/hplugin.json | 5 +- plugins/File Metadata/main.py | 144 ++++--- plugins/File Metadata/readme.md | 3 + 16 files changed, 848 insertions(+), 573 deletions(-) create mode 100644 .travis.yml.orig create mode 100644 plugins/EHentai Login/.info create mode 100644 plugins/EHentai Login/site/index.html create mode 100644 plugins/EHentai Login/site/script.js diff --git a/.travis.yml.orig b/.travis.yml.orig new file mode 100644 index 0000000..b567b32 --- /dev/null +++ b/.travis.yml.orig @@ -0,0 +1,23 @@ +notifications: + email: + on_success: never + on_failure: always +language: python +python: 3.6 +addons: + apt: + update: true +env: + global: + - GH_USER=Twiddly + - GH_MAIL=pew@pewpew.moe + - REPO=happypandax/plugins + - secure: XiUXHPc5pgrdIxHkYXzGRDAqdDCpuszKAJ/75+ZSjH+/Nv5uYLtP9LXzmOZm/x6rxIyNXP408sTnULm+Y+HfWoNV1sCaEwa50NniCPcbuEOtKe0N8o6VKbAmIaxyRZaThvDdIrB2U7VDI9Y+qeRuYfNEM77tEXklzu5SF2sfOAyaMQTdh1qCbGz4++EcZ2451ov8ZHTmHpEMCbUNeK9QZFSA14exFd5VlKYlDrehjoqFATR0Uypcjufh/uJluOWFpscG9duR2aChHkxZu/hH7UYNYRQG/N1VRYUR0g+tQ3CDMWBzIjbkASorZJydy1p53UVUEkTMwhSFw1SGCdAhobPUXlpeYFp9C932ODEhUkzEM3GmmEeV+53mq7nzi6bmOL3SdsWJnf5EZrPI2OOVqgkf2Nh/LkmhANlypcKDmWJOK+izUuMH6q/cl0ZnLSI+WsZU4d1WStfMrqNHE+/3fpwG8yf7CJ2788tzYHyPO9vzJvGsAoY3Z272BQ8rm6yFc/SWE6Mc93wC0vZ5Bd1WfOGMRWn6GVyvvyFKri86pgGj0N7BxXInMS4EWc/AD6r5RLc8xrTYKs0u+VHFAtWnnv7NlhXHnZUqPcSzpAvrhvc91575o7HNC2z/czJIT73eN1oXUMFqTkCvxYg2mC41VSvxf70CPYXAu/DBHLn1uio= + + +script: + - python3 build.py + - git config --local user.name "$GH_USER" + - git config --local user.email "$GH_MAIL" + - git commit -m "build" + - git push --quiet "https://$GITHUB_TOKEN@github.com/$REPO.git" master > /dev/null 2>&1 diff --git a/plugins/Chaika Metadata/hplugin.json b/plugins/Chaika Metadata/hplugin.json index 661cb8e..1b6ab70 100644 --- a/plugins/Chaika Metadata/hplugin.json +++ b/plugins/Chaika Metadata/hplugin.json @@ -2,13 +2,14 @@ "id": "55747a41-789b-43dd-964a-2a6cb1761ff4", "shortname": "chaika-metadata", "name": "Chaika Metadata", - "version": "0.1.0b", + "version": "1.0.0", "description": "A plugin that can fetch metadata from Panda.Chaika", "author": "Twiddly", + "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata", "website": "https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata", "entry": "main.py", "test": "test.py", "require": [ - "happypandax >= 0.6.1" + "happypandax >= 0.10.0" ] } \ No newline at end of file diff --git a/plugins/Chaika Metadata/main.py b/plugins/Chaika Metadata/main.py index aaa91c4..8d3fa21 100644 --- a/plugins/Chaika Metadata/main.py +++ b/plugins/Chaika Metadata/main.py @@ -1,6 +1,5 @@ # main.py import __hpx__ as hpx -import gevent import regex import arrow import datetime @@ -13,16 +12,16 @@ log = hpx.get_logger("main") -match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. -match_url_end = r"\/?$" +MATCH_URL_PREFIX = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +MATCH_URL_END = r"\/?$" -default_delay = 0.5 +DEFAULT_DELAY = 0.5 -urls_regex = { - 'gallery': match_url_prefix + r"(panda\.chaika\.moe\/(archive|gallery)\/[0-9]+)" + match_url_end, +URLS_REGEX = { + 'gallery': MATCH_URL_PREFIX + r"(panda\.chaika\.moe\/(archive|gallery)\/[0-9]+)" + MATCH_URL_END, } -urls = { +URLS = { 'ch': 'https://panda.chaika.moe', 'gallery': 'https://panda.chaika.moe/gallery/', 'archive': 'https://panda.chaika.moe/archive/', @@ -34,7 +33,7 @@ HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} -plugin_config = { +PLUGIN_CONFIG = { 'filename_search': False, # use the filename/folder-name for searching instead of gallery title 'remove_namespaces': True, # remove superfluous namespaces like 'artist', 'language' and 'group' because they are handled specially in HPX 'gallery_results_limit': 10, # maximum amount of galleries to return @@ -45,16 +44,20 @@ @hpx.subscribe("init") def inited(): - plugin_config.update(hpx.get_plugin_config()) + PLUGIN_CONFIG.update(hpx.get_plugin_config()) # set default delay values if not set delays = hpx.get_setting("network", "delays", {}) - for u in (urls['ch'],): + for u in (URLS['ch'],): if u not in delays: - log.info(f"Setting delay on {u} requests to {default_delay}") - delays[u] = default_delay + log.info(f"Setting delay on {u} requests to {DEFAULT_DELAY}") + delays[u] = DEFAULT_DELAY hpx.update_setting("network", "delays", delays) +@hpx.subscribe('config_update') +def config_update(cfg): + PLUGIN_CONFIG.update(cfg) + @hpx.subscribe("disable") def disabled(): pass @@ -64,106 +67,116 @@ def removed(): pass @hpx.attach("Metadata.info") -def metadata_info_eh(): +def metadata_info(): return hpx.command.MetadataInfo( identifier = "chaika", name = "Panda.Chaika", - parser = urls_regex['gallery'], + parser = URLS_REGEX['gallery'], sites = ("www.panda.chaika.moe",), description = "Fetch metadata from Panda.Chaika", models = ( - hpx.command.GetModelClass("Gallery"), + hpx.command.GetDatabaseModel("Gallery"), ) ) -@hpx.attach("Metadata.query") -def query(item, url, options, capture="chaika"): +@hpx.attach("Metadata.query", trigger="chaika") +def query(itemtuple): log.info("Querying chaika for metadata") mdata = [] - gurls = [] # tuple of (title, url) - # url was provided - if url: - log.info(f"url provided: {url} for {item}") - gurls.append((url, url)) - else: # manually search for id - log.info(f"url not provided for {item}") - # search with title - i_title = "" - i_hash = "" - if plugin_config.get("filename_search"): - sources = item.get_sources() - if sources: - # get folder/file name - i_title = os.path.split(sources[0])[1] - # remove ext - i_title = os.path.splitext(i_title)[0] + for mitem in itemtuple: + item = mitem.item + url = mitem.url + gurls = [] # tuple of (title, url) + # url was provided + if url: + log.info(f"url provided: {url} for {item}") + gurls.append((url, url)) + else: # manually search for id + log.info(f"url not provided for {item}") + # search with title + i_title = "" + i_hash = "" + if PLUGIN_CONFIG.get("filename_search"): + sources = item.get_sources() + if sources: + # get folder/file name + i_title = os.path.split(sources[0])[1] + # remove ext + i_title = os.path.splitext(i_title)[0] + else: + if item.titles: + i_title = item.titles[0].name # make user choice + if i_title: + gurls = title_search(i_title) + + # search with hash + if not gurls: + pass + + log.info(f"found {len(gurls)} urls for item: {item}") + + # list is sorted by date added so we reverse it + gurls.reverse() + + log.debug(f"{gurls}") + final_gurls = [] + pref_lang = PLUGIN_CONFIG.get('preferred_language') + if pref_lang: + for t in gurls: + if pref_lang.lower() in t[0].lower(): + final_gurls.insert(0, t) + continue + final_gurls.append(t) else: - if item.titles: - i_title = item.titles[0].name # make user choice - if i_title: - gurls = title_search(i_title) - - # search with hash - if not gurls: - pass - - log.info(f"found {len(gurls)} urls for item: {item}") - - # list is sorted by date added so we reverse it - gurls.reverse() - - log.debug(f"{gurls}") - final_gurls = [] - pref_lang = plugin_config.get('preferred_language') - if pref_lang: - for t in gurls: - if pref_lang.lower() in t[0].lower(): - final_gurls.insert(0, t) - continue - final_gurls.append(t) - else: - final_gurls = gurls - - for t, u in final_gurls: - g_type, g_id = parse_url(u) - if g_type and g_id: - mdata.append(hpx.command.MetadataData( - data={ - 'type': g_type, - 'id': g_id, - 'gallery_url': u, - 'apply_url': plugin_config.get('add_gallery_url', True), - })) + final_gurls = gurls + + for t, u in final_gurls: + g_type, g_id = parse_url(u) + if g_type and g_id: + mdata.append(hpx.command.MetadataData( + metadataitem = mitem, + title=t, + url=u, + data={ + 'type': g_type, + 'id': g_id, + 'gallery_url': u, + })) return tuple(mdata) -@hpx.attach("Metadata.apply") -def apply(datatuple, item, options, capture="chaika"): +@hpx.attach("Metadata.apply", trigger="chaika") +def apply(datatuple): log.info("Applying metadata from chaika") - applied = False - - for d in datatuple: + mresult = [] + + for mdata in datatuple: + applied = False # prepare request req_props = hpx.command.RequestProperties( headers=HEADERS, ) - api_url = urls['archive_api'] if d.data['type'] == 'archive' else urls['gallery_api'] - api_url += str(d.data['id']) + api_url = URLS['archive_api'] if mdata.data['type'] == 'archive' else URLS['gallery_api'] + api_url += str(mdata.data['id']) r = hpx.command.SingleGETRequest().request(api_url, req_props) if r.ok: response = r.json if response and not 'result' in response: - mdata = filter_metadata(response, item, apply_url=d.data['apply_url'], gallery_url=d.data['gallery_url']) - applied = apply_metadata(mdata, item) + filtered_data = format_metadata(response, mdata.item, apply_url=PLUGIN_CONFIG.get('add_gallery_url', True), gallery_url=mdata.data['gallery_url']) + applied = apply_metadata(filtered_data, mdata.item, mdata.options) elif response: log.warning(response) - log.info(f"Applied: {applied}") - return applied + reason = "" + if not applied and 'result' in response: + reason = response['result'] + mresult.append(hpx.command.MetadataResult(data=mdata, status=applied, reason=reason)) + log.info(f"Applied: {applied}") + return tuple(mresult) def title_search(title, session=None, _times=0): "Searches on chaika for galleries with given title, returns a list of (title, matching gallery urls)" - search_url = urls['title_search'] + search_url = URLS['title_search'] log.debug(f"searching with title: {title}") f_url = search_url.format( title=urllib.parse.quote_plus(title) @@ -180,7 +193,7 @@ def page_results(page_url, limit=None, session=None): "Opens chaika page, parses for results, and then returns list of (title, url)" found_urls = [] if limit is None: - limit = plugin_config.get("gallery_results_limit") + limit = PLUGIN_CONFIG.get("gallery_results_limit") # prepare request req_props = hpx.command.RequestProperties( @@ -194,7 +207,7 @@ def page_results(page_url, limit=None, session=None): results = soup.findAll("tr", class_="result-list", limit=limit) results = [r.findAll('td')[1] for r in results] # str(x.a.string) - found_urls = [(str(x.a.string), urls['ch'] + x.a['href']) for x in results] # title, url + found_urls = [(str(x.a.string), URLS['ch'] + x.a['href']) for x in results] # title, url if not found_urls: log.warning(f"No results found on url: {page_url}") @@ -223,56 +236,54 @@ def capitalize_text(text): """ return " ".join(x.capitalize() for x in text.strip().split()) -def filter_metadata(gdata, item, apply_url=False, gallery_url=None): +def format_metadata(gdata, item, apply_url=False, gallery_url=None): + """ + Formats metadata to look like this for apply_metadata: + data = { + 'titles': None, # [(title, language),...] + 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] + 'category': None, + 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} + 'pub_date': None, # DateTime object or Arrow object + 'language': None, + 'urls': None # [url, ...] + } + """ mdata = {} - replace_metadata = hpx.get_setting('metadata', 'replace_metadata') - if replace_metadata: - item.titles = [] - item.artists = [] - item.tags = [] - # flush is required so items are removed from the db - hpx.command.GetSession().flush() - - if replace_metadata: - mdata['titles'] = [] - if gdata['title']: - mdata['titles'].append((gdata['title'], 'english')) - if gdata['title_jpn']: - mdata['titles'].append((gdata['title_jpn'], 'japanese')) - else: - t = [] - if not item.title_by_language("english") and gdata['title']: - t.append((gdata['title'], 'english')) - if not item.title_by_language("japanese") and gdata['title_jpn']: - t.append((gdata['title_jpn'], 'japanese')) - if t: - mdata['titles'] = t - - if replace_metadata: - mdata['category'] = gdata['category'] - elif not item.category: - mdata['category'] = gdata['category'] + mdata['titles'] = [] + + parsed_text = hpx.command.ItemTextParser(gdata['title']) + + parsed_title = parsed_text.extract_title() + if parsed_title: + parsed_title = parsed_title[0] + mdata['titles'].append((parsed_title or gdata['title'], 'english')) + + mdata['titles'].append((gdata['title_jpn'], 'japanese')) + + + mdata['category'] = gdata['category'] if gdata['posted']: - if replace_metadata: - mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) - elif not item.pub_date: - mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + mdata['pub_date'] = arrow.Arrow.fromtimestamp(gdata['posted']) + + lang = "japanese" # default language - lang = "japanese" # def lang - if not replace_metadata and item.language: - lang = item.language.name + artists = set() + circles = set() + parodies = set() - artists = [] - circles = [] - parodies = [] + parsed_artists = parsed_text.extract_artist() + parsed_circles = parsed_text.extract_circle() - extra_namespaces = ("artist", "parody", "group", "language") + extranous_namespaces = ("artist", "parody", "group", "language") mdata['tags'] = {} + for nstag in gdata['tags']: onstag = nstag nstag = nstag.replace('_', ' ') - blacklist_tags = plugin_config.get("blacklist_tags") + blacklist_tags = PLUGIN_CONFIG.get("blacklist_tags") if blacklist_tags and (nstag in blacklist_tags or onstag in blacklist_tags): continue @@ -285,58 +296,63 @@ def filter_metadata(gdata, item, apply_url=False, gallery_url=None): if ns == 'language' and t != 'translated': lang = t elif ns == "artist": - artists.append(t) + for a in artists: # the artist extracted from the title likely has better capitalization, so choose that instead + if a.lower() == t.lower(): + artists.add(a) + break + else: + artists.add(t) elif ns == "group": - circles.append(t) + for c in circles: # the circle extracted from the title likely has better capitalization, so choose that instead + if c.lower() == t.lower(): + circles.add(c) + break + else: + circles.add(t) elif ns == "parody": - parodies.append(t) + parodies.add(t) - if not (plugin_config.get("remove_namespaces") and ns in extra_namespaces): + if not (PLUGIN_CONFIG.get("remove_namespaces") and ns in extranous_namespaces): mdata['tags'].setdefault(ns, []).append(t) else: log.debug(f"removing namespace {ns}") log.debug(f"tags: {mdata['tags']}") - if replace_metadata: - mdata['language'] = lang - elif not item.language: - mdata['language'] = lang + mdata['language'] = lang if parodies: - if replace_metadata: - item.parodies = [] - mdata['parodies'] = parodies - elif not item.parodies: - mdata['parodies'] = parodies + mdata['parodies'] = parodies if artists: a_circles = [] for a in artists: - a_circles.append((a, tuple(circles))) - if replace_metadata: - item.artists = [] - mdata['artists'] = a_circles - elif not item.artists: - mdata['artists'] = a_circles + a_circles.append((a, tuple(circles))) # assign circles to each artist + mdata['artists'] = a_circles if apply_url: if gdata.get('gallery', False): - mdata['urls'] = [urls['gallery']+f"{gdata['gallery']}/"] + mdata['urls'] = [URLS['gallery']+f"{gdata['gallery']}/"] elif gallery_url: mdata['urls'] = [gallery_url] return mdata -language_model = hpx.command.GetModelClass("Language") -title_model = hpx.command.GetModelClass("Title") -artist_model = hpx.command.GetModelClass("Artist") -parody_model = hpx.command.GetModelClass("Parody") -circle_model = hpx.command.GetModelClass("Circle") -url_model = hpx.command.GetModelClass("Url") -namespacetags_model = hpx.command.GetModelClass("NamespaceTags") - -def apply_metadata(data, gallery): +GalleryData = hpx.command.GalleryData +LanguageData = hpx.command.LanguageData +TitleData = hpx.command.TitleData +ArtistData = hpx.command.ArtistData +ArtistNameData = hpx.command.ArtistNameData +ParodyData = hpx.command.ParodyData +ParodyNameData = hpx.command.ParodyNameData +CircleData = hpx.command.CircleData +CategoryData = hpx.command.CategoryData +UrlData = hpx.command.UrlData +NamespaceTagData= hpx.command.NamespaceTagData +TagData= hpx.command.TagData +NamespaceData = hpx.command.NamespaceData + +def apply_metadata(data, gallery, options): """ data = { 'titles': None, # [(title, language),...] @@ -350,61 +366,66 @@ def apply_metadata(data, gallery): } """ - applied = False - log.debug(f"data: {data}") - if isinstance(data.get('titles'), (list, tuple)): + gdata = GalleryData() + + if isinstance(data.get('titles'), (list, tuple, set)): + gtitles = [] for t, l in data['titles']: gtitle = None if t: t = html.unescape(t) - gtitle = title_model(name=t) + gtitle = TitleData(name=t) if t and l: - gtitle.language = language_model.as_unique(name=l) + gtitle.language = LanguageData(name=l) if gtitle: - gallery.update("titles", gtitle) - log.debug("applied titles") - applied = True + gtitles.append(gtitle) - if isinstance(data.get('artists'), (list, tuple)): + if gtitles: + gdata.titles = gtitles + log.debug("applied titles") + + if isinstance(data.get('artists'), (list, tuple, set)): + gartists = [] for a, c in data['artists']: if a: - gartist = artist_model.as_unique(name=capitalize_text(a)) - if not gartist in gallery.artists: - gallery.update("artists", gartist) - if a and c: - for circlename in [x for x in c if x]: - gcircle = circle_model.as_unique(name=capitalize_text(circlename)) - if not gcircle in gartist.circles: - gartist.update("circles", gcircle) - log.debug("applied artists") - applied = True - - if isinstance(data.get('parodies'), (list, tuple)): + gartist = ArtistData(names=[ArtistNameData(name=capitalize_text(a))]) + gartists.append(gartist) + + if c: + gcircles = [] + for circlename in [x for x in c if x]: + gcircles.append(CircleData(name=capitalize_text(circlename))) + gartist.circles = gcircles + + if gartists: + gdata.artists = gartists + log.debug("applied artists") + + if isinstance(data.get('parodies'), (list, tuple, set)): + gparodies = [] for p in data['parodies']: if p: - gparody = parody_model.as_unique(name=capitalize_text(p)) - if not gparody in gallery.parodies: - gallery.update("parodies", gparody) + gparody = ParodyData(names=[ParodyNameData(name=capitalize_text(p))]) + gparodies.append(gparody) - log.debug("applied parodies") - applied = True + if gparodies: + gdata.parodies = gparodies + log.debug("applied parodies") if data.get('category'): - gallery.update("category", name=data['category']) + gdata.category = CategoryData(name=data['category']) log.debug("applied category") - applied = True if data.get('language'): - gallery.update("language", name=data['language']) + gdata.language = LanguageData(name=data['language']) log.debug("applied language") - applied = True if isinstance(data.get('tags'), (dict, list)): if isinstance(data['tags'], list): data['tags'] = {None: data['tags']} - ns_tags = [] + gnstags = [] for ns, tags in data['tags'].items(): if ns is not None: ns = ns.strip() @@ -412,42 +433,32 @@ def apply_metadata(data, gallery): ns = None for t in tags: t = t.strip() - ns_tags.append(namespacetags_model.as_unique(ns=ns, tag=t)) - - for nstag in ns_tags: - if nstag not in gallery.tags: - gallery.tags.append(nstag) - log.debug("applied tags") - applied = True + if t: + kw = {'tag': TagData(name=t)} + if ns: + kw['namespace'] = NamespaceData(name=ns) + gnstags.append(NamespaceTagData(**kw)) + + if gnstags: + gdata.tags = gnstags + log.debug("applied tags") if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): pub_date = data['pub_date'] - gallery.update("pub_date", pub_date) + gdata.pub_date = pub_date log.debug("applied pub_date") - applied = True if isinstance(data.get('urls'), (list, tuple)): - existing_urls = [x.name.lower() for x in gallery.urls] - urls = [] + gurls = [] for u in data['urls']: - if u.lower() not in existing_urls: - urls.append(url_model(name=u)) - gallery.update("urls", urls) - log.debug("applied urls") - applied = True - - return applied - -def is_image_greyscale(filepath): - "Check if image is monochrome (1 channel or 3 identical channels)" - im = Image.open(filepath).convert("RGB") - if im.mode not in ("L", "RGB"): - return False - - if im.mode == "RGB": - rgb = im.split() - if ImageChops.difference(rgb[0],rgb[1]).getextrema()[1] != 0: - return False - if ImageChops.difference(rgb[0],rgb[2]).getextrema()[1] != 0: - return False - return True \ No newline at end of file + if u: + gurls.append(UrlData(name=u)) + if gurls: + gdata.urls = gurls + log.debug("applied urls") + + applied = hpx.command.UpdateItemData(gallery, gdata, options=options) + + log.debug(f"applied: {applied}") + + return applied \ No newline at end of file diff --git a/plugins/Chaika Metadata/readme.md b/plugins/Chaika Metadata/readme.md index 880037b..28461ee 100644 --- a/plugins/Chaika Metadata/readme.md +++ b/plugins/Chaika Metadata/readme.md @@ -33,6 +33,9 @@ Name | Default | Description - File similarity search # Changelog + +- `1.0.0` + - Updated to reflect new changes in HPX v0.10.0 - `0.1.0b` - first version \ No newline at end of file diff --git a/plugins/EHentai Login/.info b/plugins/EHentai Login/.info new file mode 100644 index 0000000000000000000000000000000000000000..0b2cc0930709ca268f8326631bea07b7ca228bad GIT binary patch literal 117 zcmZo*t}SHHh~QvgU`VaVNX;ur%q(Q=h~NeCGYgX9b5nDZQj6j= 0.5.0" + "happypandax >= 0.10.0" ] } \ No newline at end of file diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 510b1f1..15a19e6 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -1,12 +1,14 @@ # main.py -from bs4 import BeautifulSoup import __hpx__ as hpx -import gevent import pickle import os +from bs4 import BeautifulSoup + log = hpx.get_logger("main") + + current_user_name = "" status_text = "" response = None @@ -14,7 +16,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 6 +default_delay = 7 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} @@ -68,16 +70,11 @@ def login_info(): name = "EHentai", parser = url_regex, sites = ("www.e-hentai.org", "www.exhentai.org"), - description = "Login to E-Hentai & EXHentai", - inputs = ( - {'name': 'IPB Member ID', 'type': str, 'mask': False}, - {'name': 'IPB Pass Hash', 'type': str, 'mask': True}, - {'name': 'EXHentai', 'type': bool} - ) + description = "Login to E-Hentai & ExHentai", ) -@hpx.attach("Login.login") -def login(userpass, options, capture="ehentai"): +@hpx.attach("Login.login", trigger="ehentai") +def login(userpass, options): global current_user_name global status_text global response @@ -87,15 +84,15 @@ def login(userpass, options, capture="ehentai"): response = None current_user_name = "" - ipb_member = userpass.get('IPB Member ID') - ipb_pass = userpass.get('IPB Pass Hash') + ipb_member = userpass.get('ipb_member_id', "") + ipb_pass = userpass.get('ipb_pass_hash', "") if ipb_member and ipb_pass: cookies = {} # get user input cookies.update({ - 'ipb_member_id': userpass.get('IPB Member ID'), - 'ipb_pass_hash': userpass.get('IPB Pass Hash'), + 'ipb_member_id': ipb_member, + 'ipb_pass_hash': ipb_pass, }) # prepare request @@ -114,18 +111,18 @@ def login(userpass, options, capture="ehentai"): bad_access, msg = check_access(r) status_text = msg if not bad_access: - if userpass.get("EXHentai", True): + if userpass.get("exhentai", True): # check exhentai req_props.session = r.session r = req.request(URLS['ex'], req_props) if r.ok: - bad_access, msg = check_access(r, ex=True) + bad_access, status_text = check_access(r, ex=True) else: - msg = "Could not access EXHentai" + status_text = "Could not access ExHentai" response = r - current_user_name = userpass.get('IPB Member ID', "") + current_user_name = ipb_member save_user_dict() else: @@ -136,22 +133,22 @@ def login(userpass, options, capture="ehentai"): return response -@hpx.attach("Login.status") -def status(options, capture="ehentai"): +@hpx.attach("Login.status", trigger="ehentai") +def status(options): return status_text -@hpx.attach("Login.logged_in") -def logged_in(options, capture="ehentai"): +@hpx.attach("Login.logged_in", trigger="ehentai") +def logged_in(options): if response: return True return False -@hpx.attach("Login.response") -def response_(options, capture="ehentai"): +@hpx.attach("Login.response", trigger="ehentai") +def response_(options): return response -@hpx.attach("Login.current_user") -def current_user(options, capture="ehentai"): +@hpx.attach("Login.current_user", trigger="ehentai") +def current_user(options): return current_user_name def check_access(r, ex=False): @@ -160,7 +157,7 @@ def check_access(r, ex=False): content_type = r.headers['content-type'] text = r.text if 'image/gif' in content_type: - msg = "No access to EXHentai" + msg = "No access to ExHentai" elif 'text/html' and 'Your IP address has been' in text: msg = text bad_access = True diff --git a/plugins/EHentai Login/readme.md b/plugins/EHentai Login/readme.md index e28aba8..cbe62c5 100644 --- a/plugins/EHentai Login/readme.md +++ b/plugins/EHentai Login/readme.md @@ -3,21 +3,15 @@ EHentai Login > This plugin can log-in to E-Hentai & ExHentai -Set the **EXHentai** option to true through your client when logging in to also check for ExHentai access. - -The user has access to both E-Hentai and ExHentai if no message is displayed on a succesful log-in. -Else the message `No access to EXHentai` will be displayed. - -To find your **IPB Member ID** and **IPB Pass Hash**, follow these steps (should work on all browsers): -1. Navigate to e-hentai.org (needs to be logged in) or exhentai.org -2. Right click on page => Inpect element -3. Go on **Console** tab -4. Write: `document.cookie` -5. A line of values should appear that correspond to active cookies -6. Look for the `ipb_member_id` and `ipb_pass_hash` values +To login, go to this plugin's site through HPX. +The plugin site can be accessed through a webclient, or at `[webserver-host]/plugin/d9b1d111-7250-4083-9efb-356fabbeada7`. +Replace `[webserver-host]` with wherever your HPX webserver is hosted at. # Changelog +- `1.0.0` + - Updated to reflect new changes in HPX v0.10.0 + - `0.2.0b` - increase default delay limit on EH requests to `9` from `4` secs, this value can be tweaked in `network.delays` inside your`config.yaml` diff --git a/plugins/EHentai Login/site/index.html b/plugins/EHentai Login/site/index.html new file mode 100644 index 0000000..3c0e553 --- /dev/null +++ b/plugins/EHentai Login/site/index.html @@ -0,0 +1,54 @@ +{% extends __default__ %} + +{% block include_javascript %} + +{% endblock %} + +{% block title %} +EHentai Metadata Plugin +{% endblock %} + +{% block before_content_form %} +

Toggle the ExHentai option before logging in to also check for ExHentai access.

+

The user has access to both E-Hentai and ExHentai if no message is displayed on a succesful log-in. Else the message No access to ExHentai will be displayed.

+
+

To find your IPB Member ID and IPB Pass Hash, follow these steps (should work on all browsers):

+
    +
  1. Navigate to e-hentai.org (needs to be logged in) or exhentai.org
  2. +
  3. Right click on page => Inpect element
  4. +
  5. Go on Console tab
  6. +
  7. Write: document.cookie
  8. +
  9. A line of values should appear that correspond to active cookies
  10. +
  11. Look for the ipb_member_id and ipb_pass_hash values
  12. +
+
+{% endblock %} + +{% block outer_content_form %} +
+
+

Logged In

+
+
+

No access to ExHentai

+
+
+

Failed to log in

+
+
+ + +
+
+ + +
+
+
+ + +
+
+ +
+{% endblock %} \ No newline at end of file diff --git a/plugins/EHentai Login/site/script.js b/plugins/EHentai Login/site/script.js new file mode 100644 index 0000000..7e0a429 --- /dev/null +++ b/plugins/EHentai Login/site/script.js @@ -0,0 +1,124 @@ +const login_identifer = "ehentai" + +function main() { + check_login(true) +} + +function set_err_msg(msg) { + document.querySelector("#error-msg").innerHTML = msg +} + +function form_status(cls) { + switch (cls) { + case 'success': + document.querySelector("form").classList.add("success") + document.querySelector("form").classList.remove("error") + document.querySelector("form").classList.remove("warning") + break + case 'error': + if (!document.querySelector("#error-msg").innerHTML) + set_err_msg("Failed to login") + document.querySelector("form").classList.add("error") + document.querySelector("form").classList.remove("success") + document.querySelector("form").classList.remove("warning") + break; + case 'warning': + document.querySelector("form").classList.toggle("warning") + break; + case 'loading': + document.querySelector("form").classList.add("loading") + break; + case '!loading': + document.querySelector("form").classList.remove("loading") + break; + } +} + +function check_login(first_time) { + form_status("loading") + hpx.call_function( + "get_login_info", + {identifier: login_identifer}, + data => { + let fdata = data.data + form_status("!loading") + if (fdata) { + if (fdata.logged_in) { + form_status("success") + if (fdata.status.toLowerCase().indexOf("exhentai") !== -1) + form_status("warning") + } + else + if (!first_time){ + set_err_msg(fdata.status) + form_status("error") + } + } else { + if (!first_time) { + form_status("error") + } + } + }) +} + +function on_login(e) { + e.preventDefault() + let arr = serialize_form(e.target) + let data = { + exhentai: false + } + for (var i in arr) { + let x = arr[i] + if (x.name == 'ipb_member_id' || x.name == 'ipb_pass_hash') { + data[x.name] = x.value + } else if (x.name == 'exhentai') + data[x.name] = (x.value == 'on') ? true : false + } + if (data.ipb_member_id && data.ipb_pass_hash) { + hpx.call_function( + "submit_login", + { + identifier:login_identifer, + credentials: data, + }) + + // submit_login is an async function so delay abit before checking if the login was successful + // a better solution is to actually poll the command and get the result when finished, but ain't nobody got time for that + form_status("loading") + setTimeout(check_login, 4000) + } else { + form_status('error') + } +} + +// in case the document is already rendered +if (document.readyState!='loading') main(); +// modern browsers +else if (document.addEventListener) document.addEventListener('DOMContentLoaded', main); +// IE <= 8 +else document.attachEvent('onreadystatechange', function(){ + if (document.readyState=='complete') main(); +}); + +// Serialize form data into an array +function serialize_form(form) { + var field, l, s = []; + if (typeof form == 'object' && form.nodeName == "FORM") { + var len = form.elements.length; + for (var i=0; i= 0.5.0", + "happypandax >= 0.10.0", "ehentai-login" ] } \ No newline at end of file diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index d04e23e..45b9906 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -1,6 +1,5 @@ # main.py import __hpx__ as hpx -import gevent import regex import arrow import datetime @@ -13,17 +12,17 @@ log = hpx.get_logger("main") -match_url_prefix = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. -match_url_end = r"\/?$" +MATCH_URL_PREFIX = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +MATCH_URL_END = r"\/?$" -default_delay = 6 +DEFAULT_DELAY = 7 -urls_regex = { - 'eh_gallery': match_url_prefix + r"((?= 0.2.0" + "happypandax >= 0.10.0" ] } \ No newline at end of file diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index 4d2d19e..7996f23 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -35,15 +35,21 @@ def get_common_data(datatypes, fpath): break return d -language_model = hpx.command.GetModelClass("Language") -title_model = hpx.command.GetModelClass("Title") -artist_model = hpx.command.GetModelClass("Artist") -parody_model = hpx.command.GetModelClass("Parody") -circle_model = hpx.command.GetModelClass("Circle") -url_model = hpx.command.GetModelClass("Url") -namespacetags_model = hpx.command.GetModelClass("NamespaceTags") - -def apply_metadata(data, gallery): +GalleryData = hpx.command.GalleryData +LanguageData = hpx.command.LanguageData +TitleData = hpx.command.TitleData +ArtistData = hpx.command.ArtistData +ArtistNameData = hpx.command.ArtistNameData +ParodyData = hpx.command.ParodyData +ParodyNameData = hpx.command.ParodyNameData +CircleData = hpx.command.CircleData +CategoryData = hpx.command.CategoryData +UrlData = hpx.command.UrlData +NamespaceTagData= hpx.command.NamespaceTagData +TagData= hpx.command.TagData +NamespaceData = hpx.command.NamespaceData + +def apply_metadata(data, gallery, options={}): """ data = { 'titles': None, # [(title, language),...] @@ -57,61 +63,66 @@ def apply_metadata(data, gallery): } """ - applied = False - log.debug(f"data: {data}") - if isinstance(data.get('titles'), (list, tuple)): + gdata = GalleryData() + + if isinstance(data.get('titles'), (list, tuple, set)): + gtitles = [] for t, l in data['titles']: gtitle = None if t: t = html.unescape(t) - gtitle = title_model(name=t) + gtitle = TitleData(name=t) if t and l: - gtitle.language = language_model.as_unique(name=l) + gtitle.language = LanguageData(name=l) if gtitle: - gallery.update("titles", gtitle) - log.debug("applied titles") - applied = True + gtitles.append(gtitle) + + if gtitles: + gdata.titles = gtitles + log.debug("applied titles") - if isinstance(data.get('artists'), (list, tuple)): + if isinstance(data.get('artists'), (list, tuple, set)): + gartists = [] for a, c in data['artists']: if a: - gartist = artist_model.as_unique(name=common.capitalize_text(a)) - if not gartist in gallery.artists: - gallery.update("artists", gartist) - if a and c: - for circlename in [x for x in c if x]: - gcircle = circle_model.as_unique(name=common.capitalize_text(circlename)) - if not gcircle in gartist.circles: - gartist.update("circles", gcircle) - log.debug("applied artists") - applied = True - - if isinstance(data.get('parodies'), (list, tuple)): + gartist = ArtistData(names=[ArtistNameData(name=capitalize_text(a))]) + gartists.append(gartist) + + if c: + gcircles = [] + for circlename in [x for x in c if x]: + gcircles.append(CircleData(name=capitalize_text(circlename))) + gartist.circles = gcircles + + if gartists: + gdata.artists = gartists + log.debug("applied artists") + + if isinstance(data.get('parodies'), (list, tuple, set)): + gparodies = [] for p in data['parodies']: if p: - gparody = parody_model.as_unique(name=common.capitalize_text(p)) - if not gparody in gallery.parodies: - gallery.update("parodies", gparody) + gparody = ParodyData(names=[ParodyNameData(name=capitalize_text(p))]) + gparodies.append(gparody) - log.debug("applied parodies") - applied = True + if gparodies: + gdata.parodies = gparodies + log.debug("applied parodies") if data.get('category'): - gallery.update("category", name=data['category']) + gdata.category = CategoryData(name=data['category']) log.debug("applied category") - applied = True if data.get('language'): - gallery.update("language", name=data['language']) + gdata.language = LanguageData(name=data['language']) log.debug("applied language") - applied = True if isinstance(data.get('tags'), (dict, list)): if isinstance(data['tags'], list): data['tags'] = {None: data['tags']} - ns_tags = [] + gnstags = [] for ns, tags in data['tags'].items(): if ns is not None: ns = ns.strip() @@ -119,29 +130,33 @@ def apply_metadata(data, gallery): ns = None for t in tags: t = t.strip() - ns_tags.append(namespacetags_model.as_unique(ns=ns, tag=t)) - - for nstag in ns_tags: - if nstag not in gallery.tags: - gallery.tags.append(nstag) - log.debug("applied tags") - applied = True + if t: + kw = {'tag': TagData(name=t)} + if ns: + kw['namespace'] = NamespaceData(name=ns) + gnstags.append(NamespaceTagData(**kw)) + + if gnstags: + gdata.tags = gnstags + log.debug("applied tags") if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): pub_date = data['pub_date'] - gallery.update("pub_date", pub_date) + gdata.pub_date = pub_date log.debug("applied pub_date") - applied = True if isinstance(data.get('urls'), (list, tuple)): - existing_urls = [x.name.lower() for x in gallery.urls] - urls = [] + gurls = [] for u in data['urls']: - if u.lower() not in existing_urls: - urls.append(url_model(name=u)) - gallery.update("urls", urls) - log.debug("applied urls") - applied = True + if u: + gurls.append(UrlData(name=u)) + if gurls: + gdata.urls = gurls + log.debug("applied urls") + + applied = hpx.command.UpdateItemData(gallery, gdata, options=options) + + log.debug(f"applied: {applied}") return applied @@ -149,6 +164,10 @@ def apply_metadata(data, gallery): def inited(): common.plugin_config.update(hpx.get_plugin_config()) +@hpx.subscribe('config_update') +def config_update(cfg): + common.plugin_config.update(cfg) + @hpx.attach("GalleryFS.parse_metadata_file") def parse(path, gallery): fs = hpx.command.CoreFS(path) @@ -159,11 +178,18 @@ def parse(path, gallery): cdata = common.common_data.copy() + applied = False + for fnames, dtypes in common.filenames.items(): for fpath, fname in contents.items(): if fname in fnames: log.debug(f"path: {fpath}") - cdata.update(get_common_data(dtypes, fpath)) + d = get_common_data(dtypes, fpath) + if d: + applied = True + cdata.update(d) break - - return apply_metadata(cdata, gallery) \ No newline at end of file + if applied: + apply_metadata(cdata, gallery) + + return applied \ No newline at end of file diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 4e510c0..2552232 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -47,6 +47,9 @@ Follow these steps to add support for more kind of files: # Changelog +- `1.0.0` + - Updated to reflect new changes in HPX v0.10.0 + - `0.3.0b` - **HDoujin**: add option `characters_namespace` - **HDoujin**: parse `PARODY` and `CHARACTERS` fields From cf632fbd1fe0fc9a29e16b4f33cc6ea69bd9a63f Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 4 Jun 2019 03:48:15 +0200 Subject: [PATCH 39/68] fix; --- .travis.yml.orig | 23 ----------------------- 1 file changed, 23 deletions(-) delete mode 100644 .travis.yml.orig diff --git a/.travis.yml.orig b/.travis.yml.orig deleted file mode 100644 index b567b32..0000000 --- a/.travis.yml.orig +++ /dev/null @@ -1,23 +0,0 @@ -notifications: - email: - on_success: never - on_failure: always -language: python -python: 3.6 -addons: - apt: - update: true -env: - global: - - GH_USER=Twiddly - - GH_MAIL=pew@pewpew.moe - - REPO=happypandax/plugins - - secure: XiUXHPc5pgrdIxHkYXzGRDAqdDCpuszKAJ/75+ZSjH+/Nv5uYLtP9LXzmOZm/x6rxIyNXP408sTnULm+Y+HfWoNV1sCaEwa50NniCPcbuEOtKe0N8o6VKbAmIaxyRZaThvDdIrB2U7VDI9Y+qeRuYfNEM77tEXklzu5SF2sfOAyaMQTdh1qCbGz4++EcZ2451ov8ZHTmHpEMCbUNeK9QZFSA14exFd5VlKYlDrehjoqFATR0Uypcjufh/uJluOWFpscG9duR2aChHkxZu/hH7UYNYRQG/N1VRYUR0g+tQ3CDMWBzIjbkASorZJydy1p53UVUEkTMwhSFw1SGCdAhobPUXlpeYFp9C932ODEhUkzEM3GmmEeV+53mq7nzi6bmOL3SdsWJnf5EZrPI2OOVqgkf2Nh/LkmhANlypcKDmWJOK+izUuMH6q/cl0ZnLSI+WsZU4d1WStfMrqNHE+/3fpwG8yf7CJ2788tzYHyPO9vzJvGsAoY3Z272BQ8rm6yFc/SWE6Mc93wC0vZ5Bd1WfOGMRWn6GVyvvyFKri86pgGj0N7BxXInMS4EWc/AD6r5RLc8xrTYKs0u+VHFAtWnnv7NlhXHnZUqPcSzpAvrhvc91575o7HNC2z/czJIT73eN1oXUMFqTkCvxYg2mC41VSvxf70CPYXAu/DBHLn1uio= - - -script: - - python3 build.py - - git config --local user.name "$GH_USER" - - git config --local user.email "$GH_MAIL" - - git commit -m "build" - - git push --quiet "https://$GITHUB_TOKEN@github.com/$REPO.git" master > /dev/null 2>&1 From 19b69875110c9d72cdb81d436df0e1df2c88d7fe Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 4 Jun 2019 03:51:56 +0200 Subject: [PATCH 40/68] update readme; --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 5faa9f8..94a1df5 100644 --- a/README.md +++ b/README.md @@ -21,9 +21,9 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github Name | Version | Description --- | --- | --- -[**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `0.1.0b` | *A plugin that can fetch metadata from Panda.Chaika* -[**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `0.2.0b` | *A plugin that can login to E-Hentai & ExHentai* -[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `0.4.0b` | *A plugin that can fetch metadata from E-Hentai & ExHentai* -[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `0.3.0b` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* +[**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `1.0.0` | *A plugin that can fetch metadata from Panda.Chaika* +[**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `1.0.0` | *A plugin that can login to E-Hentai & ExHentai* +[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `1.0.0` | *A plugin that can fetch metadata from E-Hentai & ExHentai* +[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `1.0.0` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* From 81aa071e89fc5381a1c0f789b2b309dfe85bd328 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 4 Jun 2019 19:11:37 +0200 Subject: [PATCH 41/68] fix; --- .gitignore | 1 + plugins/EHentai Login/.info | Bin 117 -> 0 bytes 2 files changed, 1 insertion(+) delete mode 100644 plugins/EHentai Login/.info diff --git a/.gitignore b/.gitignore index 1900a0c..cdce0cc 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,7 @@ logs/ .idea/**/dynamic.xml .idea/**/uiDesigner.xml .idea/**/dbnavigator.xml +*.info # Gradle .idea/**/gradle.xml diff --git a/plugins/EHentai Login/.info b/plugins/EHentai Login/.info deleted file mode 100644 index 0b2cc0930709ca268f8326631bea07b7ca228bad..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 117 zcmZo*t}SHHh~QvgU`VaVNX;ur%q(Q=h~NeCGYgX9b5nDZQj6j Date: Thu, 6 Jun 2019 02:45:40 +0200 Subject: [PATCH 42/68] updated the File Metadata plugin to v1.0.1; --- plugins/EHentai Metadata/main.py | 2 +- .../extractors/ehentaidownloader.py | 2 +- plugins/File Metadata/extractors/eze.py | 7 +- plugins/File Metadata/extractors/hdoujin.py | 2 +- plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/main.py | 97 ++++++++++++++++++- plugins/File Metadata/readme.md | 4 + 7 files changed, 109 insertions(+), 7 deletions(-) diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 45b9906..827d4e9 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -467,7 +467,7 @@ def apply_metadata(data, gallery, options): if c: gcircles = [] for circlename in [x for x in c if x]: - gcircles.append(CircleData(name=capitalize_text(circlename))) + gcircles.append(CircleData(name=ca pitalize_text(circlename))) gartist.circles = gcircles if gartists: diff --git a/plugins/File Metadata/extractors/ehentaidownloader.py b/plugins/File Metadata/extractors/ehentaidownloader.py index 7bb2cb6..a9c4d18 100644 --- a/plugins/File Metadata/extractors/ehentaidownloader.py +++ b/plugins/File Metadata/extractors/ehentaidownloader.py @@ -60,7 +60,7 @@ def extract(self, filedata): d.setdefault('urls', []).append(line) else: title_lang = "english" if linenum == 1 else "japanese" - nameparser = hpx.command.NameParser(line) + nameparser = hpx.command.ItemTextParser(line) parsed_title = nameparser.extract_title() d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) continue diff --git a/plugins/File Metadata/extractors/eze.py b/plugins/File Metadata/extractors/eze.py index 4a14dec..00519ac 100644 --- a/plugins/File Metadata/extractors/eze.py +++ b/plugins/File Metadata/extractors/eze.py @@ -7,9 +7,12 @@ class Eze(common.Extractor): def file_to_dict(self, fs): d = super().file_to_dict(fs) - k = ('gallery_info', 'image_info') + k = ('gallery_info',) if d and not all(map(lambda x: x in d, k)): # make sure all keys are present d = None + k = ('image_info', 'gallery_info_full') + if d and not any(map(lambda x: x in d, k)): # make sure one of the keys are present + d = None return d def extract(self, filedata): @@ -26,7 +29,7 @@ def extract(self, filedata): for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): if t: - nameparser = hpx.command.NameParser(t) + nameparser = hpx.command.ItemTextParser(t) parsed_title = nameparser.extract_title() d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) diff --git a/plugins/File Metadata/extractors/hdoujin.py b/plugins/File Metadata/extractors/hdoujin.py index c8d1140..ea647d7 100644 --- a/plugins/File Metadata/extractors/hdoujin.py +++ b/plugins/File Metadata/extractors/hdoujin.py @@ -35,7 +35,7 @@ def extract(self, filedata): for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): if t: - nameparser = hpx.command.NameParser(t) + nameparser = hpx.command.ItemTextParser(t) parsed_title = nameparser.extract_title() d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index afec94b..e1dff95 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "1.0.0", + "version": "1.0.1", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index 7996f23..c2eaa5a 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -29,7 +29,10 @@ def get_common_data(datatypes, fpath): log.info(f"Skipping {datatype}") continue if fdata: + log.info(f"{datatype} matched!") md.update(ex.extract(fdata)) + else: + log.info(f"{datatype} didn't match") if md: d.update(md) break @@ -192,4 +195,96 @@ def parse(path, gallery): if applied: apply_metadata(cdata, gallery) - return applied \ No newline at end of file + return applied + +# This is work in progress to turn this plugin into a regular metadata handler too + +# @hpx.attach("Metadata.info") +# def metadata_info(): +# return hpx.command.MetadataInfo( +# identifier = "filemetadata", +# batch = 25, +# name = "File Metadata", +# description = "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", +# models = ( +# hpx.command.GetDatabaseModel("Gallery"), +# ) +# ) + +# def query(itemtuple, login_site=URLS['eh']): +# "Looks up files for matching items" +# mdata = [] + +# # get exhentai login session if applicable +# ex_login = hpx.command.GetLoginStatus(login_site) if "exhentai" in login_site else False +# login_session = None +# if ex_login: +# login_session = hpx.command.GetLoginSession(login_site) +# if login_site == 'exhentai': +# log.info(f"logged in to exhentai: {ex_login}") + +# for mitem in itemtuple: +# gurls = [] # tuple of (title, url) + +# url = mitem.url +# item = mitem.item +# options = mitem.options + +# # url was provided +# if url: +# log.info(f"url provided: {url} for {item}") +# gurls.append((url, url)) +# else: # manually search for id +# log.info(f"url not provided for {item}") +# if (ex_login if "exhentai" in login_site else True): +# # search with title +# i_title = "" +# i_hash = "" +# if PLUGIN_CONFIG.get("filename_search"): +# sources = item.get_sources() +# if sources: +# # get folder/file name +# i_title = os.path.split(sources[0])[1] +# # remove ext +# i_title = os.path.splitext(i_title)[0] +# else: +# if item.titles: +# i_title = item.titles[0].name # make user choice +# if i_title: +# gurls = title_search(i_title, ex='exhentai' in login_site, session=login_session) + +# # TODO: search with hash +# if not gurls: +# pass + +# log.info(f"found {len(gurls)} urls for item: {item}") + +# # list is sorted by date added so we reverse it +# gurls.reverse() + +# log.debug(f"{gurls}") +# final_gurls = [] +# # TODO: maybe prefer language of gallery first? +# pref_lang = PLUGIN_CONFIG.get('preferred_language') +# if pref_lang: +# for t in gurls: +# if pref_lang.lower() in t[0].lower(): +# final_gurls.insert(0, t) +# continue +# final_gurls.append(t) +# else: +# final_gurls = gurls + +# for t, u in final_gurls: +# g_id, g_token = parse_url(u) +# if g_id and g_token: +# mdata.append(hpx.command.MetadataData( +# metadataitem=mitem, +# title=t, +# url=u, +# data={ +# 'gallery': [g_id, g_token], +# 'gallery_url': u, +# })) +# log.info(f"Returning {len(mdata)} data items") +# return tuple(mdata) \ No newline at end of file diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 2552232..c5ad5c7 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -47,6 +47,10 @@ Follow these steps to add support for more kind of files: # Changelog +- `1.0.1` + - Updated the eze handler to support files produced by https://github.com/dnsev-h/ehentai-archive-info + - Fixed the extractors still using the old api + - `1.0.0` - Updated to reflect new changes in HPX v0.10.0 From 6c7b86c9d33c7fb1b60e424c6a21f7ee6a69a5e6 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 6 Jun 2019 02:46:49 +0200 Subject: [PATCH 43/68] updated the File Metadata plugin to v1.0.1; (#22) --- plugins/EHentai Metadata/main.py | 2 +- .../extractors/ehentaidownloader.py | 2 +- plugins/File Metadata/extractors/eze.py | 7 +- plugins/File Metadata/extractors/hdoujin.py | 2 +- plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/main.py | 97 ++++++++++++++++++- plugins/File Metadata/readme.md | 4 + 7 files changed, 109 insertions(+), 7 deletions(-) diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 45b9906..827d4e9 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -467,7 +467,7 @@ def apply_metadata(data, gallery, options): if c: gcircles = [] for circlename in [x for x in c if x]: - gcircles.append(CircleData(name=capitalize_text(circlename))) + gcircles.append(CircleData(name=ca pitalize_text(circlename))) gartist.circles = gcircles if gartists: diff --git a/plugins/File Metadata/extractors/ehentaidownloader.py b/plugins/File Metadata/extractors/ehentaidownloader.py index 7bb2cb6..a9c4d18 100644 --- a/plugins/File Metadata/extractors/ehentaidownloader.py +++ b/plugins/File Metadata/extractors/ehentaidownloader.py @@ -60,7 +60,7 @@ def extract(self, filedata): d.setdefault('urls', []).append(line) else: title_lang = "english" if linenum == 1 else "japanese" - nameparser = hpx.command.NameParser(line) + nameparser = hpx.command.ItemTextParser(line) parsed_title = nameparser.extract_title() d.setdefault("titles", []).append((parsed_title[0] if parsed_title else line, title_lang)) continue diff --git a/plugins/File Metadata/extractors/eze.py b/plugins/File Metadata/extractors/eze.py index 4a14dec..00519ac 100644 --- a/plugins/File Metadata/extractors/eze.py +++ b/plugins/File Metadata/extractors/eze.py @@ -7,9 +7,12 @@ class Eze(common.Extractor): def file_to_dict(self, fs): d = super().file_to_dict(fs) - k = ('gallery_info', 'image_info') + k = ('gallery_info',) if d and not all(map(lambda x: x in d, k)): # make sure all keys are present d = None + k = ('image_info', 'gallery_info_full') + if d and not any(map(lambda x: x in d, k)): # make sure one of the keys are present + d = None return d def extract(self, filedata): @@ -26,7 +29,7 @@ def extract(self, filedata): for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): if t: - nameparser = hpx.command.NameParser(t) + nameparser = hpx.command.ItemTextParser(t) parsed_title = nameparser.extract_title() d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) diff --git a/plugins/File Metadata/extractors/hdoujin.py b/plugins/File Metadata/extractors/hdoujin.py index c8d1140..ea647d7 100644 --- a/plugins/File Metadata/extractors/hdoujin.py +++ b/plugins/File Metadata/extractors/hdoujin.py @@ -35,7 +35,7 @@ def extract(self, filedata): for t, l in ((mtitle, "english"), (mtitle_jp, "japanese")): if t: - nameparser = hpx.command.NameParser(t) + nameparser = hpx.command.ItemTextParser(t) parsed_title = nameparser.extract_title() d.setdefault("titles", []).append((parsed_title[0] if parsed_title else t, l)) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index afec94b..e1dff95 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "1.0.0", + "version": "1.0.1", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index 7996f23..c2eaa5a 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -29,7 +29,10 @@ def get_common_data(datatypes, fpath): log.info(f"Skipping {datatype}") continue if fdata: + log.info(f"{datatype} matched!") md.update(ex.extract(fdata)) + else: + log.info(f"{datatype} didn't match") if md: d.update(md) break @@ -192,4 +195,96 @@ def parse(path, gallery): if applied: apply_metadata(cdata, gallery) - return applied \ No newline at end of file + return applied + +# This is work in progress to turn this plugin into a regular metadata handler too + +# @hpx.attach("Metadata.info") +# def metadata_info(): +# return hpx.command.MetadataInfo( +# identifier = "filemetadata", +# batch = 25, +# name = "File Metadata", +# description = "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", +# models = ( +# hpx.command.GetDatabaseModel("Gallery"), +# ) +# ) + +# def query(itemtuple, login_site=URLS['eh']): +# "Looks up files for matching items" +# mdata = [] + +# # get exhentai login session if applicable +# ex_login = hpx.command.GetLoginStatus(login_site) if "exhentai" in login_site else False +# login_session = None +# if ex_login: +# login_session = hpx.command.GetLoginSession(login_site) +# if login_site == 'exhentai': +# log.info(f"logged in to exhentai: {ex_login}") + +# for mitem in itemtuple: +# gurls = [] # tuple of (title, url) + +# url = mitem.url +# item = mitem.item +# options = mitem.options + +# # url was provided +# if url: +# log.info(f"url provided: {url} for {item}") +# gurls.append((url, url)) +# else: # manually search for id +# log.info(f"url not provided for {item}") +# if (ex_login if "exhentai" in login_site else True): +# # search with title +# i_title = "" +# i_hash = "" +# if PLUGIN_CONFIG.get("filename_search"): +# sources = item.get_sources() +# if sources: +# # get folder/file name +# i_title = os.path.split(sources[0])[1] +# # remove ext +# i_title = os.path.splitext(i_title)[0] +# else: +# if item.titles: +# i_title = item.titles[0].name # make user choice +# if i_title: +# gurls = title_search(i_title, ex='exhentai' in login_site, session=login_session) + +# # TODO: search with hash +# if not gurls: +# pass + +# log.info(f"found {len(gurls)} urls for item: {item}") + +# # list is sorted by date added so we reverse it +# gurls.reverse() + +# log.debug(f"{gurls}") +# final_gurls = [] +# # TODO: maybe prefer language of gallery first? +# pref_lang = PLUGIN_CONFIG.get('preferred_language') +# if pref_lang: +# for t in gurls: +# if pref_lang.lower() in t[0].lower(): +# final_gurls.insert(0, t) +# continue +# final_gurls.append(t) +# else: +# final_gurls = gurls + +# for t, u in final_gurls: +# g_id, g_token = parse_url(u) +# if g_id and g_token: +# mdata.append(hpx.command.MetadataData( +# metadataitem=mitem, +# title=t, +# url=u, +# data={ +# 'gallery': [g_id, g_token], +# 'gallery_url': u, +# })) +# log.info(f"Returning {len(mdata)} data items") +# return tuple(mdata) \ No newline at end of file diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 2552232..c5ad5c7 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -47,6 +47,10 @@ Follow these steps to add support for more kind of files: # Changelog +- `1.0.1` + - Updated the eze handler to support files produced by https://github.com/dnsev-h/ehentai-archive-info + - Fixed the extractors still using the old api + - `1.0.0` - Updated to reflect new changes in HPX v0.10.0 From dfe854106c4c45a86ed0fc8be5e80ff45874f831 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 15 Jun 2019 14:59:26 +0200 Subject: [PATCH 44/68] updated ehentai-metadata to 1.1.0; --- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 50 ++++++++++++++++++++++----- plugins/EHentai Metadata/readme.md | 13 +++++-- 3 files changed, 52 insertions(+), 13 deletions(-) diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index 30426e8..cfd9c4e 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "1.0.0", + "version": "1.1.0", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 827d4e9..6c5a6de 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -26,12 +26,13 @@ 'eh': 'https://e-hentai.org', 'ex': 'https://exhentai.org', 'api': 'https://api.e-hentai.org/api.php', - 'title_search': '{url}/?f_doujinshi=1&f_manga=1&f_artistcg=1&f_gamecg=1&f_western=1&f_non-h=1&f_imageset=1&f_cosplay=1&f_asianporn=1&f_misc=1&f_search={title}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_srdd=2&f_sfl=on&f_sfu=on', - 'title_search_exp': '{url}/?f_doujinshi=1&f_manga=1&f_artistcg=1&f_gamecg=1&f_western=1&f_non-h=1&f_imageset=1&f_cosplay=1&f_asianporn=1&f_misc=1&f_search={title}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_sh=on&f_srdd=2&f_sfl=on&f_sfu=on' + 'title_search': '{url}/?{query}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_srdd=2&f_sfl=on&f_sfu=on', } HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} +DEFAULT_CATEGORIES = ['manga', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc'] + PLUGIN_CONFIG = { 'filename_search': True, # use the filename/folder-name for searching instead of gallery title 'expunged_galleries': False, # enable expunged galleries in results @@ -39,7 +40,12 @@ 'gallery_results_limit': 10, # maximum amount of galleries to return 'blacklist_tags': [], # tags to ignore when updating tags 'add_gallery_url': True, # add ehentai url to gallery - 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default + 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default, + 'enabled_categories': DEFAULT_CATEGORIES, # categories that are enbaled in the search + 'search_query': "{title}", # the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a bracket + 'search_low_power_tags': True, # enable search low power tags + 'search_torrent_name':True, # enable search torrent name + 'search_gallery_description': False, # enable search gallery description } @hpx.subscribe("init") @@ -202,14 +208,40 @@ def query(itemtuple, login_site=URLS['eh']): def title_search(title, ex=True, session=None): "Searches on ehentai for galleries with given title, returns a list of (title, matching gallery urls)" - if PLUGIN_CONFIG.get("expunged_galleries"): - eh_url = URLS['title_search_exp'] - else: - eh_url = URLS['title_search'] + eh_url = URLS['title_search'] log.debug(f"searching with title: {title}") + sq = PLUGIN_CONFIG.get("search_query") + try: + sq = sq.format(title) + except: + log.warning("Failed to use customized search query") + sq = title + log.info(f"Final search query: {sq}") + + params = {f'f_{c}': '0' for c in DEFAULT_CATEGORIES} + + if PLUGIN_CONFIG.get("expunged_galleries"): + params['f_sh'] = 'on' + + if PLUGIN_CONFIG.get("search_low_power_tags"): + params['f_sdt1'] = 'on' + + if PLUGIN_CONFIG.get("search_gallery_description"): + params['f_sdesc'] = 'on' + + if PLUGIN_CONFIG.get("search_torrent_name"): + params['f_storr'] = 'on' + + for c in PLUGIN_CONFIG.get("enabled_categories"): + params[f'f_{c.lower()}'] = '1' + + params['f_search'] = urllib.parse.quote_plus(f'"{sq}"') + log.info(f"final params: {params}") + param_query = urllib.parse.urlencode(params) + f_eh_url = eh_url.format( url=URLS['ex'] if ex else URLS['eh'], - title=urllib.parse.quote_plus(f'"{title}"') + query=param_query ) log.debug(f"final url: {f_eh_url}") return eh_page_results(f_eh_url, session=session) @@ -467,7 +499,7 @@ def apply_metadata(data, gallery, options): if c: gcircles = [] for circlename in [x for x in c if x]: - gcircles.append(CircleData(name=ca pitalize_text(circlename))) + gcircles.append(CircleData(name=capitalize_text(circlename))) gartist.circles = gcircles if gartists: diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index 2104f38..e133ba3 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -28,8 +28,12 @@ Name | Default | Description `gallery_results_limit` | `10` | maximum amount of galleries to return `blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` strings `add_gallery_url` | `true` | add ehentai url to gallery -`preferred_language` | `english` | preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default - +`preferred_language` | `"english"` | preferred gallery language (in gallery title) to extract from if multiple galleries were found, set empty string for default +`enabled_categories` | `['manga', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc']` | categories that are enbaled for the search +`search_query` | `"{title}"` | the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a curly bracket +`search_low_power_tags` | `true` | enable search low power tags +`search_torrent_name` | `true` | enable search torrent name +`search_gallery_description` | `false` | enable search gallery description ## Things yet to be implemented @@ -37,8 +41,11 @@ Name | Default | Description # Changelog +- `1.1.0` + - added several new options and fixed some errors + - `1.0.0` - - Updated to reflect new changes in HPX v0.10.0 + - updated to reflect new changes in HPX v0.10.0 - `0.4.0b` - updated to work on new EH website design changes From 11a7921a3d53f7585845026b4ad084cfba0470c8 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 15 Jun 2019 23:18:18 +0200 Subject: [PATCH 45/68] updated ehentai-metadata; fixed ci script; --- .travis.yml | 2 +- plugins/EHentai Metadata/main.py | 16 +++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/.travis.yml b/.travis.yml index b567b32..5454303 100644 --- a/.travis.yml +++ b/.travis.yml @@ -19,5 +19,5 @@ script: - python3 build.py - git config --local user.name "$GH_USER" - git config --local user.email "$GH_MAIL" - - git commit -m "build" + - git commit -am "build" - git push --quiet "https://$GITHUB_TOKEN@github.com/$REPO.git" master > /dev/null 2>&1 diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index b66393d..adb79ae 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -211,14 +211,21 @@ def title_search(title, ex=True, session=None): eh_url = URLS['title_search'] log.debug(f"searching with title: {title}") sq = PLUGIN_CONFIG.get("search_query") + + params = {f'f_{c}': '0' for c in DEFAULT_CATEGORIES} + + title = f'"{title}"' + try: - sq = sq.format(title) + sq = sq.format(title=title) except: log.warning("Failed to use customized search query") sq = title + + params['f_search'] = sq + log.info(f"Final search query: {sq}") - params = {f'f_{c}': '0' for c in DEFAULT_CATEGORIES} if PLUGIN_CONFIG.get("expunged_galleries"): params['f_sh'] = 'on' @@ -235,7 +242,6 @@ def title_search(title, ex=True, session=None): for c in PLUGIN_CONFIG.get("enabled_categories"): params[f'f_{c.lower()}'] = '1' - params['f_search'] = urllib.parse.quote_plus(f'"{sq}"') log.info(f"final params: {params}") param_query = urllib.parse.urlencode(params) @@ -243,7 +249,7 @@ def title_search(title, ex=True, session=None): url=URLS['ex'] if ex else URLS['eh'], query=param_query ) - log.debug(f"final url: {f_eh_url}") + log.info(f"final url: {f_eh_url}") return eh_page_results(f_eh_url, session=session) def eh_page_results(eh_page_url, limit=None, session=None): @@ -499,7 +505,7 @@ def apply_metadata(data, gallery, options): if c: gcircles = [] for circlename in [x for x in c if x]: - gcircles.append(CircleData(name=ca pitalize_text(circlename))) + gcircles.append(CircleData(name=capitalize_text(circlename))) gartist.circles = gcircles if gartists: From cc8239b5466cd63e5818e2d48902bddee0afdda4 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 15 Jun 2019 23:33:47 +0200 Subject: [PATCH 46/68] update ci script; update ehentai-metadata; --- .travis.yml | 2 +- plugins/EHentai Metadata/main.py | 2 +- plugins/EHentai Metadata/readme.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.travis.yml b/.travis.yml index 5454303..b13c6bf 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,7 +12,7 @@ env: - GH_USER=Twiddly - GH_MAIL=pew@pewpew.moe - REPO=happypandax/plugins - - secure: XiUXHPc5pgrdIxHkYXzGRDAqdDCpuszKAJ/75+ZSjH+/Nv5uYLtP9LXzmOZm/x6rxIyNXP408sTnULm+Y+HfWoNV1sCaEwa50NniCPcbuEOtKe0N8o6VKbAmIaxyRZaThvDdIrB2U7VDI9Y+qeRuYfNEM77tEXklzu5SF2sfOAyaMQTdh1qCbGz4++EcZ2451ov8ZHTmHpEMCbUNeK9QZFSA14exFd5VlKYlDrehjoqFATR0Uypcjufh/uJluOWFpscG9duR2aChHkxZu/hH7UYNYRQG/N1VRYUR0g+tQ3CDMWBzIjbkASorZJydy1p53UVUEkTMwhSFw1SGCdAhobPUXlpeYFp9C932ODEhUkzEM3GmmEeV+53mq7nzi6bmOL3SdsWJnf5EZrPI2OOVqgkf2Nh/LkmhANlypcKDmWJOK+izUuMH6q/cl0ZnLSI+WsZU4d1WStfMrqNHE+/3fpwG8yf7CJ2788tzYHyPO9vzJvGsAoY3Z272BQ8rm6yFc/SWE6Mc93wC0vZ5Bd1WfOGMRWn6GVyvvyFKri86pgGj0N7BxXInMS4EWc/AD6r5RLc8xrTYKs0u+VHFAtWnnv7NlhXHnZUqPcSzpAvrhvc91575o7HNC2z/czJIT73eN1oXUMFqTkCvxYg2mC41VSvxf70CPYXAu/DBHLn1uio= + - secure: sogo+NT/2/Xr1LNmksFbMSoGCNCgVUcQynhkBiLqSfLrfT9zDXVYl4FGqIntARJSNK1BTvayV/XD0HOtMzbjeARoR91+NYgPScV3PRDu/Bw+X4yM8jjN7GZjz5+a5+co+A8cfuKdrf93CNVV6N02fxzqdC9lhoyp+HD7JxbWKl2+8YmQetrAD4dGf+KaVcJKHr/pgpBND5Tp17jO4vAEbqD+GT7aXDoC+81Onq8UOzNI0/A9s+2IzMlG4Jhfdr52ynpND1plycspByVI3kRqrFPEcWk4x2U5C8OKU6Hf4Zuj3G1d37c8MP6F9F362m6MWa4cfxOeKCmP6uRSVEf9Oxb/w2OnEg40U5nYEpBvziml1STINSgQQlwI4+iO0o1G4Zl7nRsyICZEAhzJRjoPcF5+IfzjGera0xxFkVd+0A9fz8kAyTp53BK5uAxgiaLcIfVj9WsZhSuJPG4kx0abnaNLPJtrDDTdBX9+A0Xk9sXHBCphFVOhobTUspmpCN4zWO9jH8xcPotRyo4D53I7yapSiia89yDxQNLnoNGDVPuX4KTMWO9w2snczEKo9rSJUDJVqdRU1LXbERFCoyCd33Rfm9EZsR06mtkjkpAL7YWOfbjSlyes87OBS3sRW7FqmQPEgSVbovmygOa564Yfo9B48doSKtg09aj0IBJxxXk= script: diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index adb79ae..faa3213 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -31,7 +31,7 @@ HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} -DEFAULT_CATEGORIES = ['manga', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc'] +DEFAULT_CATEGORIES = ['manga', 'doujinshi', 'non-h', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc'] PLUGIN_CONFIG = { 'filename_search': True, # use the filename/folder-name for searching instead of gallery title diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index e133ba3..a5583b5 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -29,8 +29,8 @@ Name | Default | Description `blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` strings `add_gallery_url` | `true` | add ehentai url to gallery `preferred_language` | `"english"` | preferred gallery language (in gallery title) to extract from if multiple galleries were found, set empty string for default -`enabled_categories` | `['manga', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc']` | categories that are enbaled for the search -`search_query` | `"{title}"` | the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a curly bracket +`enabled_categories` | `['manga', 'doujinshi', 'non-h', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc']` | categories that are enbaled for the search +`search_query` | `"{title}"` | the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a curly bracket. Tip: if you want to only allow english results, you should modify this to "{title} english" `search_low_power_tags` | `true` | enable search low power tags `search_torrent_name` | `true` | enable search torrent name `search_gallery_description` | `false` | enable search gallery description From 262eb052bcbd38fc279c582c8b94feec506e1afe Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 15 Jun 2019 23:38:01 +0200 Subject: [PATCH 47/68] update ci; --- .travis.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.travis.yml b/.travis.yml index b13c6bf..024875c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -21,3 +21,7 @@ script: - git config --local user.email "$GH_MAIL" - git commit -am "build" - git push --quiet "https://$GITHUB_TOKEN@github.com/$REPO.git" master > /dev/null 2>&1 + +branches: + only: + - master \ No newline at end of file From d2a68c756d9952e74258ee304b2cd72772e589bd Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 15 Jun 2019 23:40:20 +0200 Subject: [PATCH 48/68] Updated ehentai-metadata to 1.1.0; (#25) updated ehentai-metadata to 1.1.0; --- .travis.yml | 8 +++- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 58 ++++++++++++++++++++++----- plugins/EHentai Metadata/readme.md | 13 ++++-- 4 files changed, 65 insertions(+), 16 deletions(-) diff --git a/.travis.yml b/.travis.yml index b567b32..024875c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,12 +12,16 @@ env: - GH_USER=Twiddly - GH_MAIL=pew@pewpew.moe - REPO=happypandax/plugins - - secure: XiUXHPc5pgrdIxHkYXzGRDAqdDCpuszKAJ/75+ZSjH+/Nv5uYLtP9LXzmOZm/x6rxIyNXP408sTnULm+Y+HfWoNV1sCaEwa50NniCPcbuEOtKe0N8o6VKbAmIaxyRZaThvDdIrB2U7VDI9Y+qeRuYfNEM77tEXklzu5SF2sfOAyaMQTdh1qCbGz4++EcZ2451ov8ZHTmHpEMCbUNeK9QZFSA14exFd5VlKYlDrehjoqFATR0Uypcjufh/uJluOWFpscG9duR2aChHkxZu/hH7UYNYRQG/N1VRYUR0g+tQ3CDMWBzIjbkASorZJydy1p53UVUEkTMwhSFw1SGCdAhobPUXlpeYFp9C932ODEhUkzEM3GmmEeV+53mq7nzi6bmOL3SdsWJnf5EZrPI2OOVqgkf2Nh/LkmhANlypcKDmWJOK+izUuMH6q/cl0ZnLSI+WsZU4d1WStfMrqNHE+/3fpwG8yf7CJ2788tzYHyPO9vzJvGsAoY3Z272BQ8rm6yFc/SWE6Mc93wC0vZ5Bd1WfOGMRWn6GVyvvyFKri86pgGj0N7BxXInMS4EWc/AD6r5RLc8xrTYKs0u+VHFAtWnnv7NlhXHnZUqPcSzpAvrhvc91575o7HNC2z/czJIT73eN1oXUMFqTkCvxYg2mC41VSvxf70CPYXAu/DBHLn1uio= + - secure: sogo+NT/2/Xr1LNmksFbMSoGCNCgVUcQynhkBiLqSfLrfT9zDXVYl4FGqIntARJSNK1BTvayV/XD0HOtMzbjeARoR91+NYgPScV3PRDu/Bw+X4yM8jjN7GZjz5+a5+co+A8cfuKdrf93CNVV6N02fxzqdC9lhoyp+HD7JxbWKl2+8YmQetrAD4dGf+KaVcJKHr/pgpBND5Tp17jO4vAEbqD+GT7aXDoC+81Onq8UOzNI0/A9s+2IzMlG4Jhfdr52ynpND1plycspByVI3kRqrFPEcWk4x2U5C8OKU6Hf4Zuj3G1d37c8MP6F9F362m6MWa4cfxOeKCmP6uRSVEf9Oxb/w2OnEg40U5nYEpBvziml1STINSgQQlwI4+iO0o1G4Zl7nRsyICZEAhzJRjoPcF5+IfzjGera0xxFkVd+0A9fz8kAyTp53BK5uAxgiaLcIfVj9WsZhSuJPG4kx0abnaNLPJtrDDTdBX9+A0Xk9sXHBCphFVOhobTUspmpCN4zWO9jH8xcPotRyo4D53I7yapSiia89yDxQNLnoNGDVPuX4KTMWO9w2snczEKo9rSJUDJVqdRU1LXbERFCoyCd33Rfm9EZsR06mtkjkpAL7YWOfbjSlyes87OBS3sRW7FqmQPEgSVbovmygOa564Yfo9B48doSKtg09aj0IBJxxXk= script: - python3 build.py - git config --local user.name "$GH_USER" - git config --local user.email "$GH_MAIL" - - git commit -m "build" + - git commit -am "build" - git push --quiet "https://$GITHUB_TOKEN@github.com/$REPO.git" master > /dev/null 2>&1 + +branches: + only: + - master \ No newline at end of file diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index 30426e8..cfd9c4e 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "1.0.0", + "version": "1.1.0", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 827d4e9..faa3213 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -26,12 +26,13 @@ 'eh': 'https://e-hentai.org', 'ex': 'https://exhentai.org', 'api': 'https://api.e-hentai.org/api.php', - 'title_search': '{url}/?f_doujinshi=1&f_manga=1&f_artistcg=1&f_gamecg=1&f_western=1&f_non-h=1&f_imageset=1&f_cosplay=1&f_asianporn=1&f_misc=1&f_search={title}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_srdd=2&f_sfl=on&f_sfu=on', - 'title_search_exp': '{url}/?f_doujinshi=1&f_manga=1&f_artistcg=1&f_gamecg=1&f_western=1&f_non-h=1&f_imageset=1&f_cosplay=1&f_asianporn=1&f_misc=1&f_search={title}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_sh=on&f_srdd=2&f_sfl=on&f_sfu=on' + 'title_search': '{url}/?{query}&f_apply=Apply+Filter&advsearch=1&f_sname=on&f_stags=on&f_storr=on&f_srdd=2&f_sfl=on&f_sfu=on', } HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} +DEFAULT_CATEGORIES = ['manga', 'doujinshi', 'non-h', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc'] + PLUGIN_CONFIG = { 'filename_search': True, # use the filename/folder-name for searching instead of gallery title 'expunged_galleries': False, # enable expunged galleries in results @@ -39,7 +40,12 @@ 'gallery_results_limit': 10, # maximum amount of galleries to return 'blacklist_tags': [], # tags to ignore when updating tags 'add_gallery_url': True, # add ehentai url to gallery - 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default + 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default, + 'enabled_categories': DEFAULT_CATEGORIES, # categories that are enbaled in the search + 'search_query': "{title}", # the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a bracket + 'search_low_power_tags': True, # enable search low power tags + 'search_torrent_name':True, # enable search torrent name + 'search_gallery_description': False, # enable search gallery description } @hpx.subscribe("init") @@ -202,16 +208,48 @@ def query(itemtuple, login_site=URLS['eh']): def title_search(title, ex=True, session=None): "Searches on ehentai for galleries with given title, returns a list of (title, matching gallery urls)" - if PLUGIN_CONFIG.get("expunged_galleries"): - eh_url = URLS['title_search_exp'] - else: - eh_url = URLS['title_search'] + eh_url = URLS['title_search'] log.debug(f"searching with title: {title}") + sq = PLUGIN_CONFIG.get("search_query") + + params = {f'f_{c}': '0' for c in DEFAULT_CATEGORIES} + + title = f'"{title}"' + + try: + sq = sq.format(title=title) + except: + log.warning("Failed to use customized search query") + sq = title + + params['f_search'] = sq + + log.info(f"Final search query: {sq}") + + + if PLUGIN_CONFIG.get("expunged_galleries"): + params['f_sh'] = 'on' + + if PLUGIN_CONFIG.get("search_low_power_tags"): + params['f_sdt1'] = 'on' + + if PLUGIN_CONFIG.get("search_gallery_description"): + params['f_sdesc'] = 'on' + + if PLUGIN_CONFIG.get("search_torrent_name"): + params['f_storr'] = 'on' + + for c in PLUGIN_CONFIG.get("enabled_categories"): + params[f'f_{c.lower()}'] = '1' + + log.info(f"final params: {params}") + param_query = urllib.parse.urlencode(params) + f_eh_url = eh_url.format( url=URLS['ex'] if ex else URLS['eh'], - title=urllib.parse.quote_plus(f'"{title}"') + query=param_query ) - log.debug(f"final url: {f_eh_url}") + log.info(f"final url: {f_eh_url}") return eh_page_results(f_eh_url, session=session) def eh_page_results(eh_page_url, limit=None, session=None): @@ -467,7 +505,7 @@ def apply_metadata(data, gallery, options): if c: gcircles = [] for circlename in [x for x in c if x]: - gcircles.append(CircleData(name=ca pitalize_text(circlename))) + gcircles.append(CircleData(name=capitalize_text(circlename))) gartist.circles = gcircles if gartists: diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index 2104f38..a5583b5 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -28,8 +28,12 @@ Name | Default | Description `gallery_results_limit` | `10` | maximum amount of galleries to return `blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` strings `add_gallery_url` | `true` | add ehentai url to gallery -`preferred_language` | `english` | preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default - +`preferred_language` | `"english"` | preferred gallery language (in gallery title) to extract from if multiple galleries were found, set empty string for default +`enabled_categories` | `['manga', 'doujinshi', 'non-h', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc']` | categories that are enbaled for the search +`search_query` | `"{title}"` | the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a curly bracket. Tip: if you want to only allow english results, you should modify this to "{title} english" +`search_low_power_tags` | `true` | enable search low power tags +`search_torrent_name` | `true` | enable search torrent name +`search_gallery_description` | `false` | enable search gallery description ## Things yet to be implemented @@ -37,8 +41,11 @@ Name | Default | Description # Changelog +- `1.1.0` + - added several new options and fixed some errors + - `1.0.0` - - Updated to reflect new changes in HPX v0.10.0 + - updated to reflect new changes in HPX v0.10.0 - `0.4.0b` - updated to work on new EH website design changes From eda10bcd77b714dd7ca1538e39bf7f98f3de7e8a Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 22 Jun 2019 23:25:39 +0200 Subject: [PATCH 49/68] update default delays; update FileMetadata --- plugins/EHentai Login/main.py | 2 +- plugins/EHentai Metadata/main.py | 2 +- plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/main.py | 23 ++++++++++++----------- 4 files changed, 15 insertions(+), 14 deletions(-) diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 15a19e6..eb0758c 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -16,7 +16,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 7 +default_delay = 8 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index faa3213..97a21b6 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -15,7 +15,7 @@ MATCH_URL_PREFIX = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. MATCH_URL_END = r"\/?$" -DEFAULT_DELAY = 7 +DEFAULT_DELAY = 8 URLS_REGEX = { 'eh_gallery': MATCH_URL_PREFIX + r"((? Date: Sat, 22 Jun 2019 23:27:22 +0200 Subject: [PATCH 50/68] udpate --- plugins/File Metadata/readme.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index c5ad5c7..2727dd4 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -47,6 +47,9 @@ Follow these steps to add support for more kind of files: # Changelog +- `1.0.2` + - Fixed a bug where not all metadata would be applied + - `1.0.1` - Updated the eze handler to support files produced by https://github.com/dnsev-h/ehentai-archive-info - Fixed the extractors still using the old api From 72017b8f16ab8038688c9a28bdec882979a0e9b7 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sat, 22 Jun 2019 23:28:46 +0200 Subject: [PATCH 51/68] Update FileMetadata; --- plugins/EHentai Login/main.py | 2 +- plugins/EHentai Metadata/main.py | 2 +- plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/main.py | 23 ++++++++++++----------- plugins/File Metadata/readme.md | 3 +++ 5 files changed, 18 insertions(+), 14 deletions(-) diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 15a19e6..eb0758c 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -16,7 +16,7 @@ save_file = os.path.join(hpx.constants.current_dir, '.info') -default_delay = 7 +default_delay = 8 HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index faa3213..97a21b6 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -15,7 +15,7 @@ MATCH_URL_PREFIX = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. MATCH_URL_END = r"\/?$" -DEFAULT_DELAY = 7 +DEFAULT_DELAY = 8 URLS_REGEX = { 'eh_gallery': MATCH_URL_PREFIX + r"((? Date: Sat, 6 Jul 2019 17:31:19 +0300 Subject: [PATCH 52/68] Save published data in File Metadata (#27) * add published date to dictionary * bump version 1.0.3 * Updated changelog --- plugins/File Metadata/extractors/eze.py | 7 ++++++- plugins/File Metadata/hplugin.json | 4 ++-- plugins/File Metadata/readme.md | 5 ++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/plugins/File Metadata/extractors/eze.py b/plugins/File Metadata/extractors/eze.py index 00519ac..9db99de 100644 --- a/plugins/File Metadata/extractors/eze.py +++ b/plugins/File Metadata/extractors/eze.py @@ -1,3 +1,4 @@ +import arrow import __hpx__ as hpx from . import common @@ -48,6 +49,10 @@ def extract(self, filedata): if msource: d.setdefault('urls', []).append(f"https://{msource['site']}.org/g/{msource['gid']}/{msource['token']}") + mupdate = filedata.get("upload_date") + if mupdate: + d['pub_date'] = arrow.get(*mupdate) + return d -common.register_extractor(Eze, common.DataType.eze) \ No newline at end of file +common.register_extractor(Eze, common.DataType.eze) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index cb655fd..d771846 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "1.0.2", + "version": "1.0.3", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", @@ -11,4 +11,4 @@ "require": [ "happypandax >= 0.10.0" ] -} \ No newline at end of file +} diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 2727dd4..6499133 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -47,6 +47,9 @@ Follow these steps to add support for more kind of files: # Changelog +- `1.0.3` + - Updated the eze handler to save uploaded date as published date + - `1.0.2` - Fixed a bug where not all metadata would be applied @@ -68,4 +71,4 @@ Follow these steps to add support for more kind of files: - fix bug where `info.txt` in archive files would fail to get parsed - `0.1.0b` - - first version \ No newline at end of file + - first version From c1675f2c1731e3e017245d4ba358c19c927b2f33 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 29 Aug 2019 00:04:52 +0200 Subject: [PATCH 53/68] updated File Metadata plugin to act as a regular metadata handler; --- plugins/File Metadata/hplugin.json | 4 +- plugins/File Metadata/main.py | 180 ++++++++++++----------------- plugins/File Metadata/readme.md | 5 +- 3 files changed, 83 insertions(+), 106 deletions(-) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index d771846..1d1d5cd 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,13 +2,13 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "1.0.3", + "version": "2.0.0", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", "entry": "main.py", "require": [ - "happypandax >= 0.10.0" + "happypandax >= 0.11.0" ] } diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index 02f575f..9e8c199 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -172,120 +172,94 @@ def inited(): def config_update(cfg): common.plugin_config.update(cfg) -@hpx.attach("GalleryFS.parse_metadata_file") -def parse(path, gallery): +def has_file_metadata(path): fs = hpx.command.CoreFS(path) contents = {x: os.path.split(x)[1].lower() for x in fs.contents(corefs=False) if x.lower().endswith(common.filetypes)} log.debug(f"Contents for {fs.path}:") log.debug(f"{tuple(contents.values())}") - cdata = common.common_data.copy() - - applied = False - + found_files = [] for fnames, dtypes in common.filenames.items(): for fpath, fname in contents.items(): if fname in fnames: - log.debug(f"path: {fpath}") - d = get_common_data(dtypes, fpath) - if d: - applied = True - cdata.update(d) + found_files.append((dtypes, fpath)) break + + return found_files + +def apply_file_metadata(gallery, found_files): + applied = False + cdata = common.common_data.copy() + for dtypes, fpath in found_files: + log.debug(f"path: {fpath}") + d = get_common_data(dtypes, fpath) + if d: + applied = True + cdata.update(d) + if applied: apply_metadata(cdata, gallery) - + return applied -# This is work in progress to turn this plugin into a regular metadata handler too - -# @hpx.attach("Metadata.info") -# def metadata_info(): -# return hpx.command.MetadataInfo( -# identifier = "filemetadata", -# batch = 25, -# name = "File Metadata", -# description = "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", -# models = ( -# hpx.command.GetDatabaseModel("Gallery"), -# ) -# ) - -# def query(itemtuple, login_site=URLS['eh']): -# "Looks up files for matching items" -# mdata = [] - -# # get exhentai login session if applicable -# ex_login = hpx.command.GetLoginStatus(login_site) if "exhentai" in login_site else False -# login_session = None -# if ex_login: -# login_session = hpx.command.GetLoginSession(login_site) -# if login_site == 'exhentai': -# log.info(f"logged in to exhentai: {ex_login}") - -# for mitem in itemtuple: -# gurls = [] # tuple of (title, url) - -# url = mitem.url -# item = mitem.item -# options = mitem.options - -# # url was provided -# if url: -# log.info(f"url provided: {url} for {item}") -# gurls.append((url, url)) -# else: # manually search for id -# log.info(f"url not provided for {item}") -# if (ex_login if "exhentai" in login_site else True): -# # search with title -# i_title = "" -# i_hash = "" -# if PLUGIN_CONFIG.get("filename_search"): -# sources = item.get_sources() -# if sources: -# # get folder/file name -# i_title = os.path.split(sources[0])[1] -# # remove ext -# i_title = os.path.splitext(i_title)[0] -# else: -# if item.titles: -# i_title = item.titles[0].name # make user choice -# if i_title: -# gurls = title_search(i_title, ex='exhentai' in login_site, session=login_session) - -# # TODO: search with hash -# if not gurls: -# pass - -# log.info(f"found {len(gurls)} urls for item: {item}") - -# # list is sorted by date added so we reverse it -# gurls.reverse() - -# log.debug(f"{gurls}") -# final_gurls = [] -# # TODO: maybe prefer language of gallery first? -# pref_lang = PLUGIN_CONFIG.get('preferred_language') -# if pref_lang: -# for t in gurls: -# if pref_lang.lower() in t[0].lower(): -# final_gurls.insert(0, t) -# continue -# final_gurls.append(t) -# else: -# final_gurls = gurls - -# for t, u in final_gurls: -# g_id, g_token = parse_url(u) -# if g_id and g_token: -# mdata.append(hpx.command.MetadataData( -# metadataitem=mitem, -# title=t, -# url=u, -# data={ -# 'gallery': [g_id, g_token], -# 'gallery_url': u, -# })) -# log.info(f"Returning {len(mdata)} data items") -# return tuple(mdata) \ No newline at end of file +@hpx.attach("GalleryFS.parse_metadata_file") +def parse(path, gallery): + f = has_file_metadata(path) + return apply_file_metadata(gallery, f) + +##### --- + +@hpx.attach("Metadata.info") +def metadata_info(): + return hpx.command.MetadataInfo( + identifier = "filemetadata", + name = "File Metadata", + description = "Extracts and applies metadata from a file accompanying a gallery", + sites= ("eze", "E-Hentai-Downloader", "HDoujinDownloader"), + models = ( + hpx.command.GetDatabaseModel("Gallery"), + ) + ) + +@hpx.attach("Metadata.query", trigger='filemetadata') +def query(itemtuple): + "Looks up files for matching items" + mdata = [] + + for mitem in itemtuple: + item = mitem.item + options = mitem.options + + found_files = [] + for s in item.get_sources(): + found_files.extend(has_file_metadata(s)) + + log.info(f"found {len(found_files)} metadata files for item: {item}") + + if found_files: + log.debug(f"{found_files}") + + mdata.append(hpx.command.MetadataData( + metadataitem=mitem, + title=item.preferred_title.name if item.preferred_title else '', + data={ + 'found':found_files, + })) + + log.info(f"Returning {len(mdata)} data items") + return tuple(mdata) + +@hpx.attach("Metadata.apply", trigger='filemetadata') +def apply(datatuple): + mresults = [] + applied = False + + for d in datatuple: + applied = apply_file_metadata(d.item, d.data['found']) + if applied: + mresults.append(hpx.command.MetadataResult(data=d, status=True)) + else: + mresults.append(hpx.command.MetadataResult(data=d, status=False, reason="failed to apply data from file")) + + return tuple(mresults) \ No newline at end of file diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 6499133..235f6ec 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -31,7 +31,7 @@ plugin: Name | Default | Description --- | --- | --- -`characters_namespace` | `character` | which namespace to put the values in the CHARACTERS field in (applies to hdoujin) +`characters_namespace` | `character` | which namespace to put the values in the CHARACTERS field into (applies to hdoujin) # Extending @@ -47,6 +47,9 @@ Follow these steps to add support for more kind of files: # Changelog +- `2.0.0` + - The plugin will also now act as a regular metadata plugin, making it possible to retrieve metadata from files on-demand + - `1.0.3` - Updated the eze handler to save uploaded date as published date From c1958f32eb9ff006085a294330532fbec1e91230 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 29 Aug 2019 00:08:33 +0200 Subject: [PATCH 54/68] Update File Metadata (#32) updated File Metadata plugin to act as a regular metadata handler; --- plugins/File Metadata/hplugin.json | 4 +- plugins/File Metadata/main.py | 180 ++++++++++++----------------- plugins/File Metadata/readme.md | 5 +- 3 files changed, 83 insertions(+), 106 deletions(-) diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index d771846..1d1d5cd 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,13 +2,13 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "1.0.3", + "version": "2.0.0", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", "entry": "main.py", "require": [ - "happypandax >= 0.10.0" + "happypandax >= 0.11.0" ] } diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index 02f575f..9e8c199 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -172,120 +172,94 @@ def inited(): def config_update(cfg): common.plugin_config.update(cfg) -@hpx.attach("GalleryFS.parse_metadata_file") -def parse(path, gallery): +def has_file_metadata(path): fs = hpx.command.CoreFS(path) contents = {x: os.path.split(x)[1].lower() for x in fs.contents(corefs=False) if x.lower().endswith(common.filetypes)} log.debug(f"Contents for {fs.path}:") log.debug(f"{tuple(contents.values())}") - cdata = common.common_data.copy() - - applied = False - + found_files = [] for fnames, dtypes in common.filenames.items(): for fpath, fname in contents.items(): if fname in fnames: - log.debug(f"path: {fpath}") - d = get_common_data(dtypes, fpath) - if d: - applied = True - cdata.update(d) + found_files.append((dtypes, fpath)) break + + return found_files + +def apply_file_metadata(gallery, found_files): + applied = False + cdata = common.common_data.copy() + for dtypes, fpath in found_files: + log.debug(f"path: {fpath}") + d = get_common_data(dtypes, fpath) + if d: + applied = True + cdata.update(d) + if applied: apply_metadata(cdata, gallery) - + return applied -# This is work in progress to turn this plugin into a regular metadata handler too - -# @hpx.attach("Metadata.info") -# def metadata_info(): -# return hpx.command.MetadataInfo( -# identifier = "filemetadata", -# batch = 25, -# name = "File Metadata", -# description = "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", -# models = ( -# hpx.command.GetDatabaseModel("Gallery"), -# ) -# ) - -# def query(itemtuple, login_site=URLS['eh']): -# "Looks up files for matching items" -# mdata = [] - -# # get exhentai login session if applicable -# ex_login = hpx.command.GetLoginStatus(login_site) if "exhentai" in login_site else False -# login_session = None -# if ex_login: -# login_session = hpx.command.GetLoginSession(login_site) -# if login_site == 'exhentai': -# log.info(f"logged in to exhentai: {ex_login}") - -# for mitem in itemtuple: -# gurls = [] # tuple of (title, url) - -# url = mitem.url -# item = mitem.item -# options = mitem.options - -# # url was provided -# if url: -# log.info(f"url provided: {url} for {item}") -# gurls.append((url, url)) -# else: # manually search for id -# log.info(f"url not provided for {item}") -# if (ex_login if "exhentai" in login_site else True): -# # search with title -# i_title = "" -# i_hash = "" -# if PLUGIN_CONFIG.get("filename_search"): -# sources = item.get_sources() -# if sources: -# # get folder/file name -# i_title = os.path.split(sources[0])[1] -# # remove ext -# i_title = os.path.splitext(i_title)[0] -# else: -# if item.titles: -# i_title = item.titles[0].name # make user choice -# if i_title: -# gurls = title_search(i_title, ex='exhentai' in login_site, session=login_session) - -# # TODO: search with hash -# if not gurls: -# pass - -# log.info(f"found {len(gurls)} urls for item: {item}") - -# # list is sorted by date added so we reverse it -# gurls.reverse() - -# log.debug(f"{gurls}") -# final_gurls = [] -# # TODO: maybe prefer language of gallery first? -# pref_lang = PLUGIN_CONFIG.get('preferred_language') -# if pref_lang: -# for t in gurls: -# if pref_lang.lower() in t[0].lower(): -# final_gurls.insert(0, t) -# continue -# final_gurls.append(t) -# else: -# final_gurls = gurls - -# for t, u in final_gurls: -# g_id, g_token = parse_url(u) -# if g_id and g_token: -# mdata.append(hpx.command.MetadataData( -# metadataitem=mitem, -# title=t, -# url=u, -# data={ -# 'gallery': [g_id, g_token], -# 'gallery_url': u, -# })) -# log.info(f"Returning {len(mdata)} data items") -# return tuple(mdata) \ No newline at end of file +@hpx.attach("GalleryFS.parse_metadata_file") +def parse(path, gallery): + f = has_file_metadata(path) + return apply_file_metadata(gallery, f) + +##### --- + +@hpx.attach("Metadata.info") +def metadata_info(): + return hpx.command.MetadataInfo( + identifier = "filemetadata", + name = "File Metadata", + description = "Extracts and applies metadata from a file accompanying a gallery", + sites= ("eze", "E-Hentai-Downloader", "HDoujinDownloader"), + models = ( + hpx.command.GetDatabaseModel("Gallery"), + ) + ) + +@hpx.attach("Metadata.query", trigger='filemetadata') +def query(itemtuple): + "Looks up files for matching items" + mdata = [] + + for mitem in itemtuple: + item = mitem.item + options = mitem.options + + found_files = [] + for s in item.get_sources(): + found_files.extend(has_file_metadata(s)) + + log.info(f"found {len(found_files)} metadata files for item: {item}") + + if found_files: + log.debug(f"{found_files}") + + mdata.append(hpx.command.MetadataData( + metadataitem=mitem, + title=item.preferred_title.name if item.preferred_title else '', + data={ + 'found':found_files, + })) + + log.info(f"Returning {len(mdata)} data items") + return tuple(mdata) + +@hpx.attach("Metadata.apply", trigger='filemetadata') +def apply(datatuple): + mresults = [] + applied = False + + for d in datatuple: + applied = apply_file_metadata(d.item, d.data['found']) + if applied: + mresults.append(hpx.command.MetadataResult(data=d, status=True)) + else: + mresults.append(hpx.command.MetadataResult(data=d, status=False, reason="failed to apply data from file")) + + return tuple(mresults) \ No newline at end of file diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 6499133..235f6ec 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -31,7 +31,7 @@ plugin: Name | Default | Description --- | --- | --- -`characters_namespace` | `character` | which namespace to put the values in the CHARACTERS field in (applies to hdoujin) +`characters_namespace` | `character` | which namespace to put the values in the CHARACTERS field into (applies to hdoujin) # Extending @@ -47,6 +47,9 @@ Follow these steps to add support for more kind of files: # Changelog +- `2.0.0` + - The plugin will also now act as a regular metadata plugin, making it possible to retrieve metadata from files on-demand + - `1.0.3` - Updated the eze handler to save uploaded date as published date From c702c1262907c3d07feaef9ab98dee356e333980 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 5 Sep 2019 17:52:56 +0200 Subject: [PATCH 55/68] update File Metadata --- plugins/File Metadata/extractors/common.py | 4 +++- plugins/File Metadata/hplugin.json | 2 +- plugins/File Metadata/readme.md | 3 +++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/plugins/File Metadata/extractors/common.py b/plugins/File Metadata/extractors/common.py index a494f34..aaeda34 100644 --- a/plugins/File Metadata/extractors/common.py +++ b/plugins/File Metadata/extractors/common.py @@ -88,7 +88,9 @@ def file_to_dict(self, fs: hpx.command.CoreFS) -> typing.Union[dict, None]: with fs.open("r", **kw) as f: for line in f.readlines(): l = line.strip() - k, v = l.split(b':' if fs.inside_archive else ':', 1 ) + if isinstance(l, bytes): + l = l.decode(encoding="utf-8", errors="ignore") + k, v = l.split(':', 1 ) if k.strip(): d[k.strip()] = v.strip() else: diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index 1d1d5cd..689e129 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "e38e24e4-8ca8-420e-b52b-c75510097653", "shortname": "file-metadata", "name": "File Metadata", - "version": "2.0.0", + "version": "2.0.1", "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 235f6ec..1d886ee 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -47,6 +47,9 @@ Follow these steps to add support for more kind of files: # Changelog +- `2.0.1` + - Fixed an issue where metadata files in archives would fail to be detected + - `2.0.0` - The plugin will also now act as a regular metadata plugin, making it possible to retrieve metadata from files on-demand From 76abde75566a41e6458e052f99dc281d918d1c22 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Thu, 5 Sep 2019 18:46:17 +0200 Subject: [PATCH 56/68] update EHentai Metadata --- plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 18 ++++++++++++++---- plugins/EHentai Metadata/readme.md | 4 ++++ 3 files changed, 19 insertions(+), 5 deletions(-) diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index cfd9c4e..bb7513a 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "1.1.0", + "version": "1.2.0", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 97a21b6..3d2cf7c 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -206,7 +206,7 @@ def query(itemtuple, login_site=URLS['eh']): log.info(f"Returning {len(mdata)} data items") return tuple(mdata) -def title_search(title, ex=True, session=None): +def title_search(title, ex=True, session=None, _times=0): "Searches on ehentai for galleries with given title, returns a list of (title, matching gallery urls)" eh_url = URLS['title_search'] log.debug(f"searching with title: {title}") @@ -214,8 +214,6 @@ def title_search(title, ex=True, session=None): params = {f'f_{c}': '0' for c in DEFAULT_CATEGORIES} - title = f'"{title}"' - try: sq = sq.format(title=title) except: @@ -250,7 +248,19 @@ def title_search(title, ex=True, session=None): query=param_query ) log.info(f"final url: {f_eh_url}") - return eh_page_results(f_eh_url, session=session) + r = eh_page_results(f_eh_url, session=session) + + if not r and not _times: + + kw = sq.split('"', 2) # if title was qouted, counts as 1 keyword + kw_count = max(len(kw) - 1, 1) + # this is pretty unreliable and won't detect qouted multi word tags + kw_count += len(" ".join(kw[-1].split()).split(' ')) - 1 # some magic + + if kw_count > 8: # check if exceeds 8 keywords retry with quotes around title + r = title_search(f'"{title}"', ex, session, _times=_times+1) + + return r def eh_page_results(eh_page_url, limit=None, session=None): "Opens eh page, parses for results, and then returns list of (title, url)" diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index a5583b5..8b31c29 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -41,6 +41,10 @@ Name | Default | Description # Changelog +- `1.2.0` + - fixed title being qouted unconditionally + - retry the search with qouted title if keyword count exceeds 8 + - `1.1.0` - added several new options and fixed some errors From cdbc20ac6e7c98d581c8a5ad77fe741b102c0b99 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 15 Oct 2019 18:37:31 +0200 Subject: [PATCH 57/68] add a bunch of downloader plugins; update some plugins; --- plugins/Chaika Downloader/hplugin.json | 15 + plugins/Chaika Downloader/main.py | 149 ++++++ plugins/Chaika Downloader/readme.md | 13 + plugins/Chaika Downloader/test.py | 1 + plugins/Chaika Metadata/main.py | 13 +- plugins/EHentai Downloader/hplugin.json | 15 + plugins/EHentai Downloader/main.py | 222 ++++++++ plugins/EHentai Downloader/readme.md | 22 + plugins/EHentai Downloader/test.py | 1 + plugins/EHentai Login/main.py | 1 - plugins/EHentai Metadata/hplugin.json | 2 +- plugins/EHentai Metadata/main.py | 24 +- plugins/EHentai Metadata/readme.md | 5 +- .../extractors/ehentaidownloader.py | 11 + plugins/File Metadata/extractors/eze.py | 12 + plugins/File Metadata/extractors/hdoujin.py | 12 + plugins/NHentai Downloader/hplugin.json | 15 + plugins/NHentai Downloader/main.py | 150 ++++++ plugins/NHentai Downloader/readme.md | 17 + plugins/NHentai Downloader/test.py | 1 + plugins/NHentai Metadata/hplugin.json | 15 + plugins/NHentai Metadata/main.py | 497 ++++++++++++++++++ plugins/NHentai Metadata/readme.md | 35 ++ plugins/NHentai Metadata/test.py | 1 + 24 files changed, 1237 insertions(+), 12 deletions(-) create mode 100644 plugins/Chaika Downloader/hplugin.json create mode 100644 plugins/Chaika Downloader/main.py create mode 100644 plugins/Chaika Downloader/readme.md create mode 100644 plugins/Chaika Downloader/test.py create mode 100644 plugins/EHentai Downloader/hplugin.json create mode 100644 plugins/EHentai Downloader/main.py create mode 100644 plugins/EHentai Downloader/readme.md create mode 100644 plugins/EHentai Downloader/test.py create mode 100644 plugins/NHentai Downloader/hplugin.json create mode 100644 plugins/NHentai Downloader/main.py create mode 100644 plugins/NHentai Downloader/readme.md create mode 100644 plugins/NHentai Downloader/test.py create mode 100644 plugins/NHentai Metadata/hplugin.json create mode 100644 plugins/NHentai Metadata/main.py create mode 100644 plugins/NHentai Metadata/readme.md create mode 100644 plugins/NHentai Metadata/test.py diff --git a/plugins/Chaika Downloader/hplugin.json b/plugins/Chaika Downloader/hplugin.json new file mode 100644 index 0000000..e78e4f9 --- /dev/null +++ b/plugins/Chaika Downloader/hplugin.json @@ -0,0 +1,15 @@ +{ + "id": "dd86876d-4d4e-438e-bc2e-fbbb18e35742", + "shortname": "chaika-downloader", + "name": "Chaika Downloader", + "version": "1.0.0", + "description": "A plugin that enables downloading manga and doujinshi from panda.chaika.moe", + "author": "Twiddly", + "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Downloader", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Downloader", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.12.0" + ] +} \ No newline at end of file diff --git a/plugins/Chaika Downloader/main.py b/plugins/Chaika Downloader/main.py new file mode 100644 index 0000000..59ccb01 --- /dev/null +++ b/plugins/Chaika Downloader/main.py @@ -0,0 +1,149 @@ +# main.py +import __hpx__ as hpx +import regex + +from bs4 import BeautifulSoup + +DownloadRequest = hpx.command.DownloadRequest + +log = hpx.get_logger("main") + +IDENTIFIER = "chaika" +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} +DEFAULT_DELAY = 0.5 + +URLS = { + 'ch': 'https://panda.chaika.moe', + 'gallery_api': 'https://panda.chaika.moe/jsearch?gallery=', +} + +def website_url_regex_gen(domain, path_regex=None, variable_port=False, variable_tld=False, trailing_slash=True, end=True, trailing_fragment=True): + """ + Generates a regex suitable for a specific domain + """ + rgx = r"^(http\:\/\/|https\:\/\/)?(www\.)?({})".format(domain) + if variable_tld: + rgx += r"\.[a-z]{2,5}" + if variable_port: + rgx += r"(:[0-9]{1,5})?" + if trailing_slash: + rgx += r"\/?" + if path_regex: + rgx += path_regex + if trailing_slash: + rgx += r"\/?" + if trailing_fragment: + rgx += r"(#\S+)?" + if end: + rgx += "$" + return rgx + +@hpx.subscribe("init") +def inited(): + # set default delay if not set + delays = hpx.get_setting("network", "delays", {}) + delay_url = URLS['ch'] + if delay_url not in delays: + log.info(f"Setting delay on {delay_url} requests to {DEFAULT_DELAY}") + delays[delay_url] = DEFAULT_DELAY + hpx.update_setting("network", "delays", delays) + +@hpx.attach("Download.info") +def download_info(): + return hpx.command.DownloadInfo( + identifier = IDENTIFIER, + name = "Chaika", + parser = website_url_regex_gen("panda.chaika.moe", path_regex=r"(gallery|archive)\/[0-9]{3,15}", trailing_slash=True, variable_tld=False, trailing_fragment=True, end=True), + sites = ("https://panda.chaika.moe",), + description = "Download manga and doujinshi from panda.chaika.moe", + ) + +@hpx.attach("Download.query", trigger=IDENTIFIER) +def download_query(item): + """ + Called to query for resource URLs that should be downloaded. + Note that HPX will handle the actual downloading part. + The attached handler should just return all the URLs that should be downloaded in the form of .:class:`DownloadRequest` objects + + should return: + a tuple of :class:`DownloadRequest` for all the URL resources that should be downloaded. + Note that the download system is recursive, so if the URL resource matches a download handler (the same or a different one), + That handler will be called upon with a new :class:`DownloadItem` for that particular URL + (though only once, meaning, no handler will be called upon again with the exact same URL during a single session) + """ + + log.info(f"querying url: {item.url}") + + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + + # chaika has a simple url system where every download url is in the form of https://panda.chaika.moe/archive/32870/download/ + # if the url is a gallery url, find and retrieve the archive urls + + url_type, gid = parse_url(item.url) + + download_urls = [] + + if url_type == 'gallery': + log.info(f"url was a gallery url, retrieving archive urls") + req = hpx.command.SingleGETRequest().request(URLS['gallery_api']+str(gid), req_props) + if req.ok: + log.info("request was successful") + + # get all archive urls + a_urls = req.json.get("archives") + if a_urls: + # we also get to set the name of this download item + title = req.json.get('title') + if title: + item.name = title + + for a in a_urls: + download_urls.append(URLS['ch']+a['download']) + else: + download_urls.append(URLS['ch']+f"/archive/{gid}/download/") + + + download_requests = [] + + if download_urls: + log.debug(f"found {len(download_urls)} download urls: {download_urls}") + for durl in download_urls: + download_requests.append(DownloadRequest(downloaditem=item, url=durl)) + + if download_requests: + log.info(f"was able to prepare requests for {len(download_requests)} urls") + return tuple(download_requests) + +@hpx.attach("Download.done", trigger=IDENTIFIER) +def download_done(result): + """ + Called when downloading of all :class:`DownloadRequest` for a specific :class:`DownloadItem` has finished. + The handler should do any post-processing here (archive files, rename files or folders, delete extranous files and etc.). + Remember to set the `status` property on the :class:`DownloadResult` object to `False` if the post-processing was a failure. + Note that the handler should *not* import the file into HPX (if it's an item), that part will be taken care of by HPX + + should return: + the same :class:`DownloadResult` that was provided to the handler, potentially modified on the 'path' or `status` and `reason` properties + """ + # there's nothing special to post-process in the case of chaika downloader, so just return the result as is + log.info(f"download of archive was successful for {result.downloaditem.name}") + return result + +def parse_url(url): + "Parses url into a tuple of gallery/archive and id" + gallery_id = None + stype = "gallery" + + gallery_id = regex.search('([0-9]+)', url) + if gallery_id: + gallery_id = gallery_id.group() + else: + log.warning("Error extracting id from url: {}".format(url)) + + if 'archive' in url: + stype = 'archive' + + return stype, int(gallery_id) diff --git a/plugins/Chaika Downloader/readme.md b/plugins/Chaika Downloader/readme.md new file mode 100644 index 0000000..593469b --- /dev/null +++ b/plugins/Chaika Downloader/readme.md @@ -0,0 +1,13 @@ +Chaika Downloader +---------------------------- + +> A plugin that enables downloading manga and doujinshi from panda.chaika.moe + +## Configuration + +There's no available config options for this plugin + +# Changelog + +- `1.0.0` + - first version \ No newline at end of file diff --git a/plugins/Chaika Downloader/test.py b/plugins/Chaika Downloader/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/Chaika Downloader/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file diff --git a/plugins/Chaika Metadata/main.py b/plugins/Chaika Metadata/main.py index 8d3fa21..cbb4de3 100644 --- a/plugins/Chaika Metadata/main.py +++ b/plugins/Chaika Metadata/main.py @@ -15,7 +15,7 @@ MATCH_URL_PREFIX = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. MATCH_URL_END = r"\/?$" -DEFAULT_DELAY = 0.5 +DEFAULT_DELAY = 1.5 URLS_REGEX = { 'gallery': MATCH_URL_PREFIX + r"(panda\.chaika\.moe\/(archive|gallery)\/[0-9]+)" + MATCH_URL_END, @@ -72,7 +72,7 @@ def metadata_info(): identifier = "chaika", name = "Panda.Chaika", parser = URLS_REGEX['gallery'], - sites = ("www.panda.chaika.moe",), + sites = ("https://panda.chaika.moe",), description = "Fetch metadata from Panda.Chaika", models = ( hpx.command.GetDatabaseModel("Gallery"), @@ -81,6 +81,11 @@ def metadata_info(): @hpx.attach("Metadata.query", trigger="chaika") def query(itemtuple): + """ + Called to query for candidates to extract metadata from. + Note that HPX will handle choosing which candidates to extract data from. + The attached handler should just return all the candidates found. + """ log.info("Querying chaika for metadata") mdata = [] for mitem in itemtuple: @@ -146,6 +151,10 @@ def query(itemtuple): @hpx.attach("Metadata.apply", trigger="chaika") def apply(datatuple): + """ + Called to fetch and apply metadata to the given data items. + Remember to set the `status` property on the :class:`MetadataResult` object to `True` on a successful fetch. + """ log.info("Applying metadata from chaika") mresult = [] diff --git a/plugins/EHentai Downloader/hplugin.json b/plugins/EHentai Downloader/hplugin.json new file mode 100644 index 0000000..21eb484 --- /dev/null +++ b/plugins/EHentai Downloader/hplugin.json @@ -0,0 +1,15 @@ +{ + "id": "efaec768-760c-49d7-8d45-fb70b7db45e5", + "shortname": "ehentai-downloader", + "name": "EHentai Downloader", + "version": "1.0.0", + "description": "A plugin that enables downloading manga and doujinshi from E-Hentai & ExHentai", + "author": "Twiddly", + "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Downloader", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Downloader", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.12.0" + ] +} \ No newline at end of file diff --git a/plugins/EHentai Downloader/main.py b/plugins/EHentai Downloader/main.py new file mode 100644 index 0000000..5c8dabd --- /dev/null +++ b/plugins/EHentai Downloader/main.py @@ -0,0 +1,222 @@ +# main.py +import __hpx__ as hpx +import regex +import json +from bs4 import BeautifulSoup + +DownloadRequest = hpx.command.DownloadRequest + +log = hpx.get_logger("main") + +EH_IDENTIFIER = "ehentai" +EX_IDENTIFIER = "exhentai" + +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} +DEFAULT_DELAY = 5 + +URLS = { + 'eh': 'https://e-hentai.org', + 'ex': 'https://exhentai.org', + 'e_api': 'https://api.e-hentai.org/api.php', + 'ex_api': 'https://exhentai.org/api.php', + 'e_archiver': 'https://e-hentai.org/archiver.php?gid={gallery_id}&token={gallery_token}&or={archiver_key}', + 'ex_archiver': 'https://exhentai.org/archiver.php?gid={gallery_id}&token={gallery_token}&or={archiver_key}', +} + + +def website_url_regex_gen(domain, path_regex=None, variable_port=False, variable_tld=False, trailing_slash=True, end=True, trailing_fragment=True): + """ + Generates a regex suitable for a specific domain + """ + rgx = r"^(http\:\/\/|https\:\/\/)?(www\.)?({})".format(domain) + if variable_tld: + rgx += r"\.[a-z]{2,5}" + if variable_port: + rgx += r"(:[0-9]{1,5})?" + if trailing_slash: + rgx += r"\/?" + if path_regex: + rgx += path_regex + if trailing_slash: + rgx += r"\/?" + if trailing_fragment: + rgx += r"(#\S+)?" + if end: + rgx += "$" + return rgx + +@hpx.subscribe("init") +def inited(): + # set default delay values if not set + delays = hpx.get_setting("network", "delays", {}) + for u in (URLS['ex'], URLS['eh'], "https://api.e-hentai.org", URLS['ex_api']): + if u not in delays: + log.info(f"Setting delay on {u} requests to {DEFAULT_DELAY}") + delays[u] = DEFAULT_DELAY + hpx.update_setting("network", "delays", delays) + +@hpx.attach("Download.info") +def eh_download_info(): + return hpx.command.DownloadInfo( + identifier = EH_IDENTIFIER, + name = "E-Hentai", + parser = website_url_regex_gen("e-hentai.org", path_regex=r"g\/[0-9]{3,10}\/[0-9a-zA-Z]{3,15}", trailing_slash=True, variable_tld=False, trailing_fragment=True, end=True), + sites = ("https://e-hentai.org",), + description = "Download manga and doujinshi from e-hentai.org", + ) + +@hpx.attach("Download.info") +def ex_download_info(): + return hpx.command.DownloadInfo( + identifier = EX_IDENTIFIER, + name = "ExHentai", + parser = website_url_regex_gen("exhentai.org", path_regex=r"g\/[0-9]{3,10}\/[0-9a-zA-Z]{3,15}", trailing_slash=True, variable_tld=False, trailing_fragment=True, end=True), + sites = ("https://exhentai.org",), + description = "Download manga and doujinshi from exhentai.org", + ) + +@hpx.attach("Download.query", trigger=EH_IDENTIFIER) +def eh_download_query(item): + return download_query(item, False) + +@hpx.attach("Download.query", trigger=EX_IDENTIFIER) +def ex_download_query(item): + return download_query(item, True) + +def download_query(item, is_exhentai): + """ + Called to query for resource URLs that should be downloaded. + Note that HPX will handle the actual downloading part. + The attached handler should just return all the URLs that should be downloaded in the form of .:class:`DownloadRequest` objects + + should return: + a tuple of :class:`DownloadRequest` for all the URL resources that should be downloaded. + Note that the download system is recursive, so if the URL resource matches a download handler (the same or a different one), + That handler will be called upon with a new :class:`DownloadItem` for that particular URL + (though only once, meaning, no handler will be called upon again with the exact same URL during a single session) + """ + + # get ehentai login + login_site = URLS['eh'] if is_exhentai else URLS['ex'] + login_status = hpx.command.GetLoginStatus(login_site) + login_session = None + if login_status: + login_session = hpx.command.GetLoginSession(login_site) + + gid, gtoken = parse_url(item.url) + + download_requests = [] + + thumbnail_req = False + archive_req = False + + if login_session: + log.info("logged in, attempting to download archive") + # get the archiver key + log.info("getting archiver key") + # prepare request + eh_data = { + 'method': 'gdata', + 'gidlist': [[gid, gtoken]], + } + req_props = hpx.command.RequestProperties( + headers=HEADERS, + json=eh_data, + session=login_session + ) + api_url = URLS['ex_api' if is_exhentai else 'e_api'] + log.info(f"requesting with api url {api_url}") + r = hpx.command.SinglePOSTRequest().request(api_url, req_props) + + if r.ok: + try: + try: + response = r.json + except json.JSONDecodeError: + response = None + log.info("got empty response when trying to retrieve archiver key, this usually means that user has no access to exhentai") + if response and not 'error' in response: + for gdata in response['gmetadata']: + if 'archiver_key' in gdata: + if 'title' in gdata: + item.name = gdata['title'] + if 'thumb' in gdata: + download_requests.append( + DownloadRequest( + downloaditem=item, + url=gdata['thumb'], + is_thumbnail=True, + properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session + )) + thumbnail_req = True + + log.info(f"found archiver key for gallery {(gid, gtoken)}") + a_key = gdata['archiver_key'] + a_url = URLS['ex_archiver' if is_exhentai else 'e_archiver'].format(gallery_id=gid, gallery_token=gtoken, archiver_key=a_key) + # prepare request + # get the download url + form_data = { + "dltype": "org", + "dlcheck": "Download Original Archive" + } + req_props = hpx.command.RequestProperties( + headers=HEADERS, + data=form_data, + session=login_session + ) + r = hpx.command.SinglePOSTRequest().request(a_url, req_props) + if r.ok and "Key missing, or incorrect key provided" not in r.text: + soup = BeautifulSoup(r.text, "html.parser") + dp_url = soup.find("p", id="continue") + if dp_url and dp_url.a: # finally + download_requests.append( + DownloadRequest( + downloaditem=item, + url=dp_url.a['href'] + '?start=1', + properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session + filename=item.name.strip()+'.zip')) + archive_req = True + else: + log.warning(f"got invalid key page or bad status: {r.status_code}") + + else: + log.warning(f"didn't find archiver key for data: {eh_data}") + except Exception as e: + log.debug(f"got an error, last request content: \n\t {r.text}") + raise + + if not archive_req: + pass + # TODO: download individual images instead + + if download_requests: + log.info(f"was able to prepare {len(download_requests)} requests") + return tuple(download_requests) + +@hpx.attach("Download.done", trigger=[EX_IDENTIFIER, EH_IDENTIFIER]) +def download_done(result): + """ + Called when downloading of all :class:`DownloadRequest` for a specific :class:`DownloadItem` has finished. + The handler should do any post-processing here (archive files, rename files or folders, delete extranous files and etc.). + Remember to set the `status` property on the :class:`DownloadResult` object to `False` if the post-processing was a failure. + Note that the handler should *not* import the file into HPX (if it's an item), that part will be taken care of by HPX + + should return: + the same :class:`DownloadResult` that was provided to the handler, potentially modified on the 'path' or `status` and `reason` properties + """ + # there's nothing special to post-process in the case of nhentai downloader, so just return the result as is + log.info(f"download of archive was successful for {result.downloaditem.name}") + return result + +def parse_url(url): + "Parses url into a tuple of gallery id and token" + gallery_id = None + gallery_token = None + + gallery_id_token = regex.search('(?<=g/)([0-9]+)/([a-zA-Z0-9]+)', url) + if gallery_id_token: + gallery_id_token = gallery_id_token.group() + gallery_id, gallery_token = gallery_id_token.split('/') + else: + log.warning("Error extracting g_id and g_token from url: {}".format(url)) + return int(gallery_id), gallery_token \ No newline at end of file diff --git a/plugins/EHentai Downloader/readme.md b/plugins/EHentai Downloader/readme.md new file mode 100644 index 0000000..36198e7 --- /dev/null +++ b/plugins/EHentai Downloader/readme.md @@ -0,0 +1,22 @@ +EHentai Downloader +---------------------------- + +> A plugin that enables downloading manga and doujinshi from E-Hentai & ExHentai + +**IMPORTANT:** To download using GP/credits, the plugin [EHentai Login](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) is required to be present + +**IMPORTANT:** Only downloading through ehentai's archiver system (which costs GP/credits) is supported at this time + +## Configuration + +There's no available config options for this plugin + +## Things yet to be implemented + +- Support scraping the individual images +- Torrents (waiting for HPX to support this) + +# Changelog + +- `1.0.0` + - first version \ No newline at end of file diff --git a/plugins/EHentai Downloader/test.py b/plugins/EHentai Downloader/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/EHentai Downloader/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index eb0758c..34867ab 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -50,7 +50,6 @@ def inited(): with open(save_file, "rb") as f: user_dict = pickle.load(f) if user_dict: - log.info(str(user_dict)) login(user_dict, {}) if response is not None: log.info("Successfully re-logged in") diff --git a/plugins/EHentai Metadata/hplugin.json b/plugins/EHentai Metadata/hplugin.json index bb7513a..808db51 100644 --- a/plugins/EHentai Metadata/hplugin.json +++ b/plugins/EHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "1572a650-5352-4d62-802f-8dfb983f9231", "shortname": "ehentai-metadata", "name": "EHentai Metadata", - "version": "1.2.0", + "version": "1.2.1", "description": "A plugin that can fetch metadata from E-Hentai & ExHentai", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata", diff --git a/plugins/EHentai Metadata/main.py b/plugins/EHentai Metadata/main.py index 3d2cf7c..9f32d40 100644 --- a/plugins/EHentai Metadata/main.py +++ b/plugins/EHentai Metadata/main.py @@ -77,9 +77,9 @@ def metadata_info_eh(): return hpx.command.MetadataInfo( identifier = "ehentai", batch = 25, - name = "EHentai", + name = "E-Hentai", parser = URLS_REGEX['eh_gallery'], - sites = ("www.e-hentai.org",), + sites = ("https://e-hentai.org",), description = "Fetch metadata from E-Hentai", models = ( hpx.command.GetDatabaseModel("Gallery"), @@ -93,7 +93,7 @@ def metadata_info_ex(): batch = 25, name = "ExHentai", parser = URLS_REGEX['ex_gallery'], - sites = ("www.exhentai.org",), + sites = ("https://exhentai.org",), description = "Fetch metadata from ExHentai", models = ( hpx.command.GetDatabaseModel("Gallery"), @@ -129,7 +129,13 @@ def apply_ex(datatuple): return apply(datatuple) def query(itemtuple, login_site=URLS['eh']): - "Looks up on ehentai for matching items" + """ + Called to query for candidates to extract metadata from. + Note that HPX will handle choosing which candidates to extract data from. + The attached handler should just return all the candidates found. + + Looks up on ehentai for matching items + """ mdata = [] # get exhentai login session if applicable @@ -274,7 +280,7 @@ def eh_page_results(eh_page_url, limit=None, session=None): ) if session: req_props.session = session - log.debug(f"COOKIES: {session.cookies}") + log.debug(f"COOKIES: {session.cookies.keys()}") r = hpx.command.SingleGETRequest().request(eh_page_url, req_props) soup = BeautifulSoup(r.text, "html.parser") list_style = "compact" @@ -311,6 +317,10 @@ def parse_url(url): return int(gallery_id), gallery_token def apply(datatuple): + """ + Called to fetch and apply metadata to the given data items. + Remember to set the `status` property on the :class:`MetadataResult` object to `True` on a successful fetch. + """ mresults = [] applied = False eh_data = { @@ -418,14 +428,14 @@ def format_metadata(gdata, item, urls_to_apply=None): if ns == 'language' and t != 'translated': lang = t elif ns == "artist": - for a in artists: # the artist extracted from the title likely has better capitalization, so choose that instead + for a in parsed_artists: # the artist extracted from the title likely has better capitalization, so choose that instead if a.lower() == t.lower(): artists.add(a) break else: artists.add(t) elif ns == "group": - for c in circles: # the circle extracted from the title likely has better capitalization, so choose that instead + for c in parsed_circles: # the circle extracted from the title likely has better capitalization, so choose that instead if c.lower() == t.lower(): circles.add(c) break diff --git a/plugins/EHentai Metadata/readme.md b/plugins/EHentai Metadata/readme.md index 8b31c29..423daac 100644 --- a/plugins/EHentai Metadata/readme.md +++ b/plugins/EHentai Metadata/readme.md @@ -30,7 +30,7 @@ Name | Default | Description `add_gallery_url` | `true` | add ehentai url to gallery `preferred_language` | `"english"` | preferred gallery language (in gallery title) to extract from if multiple galleries were found, set empty string for default `enabled_categories` | `['manga', 'doujinshi', 'non-h', 'artistcg', 'gamecg', 'western', 'imageset', 'cosplay', 'asianporn', 'misc']` | categories that are enbaled for the search -`search_query` | `"{title}"` | the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a curly bracket. Tip: if you want to only allow english results, you should modify this to "{title} english" +`search_query` | `"{title}"` | the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a curly bracket. Tip: if you want to only allow english results, you should modify this to "{title} language:english" `search_low_power_tags` | `true` | enable search low power tags `search_torrent_name` | `true` | enable search torrent name `search_gallery_description` | `false` | enable search gallery description @@ -41,6 +41,9 @@ Name | Default | Description # Changelog +- `1.2.1` + - some misc. changes + - `1.2.0` - fixed title being qouted unconditionally - retry the search with qouted title if keyword count exceeds 8 diff --git a/plugins/File Metadata/extractors/ehentaidownloader.py b/plugins/File Metadata/extractors/ehentaidownloader.py index a9c4d18..3a02f95 100644 --- a/plugins/File Metadata/extractors/ehentaidownloader.py +++ b/plugins/File Metadata/extractors/ehentaidownloader.py @@ -7,6 +7,11 @@ class EHentaiDownloader(common.Extractor): def file_to_dict(self, fs): """ + A subclass can choose to override or extend this method. + Should return a dict with data from the file which will be passed to the extract method. + If the file is not supported or should be skipped, return None. + The parameter fs is the file in question. + File is formatted weirdly so we just return {linenumber : line} """ d = {} @@ -26,6 +31,12 @@ def file_to_dict(self, fs): return d def extract(self, filedata): + """ + A subclass must implement this method. + Should populate a dict that looks like common_data (see common.py) and return it + + filedata parameter is the dict created in the file_to_dict method + """ d = {} if filedata: log.debug("Expecting e-hentai downloader metadata file") diff --git a/plugins/File Metadata/extractors/eze.py b/plugins/File Metadata/extractors/eze.py index 9db99de..cf4be26 100644 --- a/plugins/File Metadata/extractors/eze.py +++ b/plugins/File Metadata/extractors/eze.py @@ -7,6 +7,12 @@ class Eze(common.Extractor): def file_to_dict(self, fs): + """ + A subclass can choose to override or extend this method. + Should return a dict with data from the file which will be passed to the extract method. + If the file is not supported or should be skipped, return None. + The parameter fs is the file in question. + """ d = super().file_to_dict(fs) k = ('gallery_info',) if d and not all(map(lambda x: x in d, k)): # make sure all keys are present @@ -17,6 +23,12 @@ def file_to_dict(self, fs): return d def extract(self, filedata): + """ + A subclass must implement this method. + Should populate a dict that looks like common_data (see common.py) and return it + + filedata parameter is the dict created in the file_to_dict method + """ d = {} filedata = filedata.get('gallery_info') if filedata: diff --git a/plugins/File Metadata/extractors/hdoujin.py b/plugins/File Metadata/extractors/hdoujin.py index ea647d7..df2fc06 100644 --- a/plugins/File Metadata/extractors/hdoujin.py +++ b/plugins/File Metadata/extractors/hdoujin.py @@ -6,6 +6,12 @@ class HDoujin(common.Extractor): def file_to_dict(self, fs): + """ + A subclass can choose to override or extend this method. + Should return a dict with data from the file which will be passed to the extract method. + If the file is not supported or should be skipped, return None. + The parameter fs is the file in question. + """ d = super().file_to_dict(fs) if d: if fs.ext.lower() == '.txt': @@ -27,6 +33,12 @@ def file_to_dict(self, fs): return d def extract(self, filedata): + """ + A subclass must implement this method. + Should populate a dict that looks like common_data (see common.py) and return it + + filedata parameter is the dict created in the file_to_dict method + """ d = {} if filedata: log.debug("Expecting hdoujin metadata file") diff --git a/plugins/NHentai Downloader/hplugin.json b/plugins/NHentai Downloader/hplugin.json new file mode 100644 index 0000000..d5d390f --- /dev/null +++ b/plugins/NHentai Downloader/hplugin.json @@ -0,0 +1,15 @@ +{ + "id": "d2d70306-db03-4cc0-b9c6-b5b1f95d10fe", + "shortname": "nhentai-downloader", + "name": "NHentai Downloader", + "version": "1.0.0", + "description": "A plugin that enables downloading manga and doujinshi from nhentai.net", + "author": "Twiddly", + "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.12.0" + ] +} \ No newline at end of file diff --git a/plugins/NHentai Downloader/main.py b/plugins/NHentai Downloader/main.py new file mode 100644 index 0000000..e4389fe --- /dev/null +++ b/plugins/NHentai Downloader/main.py @@ -0,0 +1,150 @@ +# main.py +import __hpx__ as hpx + +from bs4 import BeautifulSoup + +DownloadRequest = hpx.command.DownloadRequest + +log = hpx.get_logger("main") + +IDENTIFIER = "nhentai" +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} +DEFAULT_DELAY = 1.5 + +def website_url_regex_gen(domain, path_regex=None, variable_port=False, variable_tld=False, trailing_slash=True, end=True, trailing_fragment=True): + """ + Generates a regex suitable for a specific domain + """ + rgx = r"^(http\:\/\/|https\:\/\/)?(www\.)?({})".format(domain) + if variable_tld: + rgx += r"\.[a-z]{2,5}" + if variable_port: + rgx += r"(:[0-9]{1,5})?" + if trailing_slash: + rgx += r"\/?" + if path_regex: + rgx += path_regex + if trailing_slash: + rgx += r"\/?" + if trailing_fragment: + rgx += r"(#\S+)?" + if end: + rgx += "$" + return rgx + +@hpx.subscribe("init") +def inited(): + # set default delay if not set + delays = hpx.get_setting("network", "delays", {}) + delay_url = "https://nhentai.net/g/" + if delay_url not in delays: + log.info(f"Setting delay on {delay_url} requests to {DEFAULT_DELAY}") + delays[delay_url] = DEFAULT_DELAY + hpx.update_setting("network", "delays", delays) + +@hpx.attach("Download.info") +def download_info(): + return hpx.command.DownloadInfo( + identifier = IDENTIFIER, + name = "NHentai", + parser = website_url_regex_gen("nhentai.net", path_regex=r"g\/[0-9]{3,10}", trailing_slash=True, variable_tld=False, trailing_fragment=True, end=True), + sites = ("https://nhentai.net",), + description = "Download manga and doujinshi from nhentai.net", + ) + +@hpx.attach("Download.query", trigger=IDENTIFIER) +def download_query(item): + """ + Called to query for resource URLs that should be downloaded. + Note that HPX will handle the actual downloading part. + The attached handler should just return all the URLs that should be downloaded in the form of .:class:`DownloadRequest` objects + + should return: + a tuple of :class:`DownloadRequest` for all the URL resources that should be downloaded. + Note that the download system is recursive, so if the URL resource matches a download handler (the same or a different one), + That handler will be called upon with a new :class:`DownloadItem` for that particular URL + (though only once, meaning, no handler will be called upon again with the exact same URL during a single session) + """ + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + req = hpx.command.SingleGETRequest().request(item.url, req_props) + + log.info(f"querying url: {item.url}") + + download_requests = [] + + if req.ok: + log.info("request was successful") + # parse html page + soup = BeautifulSoup(req.text, "html.parser") + + # get gallery information + log.info("parsing gallery info") + info_div = soup.find("div", id="info") + if info_div: + title_el = soup.find("h1") + if title_el: + item.name = str(title_el.string) + log.info(f"found name of gallery: {item.name}") + else: + log.warning("couldn't find gallery info div") + + # get gallery cover url + cover_div = soup.find("div", id="cover") + if cover_div: + cover_img = cover_div.find("img") + if cover_img: + try: + download_requests.append(DownloadRequest(downloaditem=item, url=cover_img['data-src'], is_thumbnail=True)) + except: + log.warning("failed to get cover src") + + # get gallery page urls + thumbs_div = soup.find("div", id="thumbnail-container") + all_links = thumbs_div.findAll("a") + if all_links: + log.info(f"found {len(all_links)} thumbnail links") + for l in all_links: + # collect the urls to the page images + # nhentai has a simple url system where thumbs are stored at + # https://t.nhentai.net/galleries/1498842/2t.jpg + # and the real image at + # https://i.nhentai.net/galleries/1498842/2.jpg + url_parts = l.img['data-src'] # img is lazy loaded so src isn't available + if url_parts: + url_parts = url_parts.split('/') + img_id = url_parts[-2] + thumb_number = url_parts[-1] + img_number = thumb_number.replace('t', '') + # construct url for real image + img_url = "https://i.nhentai.net/galleries/{}/{}".format(img_id, img_number) + log.debug(f"final image url parsed to be: {img_url}") + # finally add the url to the list of requests for HPX downloader to take care of the rest + download_requests.append(DownloadRequest(downloaditem=item, url=img_url)) + else: + log.warning("failed to get thumbnail src") + else: + log.warning("couldn't find any thumbnail links") + else: + log.warning("request failed") + + if download_requests: + log.info(f"was able to prepare requests for {len(download_requests)} images") + return tuple(download_requests) + +@hpx.attach("Download.done", trigger=IDENTIFIER) +def download_done(result): + """ + Called when downloading of all :class:`DownloadRequest` for a specific :class:`DownloadItem` has finished. + The handler should do any post-processing here (archive files, rename files or folders, delete extranous files and etc.). + Remember to set the `status` property on the :class:`DownloadResult` object to `False` if the post-processing was a failure. + Note that the handler should *not* import the file into HPX (if it's an item), that part will be taken care of by HPX + + should return: + the same :class:`DownloadResult` that was provided to the handler, potentially modified on the 'path' or `status` and `reason` properties + """ + # there's nothing special to post-process in the case of nhentai downloader, so just return the result as is + log.info(f"download of images was successful for {result.downloaditem.name}") + return result \ No newline at end of file diff --git a/plugins/NHentai Downloader/readme.md b/plugins/NHentai Downloader/readme.md new file mode 100644 index 0000000..7f8edd3 --- /dev/null +++ b/plugins/NHentai Downloader/readme.md @@ -0,0 +1,17 @@ +NHentai Downloader +---------------------------- + +> A plugin that enables downloading manga and doujinshi from nhentai.net + +## Configuration + +There's no available config options for this plugin + +## Things yet to be implemented + +- Torrents (waiting for HPX to support this) + +# Changelog + +- `1.0.0` + - first version \ No newline at end of file diff --git a/plugins/NHentai Downloader/test.py b/plugins/NHentai Downloader/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/NHentai Downloader/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file diff --git a/plugins/NHentai Metadata/hplugin.json b/plugins/NHentai Metadata/hplugin.json new file mode 100644 index 0000000..0171660 --- /dev/null +++ b/plugins/NHentai Metadata/hplugin.json @@ -0,0 +1,15 @@ +{ + "id": "7d68901f-8cef-4f3c-82b1-6e93f63ba00c", + "shortname": "nhentai-metadata", + "name": "NHentai Metadata", + "version": "1.0.0", + "description": "A plugin that can fetch metadata from nhentai.net", + "author": "Twiddly", + "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Metadata", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Metadata", + "entry": "main.py", + "test": "test.py", + "require": [ + "happypandax >= 0.10.0" + ] +} \ No newline at end of file diff --git a/plugins/NHentai Metadata/main.py b/plugins/NHentai Metadata/main.py new file mode 100644 index 0000000..655dc15 --- /dev/null +++ b/plugins/NHentai Metadata/main.py @@ -0,0 +1,497 @@ +# main.py +import __hpx__ as hpx +import regex +import arrow +import datetime +import os +import urllib +import html + +from bs4 import BeautifulSoup +from PIL import Image, ImageChops + +log = hpx.get_logger("main") + +MATCH_URL_PREFIX = r"^(http\:\/\/|https\:\/\/)?(www\.)?" # http:// or https:// + www. +MATCH_URL_END = r"\/?$" + +DEFAULT_DELAY = 1.5 + +IDENTIFIER = "nhentai" + +URLS = { + 'nh': 'https://nhentai.net', + 'title_search': "https://nhentai.net/search/?q={title}" +} + +HEADERS = {'user-agent':"Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0"} + +PLUGIN_CONFIG = { + 'filename_search': False, # use the filename/folder-name for searching instead of gallery title + 'remove_namespaces': True, # remove superfluous namespaces like 'artists', 'languages' and 'groups' because they are handled specially in HPX + 'gallery_results_limit': 10, # maximum amount of galleries to return + 'blacklist_tags': [], # tags to ignore when updating tags + 'add_gallery_url': True, # add nhentai url to gallery + 'preferred_language': "english", # preferred gallery langauge (in gallery title) to extract from if multiple galleries were found, set empty string for default + 'search_query': "{title}", # the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a bracket +} + +@hpx.subscribe("init") +def inited(): + PLUGIN_CONFIG.update(hpx.get_plugin_config()) + + # set default delay values if not set + delays = hpx.get_setting("network", "delays", {}) + for u in (URLS['nh'],): + if u not in delays: + log.info(f"Setting delay on {u} requests to {DEFAULT_DELAY}") + delays[u] = DEFAULT_DELAY + hpx.update_setting("network", "delays", delays) + +@hpx.subscribe('config_update') +def config_update(cfg): + PLUGIN_CONFIG.update(cfg) + +@hpx.attach("Metadata.info") +def metadata_info(): + return hpx.command.MetadataInfo( + identifier = IDENTIFIER, + name = "nhentai", + parser = MATCH_URL_PREFIX + r"(nhentai\.net\/g\/[0-9]{3,10})" + MATCH_URL_END, + sites = ("https://nhentai.net",), + description = "Fetch metadata from nhentai.net", + models = ( + hpx.command.GetDatabaseModel("Gallery"), + ) + ) + +@hpx.attach("Metadata.query", trigger=IDENTIFIER) +def query(itemtuple): + """ + Called to query for candidates to extract metadata from. + Note that HPX will handle choosing which candidates to extract data from. + The attached handler should just return all the candidates found. + """ + log.info("Querying nhentai for metadata") + mdata = [] + for mitem in itemtuple: + item = mitem.item + url = mitem.url + gurls = [] # tuple of (title, url) + # url was provided + if url: + log.info(f"url provided: {url} for {item}") + gurls.append((url, url)) + else: # manually search for id + log.info(f"url not provided for {item}") + # search with title + i_title = "" + if PLUGIN_CONFIG.get("filename_search"): + sources = item.get_sources() + if sources: + # get folder/file name + i_title = os.path.split(sources[0])[1] + # remove ext + i_title = os.path.splitext(i_title)[0] + else: + if item.titles: + i_title = item.titles[0].name # make user choice? + if i_title: + gurls = title_search(i_title) + + log.info(f"found {len(gurls)} urls for item: {item}") + + # list is sorted by date added so we reverse it + gurls.reverse() + + log.debug(f"{gurls}") + final_gurls = [] + pref_lang = PLUGIN_CONFIG.get('preferred_language') + if pref_lang: + for t in gurls: + if pref_lang.lower() in t[0].lower(): + final_gurls.insert(0, t) + continue + final_gurls.append(t) + else: + final_gurls = gurls + + for t, u in final_gurls: + g_id = parse_url(u) + if g_id: + mdata.append(hpx.command.MetadataData( + metadataitem = mitem, + title=t, + url=u, + data={ + 'id': g_id, + 'gallery_url': u, + })) + return tuple(mdata) + +@hpx.attach("Metadata.apply", trigger=IDENTIFIER) +def apply(datatuple): + """ + Called to fetch and apply metadata to the given data items. + Remember to set the `status` property on the :class:`MetadataResult` object to `True` on a successful fetch. + """ + log.info("Applying metadata from nhentai") + mresult = [] + + for mdata in datatuple: + applied = False + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + + gallery_url = mdata.data['gallery_url'] + + r = hpx.command.SingleGETRequest().request(gallery_url, req_props) + if r.ok: + response = r.text + if response and not '404 – Not Found' in response: + filtered_data = format_metadata(response, mdata.item, apply_url=PLUGIN_CONFIG.get('add_gallery_url', True), gallery_url=gallery_url) + applied = apply_metadata(filtered_data, mdata.item, mdata.options) + elif response: + log.debug(response) + mresult.append(hpx.command.MetadataResult(data=mdata, status=applied)) + log.info(f"Applied: {applied}") + else: + log.warning(f"Request returned bad status: {r.status_code}") + return tuple(mresult) + +def title_search(title, _times=0): + "Searches on nhentai for galleries with given title, returns a list of (title, matching gallery urls)" + search_url = URLS['title_search'] + log.debug(f"searching with title: {title}") + + sq = PLUGIN_CONFIG.get("search_query") + try: + sq = sq.format(title=title) + except: + log.warning("Failed to use customized search query") + sq = title + + log.info(f"Final search query: {sq}") + + f_url = search_url.format( + title=urllib.parse.quote_plus(sq) + ) + + log.debug(f"final url: {f_url}") + + r = page_results(f_url) + + if not r and not _times: + title = regex.sub(r"\(.+?\)|\[.+?\]", "", title) + title = " ".join(title.split()) + r = title_search(title, _times=_times+1) + return r + +def page_results(page_url, limit=None): + "Opens nhentai page, parses for results, and then returns list of (title, url)" + found_urls = [] # title, url + if limit is None: + limit = PLUGIN_CONFIG.get("gallery_results_limit") + + # prepare request + req_props = hpx.command.RequestProperties( + headers=HEADERS, + ) + r = hpx.command.SingleGETRequest().request(page_url, req_props) + r.raise_for_status() + soup = BeautifulSoup(r.text, "html.parser") + results = soup.findAll("div", class_="gallery", limit=limit) + for x in results: + # str(x.a.string) + t = "" + cap = x.find("div", class_="caption") + if cap: + t = str(cap.string) + u = URLS['nh'] + x.a['href'] + found_urls.append((t or u, u)) + + if not found_urls: + log.warning(f"No results found on url: {page_url}") + log.debug(f"HTML: {r.text}") + return found_urls + +def parse_url(url): + "Extracts the gallery id from url" + gallery_id = None + + gallery_id_token = regex.search('(?<=g/)([0-9]+)', url) + if gallery_id_token: + gallery_id = gallery_id_token.group() + else: + log.warning("Error extracting gallery id from url: {}".format(url)) + return gallery_id + + +def capitalize_text(text): + """ + better str.capitalize + """ + return " ".join(x.capitalize() for x in text.strip().split()) + +def format_metadata(text, item, apply_url=False, gallery_url=None): + """ + Formats metadata to look like this for apply_metadata: + data = { + 'titles': None, # [(title, language),...] + 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] + 'category': None, + 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} + 'pub_date': None, # DateTime object or Arrow object + 'language': None, + 'urls': None # [url, ...] + } + """ + mdata = {} + + soup = BeautifulSoup(text, "html.parser") + info_div = soup.find("div", id="info") + if info_div: + + mdata['titles'] = [] + + parsed_text = None + eng_title = info_div.find("h1") + if eng_title: + eng_title = str(eng_title.string) + parsed_text = hpx.command.ItemTextParser(eng_title) + + parsed_title = parsed_text.extract_title() + if parsed_title: + parsed_title = parsed_title[0] + + mdata['titles'].append((parsed_title or eng_title, 'english')) + + jp_title = info_div.find("h2") + if jp_title: + mdata['titles'].append((str(jp_title.string), 'japanese')) + + parsed_artists = parsed_text.extract_artist() if parsed_text else [] + parsed_circles = parsed_text.extract_circle() if parsed_text else [] + + artists = set() + circles = set() + parodies = set() + + lang = "japanese" # default language + + tags_containers = info_div.find("section", id="tags") + if tags_containers: + extranous_namespaces = ("artists", "categories", "parodies", "groups", "languages") + blacklist_tags = [x.lower() for x in PLUGIN_CONFIG.get("blacklist_tags")] + for tag_container in tags_containers.findAll("div", class_="tag-container"): + ns = list(tag_container.stripped_strings)[0] + if not ns: + continue + ns = ns[:-1] # remove colon + ns = ns.lower() + tags = [list(x.stripped_strings)[0] for x in tag_container.findAll("a", class_="tag")] + + nstag = lambda t: ns + ':' + t + + if ns == "artists": + for t in tags: + if blacklist_tags and nstag(t) in blacklist_tags: + continue + for a in parsed_artists: # the artist extracted from the title likely has better capitalization, so choose that instead + if a.lower() == t.lower(): + artists.add(a) + break + else: + artists.add(t) + elif ns == "groups": + for t in tags: + if blacklist_tags and nstag(t) in blacklist_tags: + continue + for a in parsed_circles: # the circle extracted from the title likely has better capitalization, so choose that instead + if a.lower() == t.lower(): + circles.add(a) + break + else: + circles.add(t) + elif ns == "parodies": + for t in tags: + if blacklist_tags and nstag(t) in blacklist_tags: + continue + parodies.add(t) + elif ns == "categories": + t = tags[0] # only supports one + if not (blacklist_tags and nstag(t) in blacklist_tags): + mdata['category'] = capitalize_text(t) + elif ns == "languages": + for t in tags: + if blacklist_tags and nstag(t) in blacklist_tags: + continue + if t in ('translated'): + continue + lang = t # only supports one + + if PLUGIN_CONFIG.get("remove_namespaces") and ns in extranous_namespaces: + if ns == 'languages': # keep other tags + tags = [x for x in tags if x != lang] + else: + continue + + # add rest as tags + if tags: + mdata.setdefault('tags', {}) + for t in tags: + if blacklist_tags and nstag(t) in blacklist_tags: + continue + if ns == 'tags': + mdata['tags'].setdefault(None, []).append(t) + else: + mdata['tags'].setdefault(ns, []).append(t) + + mdata['language'] = lang + + if not artists: + artists.union(set(parsed_artists)) + if not circles: + circles.union(set(parsed_circles)) + + if parodies: + mdata['parodies'] = parodies + + if artists: + a_circles = [] + for a in artists: + a_circles.append((a, tuple(circles))) # assign circles to each artist + mdata['artists'] = a_circles + + if apply_url: + mdata['urls'] = [gallery_url] + + log.debug(f"formatted data: {mdata}") + + return mdata + +GalleryData = hpx.command.GalleryData +LanguageData = hpx.command.LanguageData +TitleData = hpx.command.TitleData +ArtistData = hpx.command.ArtistData +ArtistNameData = hpx.command.ArtistNameData +ParodyData = hpx.command.ParodyData +ParodyNameData = hpx.command.ParodyNameData +CircleData = hpx.command.CircleData +CategoryData = hpx.command.CategoryData +UrlData = hpx.command.UrlData +NamespaceTagData= hpx.command.NamespaceTagData +TagData= hpx.command.TagData +NamespaceData = hpx.command.NamespaceData + +def apply_metadata(data, gallery, options): + """ + data = { + 'titles': None, # [(title, language),...] + 'artists': None, # [(artist, (circle, circle, ..)),...] + 'parodies': None, # [parody, ...] + 'category': None, + 'tags': None, # [tag, tag, tag, ..] or {ns:[tag, tag, tag, ...]} + 'pub_date': None, # DateTime object or Arrow object + 'language': None, + 'urls': None # [url, ...] + } + """ + + log.debug(f"data: {data}") + + gdata = GalleryData() + + if isinstance(data.get('titles'), (list, tuple, set)): + gtitles = [] + for t, l in data['titles']: + gtitle = None + if t: + t = html.unescape(t) + gtitle = TitleData(name=t) + if t and l: + gtitle.language = LanguageData(name=l) + if gtitle: + gtitles.append(gtitle) + + if gtitles: + gdata.titles = gtitles + log.debug("applied titles") + + if isinstance(data.get('artists'), (list, tuple, set)): + gartists = [] + for a, c in data['artists']: + if a: + gartist = ArtistData(names=[ArtistNameData(name=capitalize_text(a))]) + gartists.append(gartist) + + if c: + gcircles = [] + for circlename in [x for x in c if x]: + gcircles.append(CircleData(name=capitalize_text(circlename))) + gartist.circles = gcircles + + if gartists: + gdata.artists = gartists + log.debug("applied artists") + + if isinstance(data.get('parodies'), (list, tuple, set)): + gparodies = [] + for p in data['parodies']: + if p: + gparody = ParodyData(names=[ParodyNameData(name=capitalize_text(p))]) + gparodies.append(gparody) + + if gparodies: + gdata.parodies = gparodies + log.debug("applied parodies") + + if data.get('category'): + gdata.category = CategoryData(name=data['category']) + log.debug("applied category") + + if data.get('language'): + gdata.language = LanguageData(name=data['language']) + log.debug("applied language") + + if isinstance(data.get('tags'), (dict, list)): + if isinstance(data['tags'], list): + data['tags'] = {None: data['tags']} + gnstags = [] + for ns, tags in data['tags'].items(): + if ns is not None: + ns = ns.strip() + for t in tags: + t = t.strip() + if t: + kw = {'tag': TagData(name=t)} + if ns: + kw['namespace'] = NamespaceData(name=ns) + gnstags.append(NamespaceTagData(**kw)) + + if gnstags: + gdata.tags = gnstags + log.debug("applied tags") + + if isinstance(data.get('pub_date'), (datetime.datetime, arrow.Arrow)): + pub_date = data['pub_date'] + gdata.pub_date = pub_date + log.debug("applied pub_date") + + if isinstance(data.get('urls'), (list, tuple)): + gurls = [] + for u in data['urls']: + if u: + gurls.append(UrlData(name=u)) + if gurls: + gdata.urls = gurls + log.debug("applied urls") + + applied = hpx.command.UpdateItemData(gallery, gdata, options=options) + + log.debug(f"applied: {applied}") + + return applied \ No newline at end of file diff --git a/plugins/NHentai Metadata/readme.md b/plugins/NHentai Metadata/readme.md new file mode 100644 index 0000000..0a732b9 --- /dev/null +++ b/plugins/NHentai Metadata/readme.md @@ -0,0 +1,35 @@ +NHentai Metadata +---------------------------- + +> This plugin fetches metadata from nhentai.net + +## Configuration + +Configure this plugin by adding `nhentai-metadata` to the `plugin.config` namespace in your `config.yaml`: +```yaml +plugin: + config: + nhentai-metadata: + option1: True + option2: + - item 1 + - item 2 +``` + +#### Available options + +Name | Default | Description +--- | --- | --- +`filename_search` | `true` | use the filename/folder-name for searching instead of gallery title +`remove_namespaces` | `true` | remove superfluous namespaces like 'artists', 'languages' and 'groups' and so on because they are handled specially in HPX +`gallery_results_limit` | `10` | maximum amount of galleries to return +`blacklist_tags` | `[]` | tags to ignore when updating tags, a list of `namespace:tag` strings +`add_gallery_url` | `true` | add ehentai url to gallery +`preferred_language` | `"english"` | preferred gallery language (in gallery title) to extract from if multiple galleries were found, set empty string for default +`search_query` | `"{title}"` | the search query, '{title}' will be replaced with the gallery title, use double curly brackets to escape a curly bracket. Tip: if you want to only allow english results, you should modify this to "{title} language:english" + + +# Changelog + +- `1.0.0` + - first version \ No newline at end of file diff --git a/plugins/NHentai Metadata/test.py b/plugins/NHentai Metadata/test.py new file mode 100644 index 0000000..36a317e --- /dev/null +++ b/plugins/NHentai Metadata/test.py @@ -0,0 +1 @@ +# test.py \ No newline at end of file From e59edb548fb56d6606516c859e1d39717fa9b3da Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 15 Oct 2019 18:41:45 +0200 Subject: [PATCH 58/68] update readme; --- README.md | 10 +++++++--- build.py | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 94a1df5..5b99d46 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ -##### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). +#### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). ### How to download @@ -21,9 +21,13 @@ Read the relevant section [#Be careful about plugins](https://happypandax.github Name | Version | Description --- | --- | --- +[**Chaika Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from panda.chaika.moe* [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `1.0.0` | *A plugin that can fetch metadata from Panda.Chaika* +[**EHentai Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from E-Hentai & ExHentai* [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `1.0.0` | *A plugin that can login to E-Hentai & ExHentai* -[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `1.0.0` | *A plugin that can fetch metadata from E-Hentai & ExHentai* -[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `1.0.0` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* +[**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `1.2.1` | *A plugin that can fetch metadata from E-Hentai & ExHentai* +[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `2.0.1` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* +[**NHentai Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from nhentai.net* +[**NHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Metadata) | `1.0.0` | *A plugin that can fetch metadata from nhentai.net* diff --git a/build.py b/build.py index d207964..b67c4bd 100644 --- a/build.py +++ b/build.py @@ -4,7 +4,7 @@ from urllib.parse import quote readme = """ -##### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). +#### In this repository resides plugins for HappyPanda X. If you wish to write a plugin for HPX head over to [the docs](https://happypandax.github.io/plugin.html#plugins). ### How to download From ac372406f17fa989ec6b2ae46b1cda3cb8099d5c Mon Sep 17 00:00:00 2001 From: Twiddly Date: Tue, 7 Jul 2020 13:06:02 +0200 Subject: [PATCH 59/68] update ehentai login to 1.1.0; --- README.md | 2 +- plugins/EHentai Login/hplugin.json | 4 ++-- plugins/EHentai Login/main.py | 22 ++++++++++++++++------ plugins/EHentai Login/readme.md | 5 ++++- plugins/EHentai Login/site/index.html | 16 ++++++++++++---- plugins/EHentai Login/site/script.js | 10 +++++----- plugins/File Metadata/main.py | 10 ++++++++++ 7 files changed, 50 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 5b99d46..73baf4d 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ Name | Version | Description [**Chaika Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from panda.chaika.moe* [**Chaika Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/Chaika%20Metadata) | `1.0.0` | *A plugin that can fetch metadata from Panda.Chaika* [**EHentai Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from E-Hentai & ExHentai* -[**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `1.0.0` | *A plugin that can login to E-Hentai & ExHentai* +[**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `1.1.0` | *A plugin that can login to E-Hentai & ExHentai* [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `1.2.1` | *A plugin that can fetch metadata from E-Hentai & ExHentai* [**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `2.0.1` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* [**NHentai Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from nhentai.net* diff --git a/plugins/EHentai Login/hplugin.json b/plugins/EHentai Login/hplugin.json index 5bdfe1a..f35d421 100644 --- a/plugins/EHentai Login/hplugin.json +++ b/plugins/EHentai Login/hplugin.json @@ -2,7 +2,7 @@ "id": "d9b1d111-7250-4083-9efb-356fabbeada7", "shortname": "ehentai-login", "name": "EHentai Login", - "version": "1.0.0", + "version": "1.1.0", "description": "A plugin that can login to E-Hentai & ExHentai", "author": "Twiddly", "site_folder": "site/", @@ -13,4 +13,4 @@ "require": [ "happypandax >= 0.10.0" ] -} \ No newline at end of file +} diff --git a/plugins/EHentai Login/main.py b/plugins/EHentai Login/main.py index 34867ab..7563dbe 100644 --- a/plugins/EHentai Login/main.py +++ b/plugins/EHentai Login/main.py @@ -85,15 +85,25 @@ def login(userpass, options): ipb_member = userpass.get('ipb_member_id', "") ipb_pass = userpass.get('ipb_pass_hash', "") - if ipb_member and ipb_pass: + try: + if not ipb_member or not ipb_pass: + raise ValueError("Missing ipb_member_id or ipb_pass_hash") cookies = {} - # get user input + + additional = userpass.get('additional', "") + if additional: + try: + additional = {k.strip():v.strip() for k, v in [x.strip().split('=', 1) for x in additional.split(',')] } + cookies.update(additional) + except: + raise ValueError("Failed to parse additional values") + cookies.update({ 'ipb_member_id': ipb_member, 'ipb_pass_hash': ipb_pass, }) - + # prepare request req_props = hpx.command.RequestProperties( session=True, @@ -123,12 +133,12 @@ def login(userpass, options): current_user_name = ipb_member save_user_dict() - + else: status_text = r.reason - else: - status_text = "No user credentials provided" + except ValueError as e: + status_text = str(e) return response diff --git a/plugins/EHentai Login/readme.md b/plugins/EHentai Login/readme.md index cbe62c5..7258ebc 100644 --- a/plugins/EHentai Login/readme.md +++ b/plugins/EHentai Login/readme.md @@ -9,6 +9,9 @@ Replace `[webserver-host]` with wherever your HPX webserver is hosted at. # Changelog +- `1.1.0` + - Added a new field for additional cookie values + - `1.0.0` - Updated to reflect new changes in HPX v0.10.0 @@ -16,4 +19,4 @@ Replace `[webserver-host]` with wherever your HPX webserver is hosted at. - increase default delay limit on EH requests to `9` from `4` secs, this value can be tweaked in `network.delays` inside your`config.yaml` - `0.1.0b` - - first version \ No newline at end of file + - first version diff --git a/plugins/EHentai Login/site/index.html b/plugins/EHentai Login/site/index.html index 3c0e553..6d463c0 100644 --- a/plugins/EHentai Login/site/index.html +++ b/plugins/EHentai Login/site/index.html @@ -19,7 +19,7 @@
  • Go on Console tab
  • Write: document.cookie
  • A line of values should appear that correspond to active cookies
  • -
  • Look for the ipb_member_id and ipb_pass_hash values
  • +
  • Look for the ipb_member_id, ipb_pass_hash and other values
  • {% endblock %} @@ -37,12 +37,20 @@
    - +
    - +
    +
    + +
    +

    Comma-separated values: key_1=value_1, key_2=value2

    +
    + +
    +
    @@ -51,4 +59,4 @@
    -{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/plugins/EHentai Login/site/script.js b/plugins/EHentai Login/site/script.js index 7e0a429..83b68b2 100644 --- a/plugins/EHentai Login/site/script.js +++ b/plugins/EHentai Login/site/script.js @@ -8,7 +8,7 @@ function set_err_msg(msg) { document.querySelector("#error-msg").innerHTML = msg } -function form_status(cls) { +function form_status(cls, msg) { switch (cls) { case 'success': document.querySelector("form").classList.add("success") @@ -17,7 +17,7 @@ function form_status(cls) { break case 'error': if (!document.querySelector("#error-msg").innerHTML) - set_err_msg("Failed to login") + set_err_msg("Failed to login: " + msg.toString()) document.querySelector("form").classList.add("error") document.querySelector("form").classList.remove("success") document.querySelector("form").classList.remove("warning") @@ -55,7 +55,7 @@ function check_login(first_time) { } } else { if (!first_time) { - form_status("error") + form_status("error", fdata.status) } } }) @@ -69,7 +69,7 @@ function on_login(e) { } for (var i in arr) { let x = arr[i] - if (x.name == 'ipb_member_id' || x.name == 'ipb_pass_hash') { + if ( ['ipb_member_id', 'ipb_pass_hash', 'additional'].includes(x.name)) { data[x.name] = x.value } else if (x.name == 'exhentai') data[x.name] = (x.value == 'on') ? true : false @@ -121,4 +121,4 @@ function serialize_form(form) { } } return s; -} \ No newline at end of file +} diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index 9e8c199..c271463 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -158,6 +158,16 @@ def apply_metadata(data, gallery, options={}): gdata.urls = SetValue(gurls) log.debug("applied urls") + if data.get('times_read'): + gdata.times_read = SetValue(data['times_read']) + log.debug("applied times_read") + + if data['times_read'] > 0: + gallery_id = gallery.id + page_id = gallery.last_page.id + + GalleryProgress.update_progress(gallery_id, page_id) + applied = hpx.command.UpdateItemData(gallery, gdata, options=options) log.debug(f"applied: {applied}") From 01faceb0db9516aad2a392de4161d5da7987873a Mon Sep 17 00:00:00 2001 From: Twiddly Date: Mon, 17 Aug 2020 03:51:41 +0200 Subject: [PATCH 60/68] updated nhentai metadata --- plugins/NHentai Metadata/hplugin.json | 2 +- plugins/NHentai Metadata/main.py | 4 ++-- plugins/NHentai Metadata/readme.md | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/plugins/NHentai Metadata/hplugin.json b/plugins/NHentai Metadata/hplugin.json index 0171660..78e3ea3 100644 --- a/plugins/NHentai Metadata/hplugin.json +++ b/plugins/NHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "7d68901f-8cef-4f3c-82b1-6e93f63ba00c", "shortname": "nhentai-metadata", "name": "NHentai Metadata", - "version": "1.0.0", + "version": "1.0.1", "description": "A plugin that can fetch metadata from nhentai.net", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Metadata", diff --git a/plugins/NHentai Metadata/main.py b/plugins/NHentai Metadata/main.py index 655dc15..74039da 100644 --- a/plugins/NHentai Metadata/main.py +++ b/plugins/NHentai Metadata/main.py @@ -260,7 +260,7 @@ def format_metadata(text, item, apply_url=False, gallery_url=None): parsed_text = None eng_title = info_div.find("h1") if eng_title: - eng_title = str(eng_title.string) + eng_title = str(eng_title.text) parsed_text = hpx.command.ItemTextParser(eng_title) parsed_title = parsed_text.extract_title() @@ -271,7 +271,7 @@ def format_metadata(text, item, apply_url=False, gallery_url=None): jp_title = info_div.find("h2") if jp_title: - mdata['titles'].append((str(jp_title.string), 'japanese')) + mdata['titles'].append((str(jp_title.text), 'japanese')) parsed_artists = parsed_text.extract_artist() if parsed_text else [] parsed_circles = parsed_text.extract_circle() if parsed_text else [] diff --git a/plugins/NHentai Metadata/readme.md b/plugins/NHentai Metadata/readme.md index 0a732b9..fdf7f71 100644 --- a/plugins/NHentai Metadata/readme.md +++ b/plugins/NHentai Metadata/readme.md @@ -31,5 +31,8 @@ Name | Default | Description # Changelog +- `1.0.1` + - updated to reflect site changes where titles where not geting extracted + - `1.0.0` - first version \ No newline at end of file From 6472a37cf6914fa32f99069724fa09fa324ddd95 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Mon, 17 Aug 2020 04:01:07 +0200 Subject: [PATCH 61/68] updated nhentai metadata (#38) --- plugins/NHentai Metadata/hplugin.json | 2 +- plugins/NHentai Metadata/main.py | 4 ++-- plugins/NHentai Metadata/readme.md | 3 +++ 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/plugins/NHentai Metadata/hplugin.json b/plugins/NHentai Metadata/hplugin.json index 0171660..78e3ea3 100644 --- a/plugins/NHentai Metadata/hplugin.json +++ b/plugins/NHentai Metadata/hplugin.json @@ -2,7 +2,7 @@ "id": "7d68901f-8cef-4f3c-82b1-6e93f63ba00c", "shortname": "nhentai-metadata", "name": "NHentai Metadata", - "version": "1.0.0", + "version": "1.0.1", "description": "A plugin that can fetch metadata from nhentai.net", "author": "Twiddly", "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Metadata", diff --git a/plugins/NHentai Metadata/main.py b/plugins/NHentai Metadata/main.py index 655dc15..74039da 100644 --- a/plugins/NHentai Metadata/main.py +++ b/plugins/NHentai Metadata/main.py @@ -260,7 +260,7 @@ def format_metadata(text, item, apply_url=False, gallery_url=None): parsed_text = None eng_title = info_div.find("h1") if eng_title: - eng_title = str(eng_title.string) + eng_title = str(eng_title.text) parsed_text = hpx.command.ItemTextParser(eng_title) parsed_title = parsed_text.extract_title() @@ -271,7 +271,7 @@ def format_metadata(text, item, apply_url=False, gallery_url=None): jp_title = info_div.find("h2") if jp_title: - mdata['titles'].append((str(jp_title.string), 'japanese')) + mdata['titles'].append((str(jp_title.text), 'japanese')) parsed_artists = parsed_text.extract_artist() if parsed_text else [] parsed_circles = parsed_text.extract_circle() if parsed_text else [] diff --git a/plugins/NHentai Metadata/readme.md b/plugins/NHentai Metadata/readme.md index 0a732b9..fdf7f71 100644 --- a/plugins/NHentai Metadata/readme.md +++ b/plugins/NHentai Metadata/readme.md @@ -31,5 +31,8 @@ Name | Default | Description # Changelog +- `1.0.1` + - updated to reflect site changes where titles where not geting extracted + - `1.0.0` - first version \ No newline at end of file From 10e87d9320b5e681098ba53dcaadab42e69ee0b8 Mon Sep 17 00:00:00 2001 From: AnonRaver <70525532+AnonRaver@users.noreply.github.com> Date: Mon, 31 Aug 2020 16:01:52 +0200 Subject: [PATCH 62/68] fix gallery name parsing because of layout change Title was always "None" because the page layout changed and they put multiple inside the

    --- plugins/NHentai Downloader/main.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/plugins/NHentai Downloader/main.py b/plugins/NHentai Downloader/main.py index e4389fe..14bc655 100644 --- a/plugins/NHentai Downloader/main.py +++ b/plugins/NHentai Downloader/main.py @@ -84,10 +84,12 @@ def download_query(item): log.info("parsing gallery info") info_div = soup.find("div", id="info") if info_div: - title_el = soup.find("h1") + title_el = soup.find("h1", class_="title") if title_el: - item.name = str(title_el.string) - log.info(f"found name of gallery: {item.name}") + title_name = soup.find("span", class_="pretty") + if title_name: + item.name = str(title_name.string) + log.info(f"found name of gallery: {item.name}") else: log.warning("couldn't find gallery info div") @@ -147,4 +149,4 @@ def download_done(result): """ # there's nothing special to post-process in the case of nhentai downloader, so just return the result as is log.info(f"download of images was successful for {result.downloaditem.name}") - return result \ No newline at end of file + return result From 4ecc1b35521a7f49a656206bcf8a5409cb16bca8 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sun, 21 Mar 2021 14:38:43 +0100 Subject: [PATCH 63/68] add better error handling in filemetadata; --- plugins/File Metadata/extractors/common.py | 14 ++++++----- plugins/File Metadata/hplugin.json | 22 ++++++++--------- plugins/File Metadata/main.py | 28 +++++++++++----------- 3 files changed, 32 insertions(+), 32 deletions(-) diff --git a/plugins/File Metadata/extractors/common.py b/plugins/File Metadata/extractors/common.py index aaeda34..23b79c6 100644 --- a/plugins/File Metadata/extractors/common.py +++ b/plugins/File Metadata/extractors/common.py @@ -5,6 +5,9 @@ log = hpx.get_logger(__name__) +class IncompatibleFile(ValueError): + pass + class DataType(enum.Flag): """ The available extractors. @@ -20,7 +23,7 @@ class DataType(enum.Flag): filenames = { "info.json": DataType.eze | DataType.hdoujin, "info.txt": DataType.hdoujin | DataType.e_hentai_downloader, - } +} common_data = { 'titles': None, # [(title, language),...] @@ -90,14 +93,13 @@ def file_to_dict(self, fs: hpx.command.CoreFS) -> typing.Union[dict, None]: l = line.strip() if isinstance(l, bytes): l = l.decode(encoding="utf-8", errors="ignore") - k, v = l.split(':', 1 ) + k, v = l.split(':', 1) if k.strip(): d[k.strip()] = v.strip() else: raise NotImplementedError(f"{fs.ext} filetype not supported yet") - except Exception: # Bad, I know, but too lazy - log.warning("An error occured while trying to parse file into a dict") - raise ValueError + except Exception as e: # Bad, I know, but too lazy + raise IncompatibleFile(e) return d def extract(self, filedata: dict) -> dict: @@ -107,4 +109,4 @@ def extract(self, filedata: dict) -> dict: filedata parameter is the dict created in the file_to_dict method """ - raise NotImplementedError \ No newline at end of file + raise NotImplementedError diff --git a/plugins/File Metadata/hplugin.json b/plugins/File Metadata/hplugin.json index 689e129..9defcf6 100644 --- a/plugins/File Metadata/hplugin.json +++ b/plugins/File Metadata/hplugin.json @@ -1,14 +1,12 @@ { - "id": "e38e24e4-8ca8-420e-b52b-c75510097653", - "shortname": "file-metadata", - "name": "File Metadata", - "version": "2.0.1", - "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", - "author": "Twiddly", - "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", - "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", - "entry": "main.py", - "require": [ - "happypandax >= 0.11.0" - ] + "id": "e38e24e4-8ca8-420e-b52b-c75510097653", + "shortname": "file-metadata", + "name": "File Metadata", + "version": "2.0.2", + "description": "Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin", + "author": "Twiddly", + "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata", + "entry": "main.py", + "require": ["happypandax >= 0.11.0"] } diff --git a/plugins/File Metadata/main.py b/plugins/File Metadata/main.py index c271463..4e85c0f 100644 --- a/plugins/File Metadata/main.py +++ b/plugins/File Metadata/main.py @@ -25,8 +25,8 @@ def get_common_data(datatypes, fpath): if ex: try: fdata = ex.file_to_dict(fpath) - except ValueError: - log.info(f"Skipping {datatype}") + except common.IncompatibleFile as e: + log.info(f"Skipping incompatible file for {datatype}: {str(e)}") continue if fdata: log.info(f"{datatype} matched!") @@ -49,8 +49,8 @@ def get_common_data(datatypes, fpath): CircleData = hpx.command.CircleData CategoryData = hpx.command.CategoryData UrlData = hpx.command.UrlData -NamespaceTagData= hpx.command.NamespaceTagData -TagData= hpx.command.TagData +NamespaceTagData = hpx.command.NamespaceTagData +TagData = hpx.command.TagData NamespaceData = hpx.command.NamespaceData def apply_metadata(data, gallery, options={}): @@ -118,7 +118,7 @@ def apply_metadata(data, gallery, options={}): if data.get('category'): gdata.category = SetValue(CategoryData(name=data['category'])) log.debug("applied category") - + if data.get('language'): gdata.language = SetValue(LanguageData(name=data['language'])) log.debug("applied language") @@ -173,7 +173,7 @@ def apply_metadata(data, gallery, options={}): log.debug(f"applied: {applied}") return applied - + @hpx.subscribe("init") def inited(): common.plugin_config.update(hpx.get_plugin_config()) @@ -218,16 +218,16 @@ def parse(path, gallery): f = has_file_metadata(path) return apply_file_metadata(gallery, f) -##### --- +##### --- @hpx.attach("Metadata.info") def metadata_info(): return hpx.command.MetadataInfo( - identifier = "filemetadata", - name = "File Metadata", - description = "Extracts and applies metadata from a file accompanying a gallery", - sites= ("eze", "E-Hentai-Downloader", "HDoujinDownloader"), - models = ( + identifier="filemetadata", + name="File Metadata", + description="Extracts and applies metadata from a file accompanying a gallery", + sites=("eze", "E-Hentai-Downloader", "HDoujinDownloader"), + models=( hpx.command.GetDatabaseModel("Gallery"), ) ) @@ -254,7 +254,7 @@ def query(itemtuple): metadataitem=mitem, title=item.preferred_title.name if item.preferred_title else '', data={ - 'found':found_files, + 'found': found_files, })) log.info(f"Returning {len(mdata)} data items") @@ -272,4 +272,4 @@ def apply(datatuple): else: mresults.append(hpx.command.MetadataResult(data=d, status=False, reason="failed to apply data from file")) - return tuple(mresults) \ No newline at end of file + return tuple(mresults) From 4c2a3132578cd051a49813e72124868e49866883 Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sun, 21 Mar 2021 15:23:44 +0100 Subject: [PATCH 64/68] update readmes; --- plugins/File Metadata/readme.md | 3 +++ plugins/NHentai Downloader/hplugin.json | 26 ++++++++++++------------- plugins/NHentai Downloader/readme.md | 3 +++ 3 files changed, 18 insertions(+), 14 deletions(-) diff --git a/plugins/File Metadata/readme.md b/plugins/File Metadata/readme.md index 1d886ee..a8a7244 100644 --- a/plugins/File Metadata/readme.md +++ b/plugins/File Metadata/readme.md @@ -47,6 +47,9 @@ Follow these steps to add support for more kind of files: # Changelog +- `2.0.2` + - Improved error handling on incompatible detected files + - `2.0.1` - Fixed an issue where metadata files in archives would fail to be detected diff --git a/plugins/NHentai Downloader/hplugin.json b/plugins/NHentai Downloader/hplugin.json index d5d390f..8f59237 100644 --- a/plugins/NHentai Downloader/hplugin.json +++ b/plugins/NHentai Downloader/hplugin.json @@ -1,15 +1,13 @@ { - "id": "d2d70306-db03-4cc0-b9c6-b5b1f95d10fe", - "shortname": "nhentai-downloader", - "name": "NHentai Downloader", - "version": "1.0.0", - "description": "A plugin that enables downloading manga and doujinshi from nhentai.net", - "author": "Twiddly", - "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader", - "website": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader", - "entry": "main.py", - "test": "test.py", - "require": [ - "happypandax >= 0.12.0" - ] -} \ No newline at end of file + "id": "d2d70306-db03-4cc0-b9c6-b5b1f95d10fe", + "shortname": "nhentai-downloader", + "name": "NHentai Downloader", + "version": "1.0.1", + "description": "A plugin that enables downloading manga and doujinshi from nhentai.net", + "author": "Twiddly", + "update_url": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader", + "website": "https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader", + "entry": "main.py", + "test": "test.py", + "require": ["happypandax >= 0.12.0"] +} diff --git a/plugins/NHentai Downloader/readme.md b/plugins/NHentai Downloader/readme.md index 7f8edd3..f2b1790 100644 --- a/plugins/NHentai Downloader/readme.md +++ b/plugins/NHentai Downloader/readme.md @@ -12,6 +12,9 @@ There's no available config options for this plugin - Torrents (waiting for HPX to support this) # Changelog + +- `1.0.1` + - fixed an issue where galleries would fail to download because the extracted title was invalid - `1.0.0` - first version \ No newline at end of file From 8ec25e3535f622fa61356ad043363541915ba49f Mon Sep 17 00:00:00 2001 From: Twiddly Date: Sun, 21 Mar 2021 15:26:40 +0100 Subject: [PATCH 65/68] update readme --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 73baf4d..d3142f9 100644 --- a/README.md +++ b/README.md @@ -26,8 +26,8 @@ Name | Version | Description [**EHentai Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from E-Hentai & ExHentai* [**EHentai Login**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Login) | `1.1.0` | *A plugin that can login to E-Hentai & ExHentai* [**EHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/EHentai%20Metadata) | `1.2.1` | *A plugin that can fetch metadata from E-Hentai & ExHentai* -[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `2.0.1` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* -[**NHentai Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader) | `1.0.0` | *A plugin that enables downloading manga and doujinshi from nhentai.net* -[**NHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Metadata) | `1.0.0` | *A plugin that can fetch metadata from nhentai.net* +[**File Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/File%20Metadata) | `2.0.2` | *Extracts and applies metadata from a file accompanying a gallery. Supports files produced from eze, e-hentai-downloader and hdoujin* +[**NHentai Downloader**](https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Downloader) | `1.0.1` | *A plugin that enables downloading manga and doujinshi from nhentai.net* +[**NHentai Metadata**](https://github.com/happypandax/plugins/tree/master/plugins/NHentai%20Metadata) | `1.0.1` | *A plugin that can fetch metadata from nhentai.net* From b7c564f71d2c12af684e7ce0a08f64fa77645b46 Mon Sep 17 00:00:00 2001 From: glop102 Date: Thu, 1 Sep 2022 02:50:49 -0400 Subject: [PATCH 66/68] Added tags to the title for common failure conditions There are two common failure modes for e(x)hentai galleries 1) the gallery is expunged (eg copyright takedown) 2) the user is out of GP to download the archive Failure 2 is easily detectable as the response to getting the archive URL specifically reports such a failure. Failure 1 is more of an educated guess as the point of detection is getting a 404 even though we were given an archive key. Also a seemingly innocuous bug of the condition of which login service to use. The condition to choose x or non-x was backwards. --- plugins/EHentai Downloader/main.py | 34 ++++++++++++++++++------------ 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/plugins/EHentai Downloader/main.py b/plugins/EHentai Downloader/main.py index 5c8dabd..f77a972 100644 --- a/plugins/EHentai Downloader/main.py +++ b/plugins/EHentai Downloader/main.py @@ -97,7 +97,7 @@ def download_query(item, is_exhentai): """ # get ehentai login - login_site = URLS['eh'] if is_exhentai else URLS['ex'] + login_site = URLS['ex'] if is_exhentai else URLS['eh'] login_status = hpx.command.GetLoginStatus(login_site) login_session = None if login_status: @@ -165,19 +165,27 @@ def download_query(item, is_exhentai): session=login_session ) r = hpx.command.SinglePOSTRequest().request(a_url, req_props) - if r.ok and "Key missing, or incorrect key provided" not in r.text: - soup = BeautifulSoup(r.text, "html.parser") - dp_url = soup.find("p", id="continue") - if dp_url and dp_url.a: # finally - download_requests.append( - DownloadRequest( - downloaditem=item, - url=dp_url.a['href'] + '?start=1', - properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session - filename=item.name.strip()+'.zip')) - archive_req = True + if r.ok: + if "Insufficient funds" in r.text: + log.info("Unable to grab gallery archive due to insufficent funds (GP) on the account") + item.name = "(Insufficient GP) "+item.name + elif "Key missing, or incorrect key provided" not in r.text: + soup = BeautifulSoup(r.text, "html.parser") + dp_url = soup.find("p", id="continue") + if dp_url and dp_url.a: # finally + download_requests.append( + DownloadRequest( + downloaditem=item, + url=dp_url.a['href'] + '?start=1', + properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session + filename=item.name.strip()+'.zip')) + archive_req = True else: log.warning(f"got invalid key page or bad status: {r.status_code}") + if r.status_code == 404 and "This gallery is currently unavailable" in r.text: + #We know that there is a valid key for us to get here, so the gallery existed at some point in the past + #Most of the time, it is a copyright takedown, but I don't see a simple way to determine what is the cause + item.name = "(Gallery Expunged) "+item.name else: log.warning(f"didn't find archiver key for data: {eh_data}") @@ -219,4 +227,4 @@ def parse_url(url): gallery_id, gallery_token = gallery_id_token.split('/') else: log.warning("Error extracting g_id and g_token from url: {}".format(url)) - return int(gallery_id), gallery_token \ No newline at end of file + return int(gallery_id), gallery_token From c3389884c10a5e35dce5976b4ab40d74eafcdc2b Mon Sep 17 00:00:00 2001 From: glop102 Date: Wed, 14 Sep 2022 23:58:15 -0400 Subject: [PATCH 67/68] Failed attempt at expunged galleries This is only a failure because the flag seems to make zero sense. I have examples where things are marked as expunged but are still totally available on both domains, archives included. I also have examples where the archives are not available but the expunged flag is still false. I have not found a single example yet where a gallery is marked as expunged and is unavailable, ergo, the flag is useless. --- plugins/EHentai Downloader/main.py | 34 ++++++++++++++++-------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/plugins/EHentai Downloader/main.py b/plugins/EHentai Downloader/main.py index f77a972..996e8d5 100644 --- a/plugins/EHentai Downloader/main.py +++ b/plugins/EHentai Downloader/main.py @@ -137,19 +137,22 @@ def download_query(item, is_exhentai): log.info("got empty response when trying to retrieve archiver key, this usually means that user has no access to exhentai") if response and not 'error' in response: for gdata in response['gmetadata']: + # Often the gallery is still available to download even though it is flagged as expunged + # This makes no sense to me, as other times when the gallery is not available, this flag is still set to false and so seems like it is totally pointless + # if "expunged" in gdata and gdata["expunged"]==True: + # item.name = "(Gallery Expunged) "+item.name + if 'title' in gdata: + item.name = gdata['title'] + if 'thumb' in gdata: + download_requests.append( + DownloadRequest( + downloaditem=item, + url=gdata['thumb'], + is_thumbnail=True, + properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session + )) + thumbnail_req = True if 'archiver_key' in gdata: - if 'title' in gdata: - item.name = gdata['title'] - if 'thumb' in gdata: - download_requests.append( - DownloadRequest( - downloaditem=item, - url=gdata['thumb'], - is_thumbnail=True, - properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session - )) - thumbnail_req = True - log.info(f"found archiver key for gallery {(gid, gtoken)}") a_key = gdata['archiver_key'] a_url = URLS['ex_archiver' if is_exhentai else 'e_archiver'].format(gallery_id=gid, gallery_token=gtoken, archiver_key=a_key) @@ -184,9 +187,8 @@ def download_query(item, is_exhentai): log.warning(f"got invalid key page or bad status: {r.status_code}") if r.status_code == 404 and "This gallery is currently unavailable" in r.text: #We know that there is a valid key for us to get here, so the gallery existed at some point in the past - #Most of the time, it is a copyright takedown, but I don't see a simple way to determine what is the cause - item.name = "(Gallery Expunged) "+item.name - + #This seems like it is most of the time a copyright takedown, but I have no idea why this is not marked as expunged + item.name = "(Gallery Unavailable) "+item.name else: log.warning(f"didn't find archiver key for data: {eh_data}") except Exception as e: @@ -212,7 +214,7 @@ def download_done(result): should return: the same :class:`DownloadResult` that was provided to the handler, potentially modified on the 'path' or `status` and `reason` properties """ - # there's nothing special to post-process in the case of nhentai downloader, so just return the result as is + # there's nothing special to post-process in the case of e(x)hentai downloader, so just return the result as is log.info(f"download of archive was successful for {result.downloaditem.name}") return result From c5e6c02f1ef7cae9c665cd517e85ed839db50cfd Mon Sep 17 00:00:00 2001 From: glop102 Date: Fri, 16 Sep 2022 16:03:47 -0400 Subject: [PATCH 68/68] Small refactor to the ehentai downloader The code was a bit silly with the indentation due to nesting things inside of if statements that never even had an else clause. Mostly code was just moved up in scope and the if statements were inverted to return early when meeting the pre-condition. Also added in comments for different sections and organized the sections to keep logical parts together. --- plugins/EHentai Downloader/main.py | 203 ++++++++++++++++------------- 1 file changed, 111 insertions(+), 92 deletions(-) diff --git a/plugins/EHentai Downloader/main.py b/plugins/EHentai Downloader/main.py index 996e8d5..bfaaa06 100644 --- a/plugins/EHentai Downloader/main.py +++ b/plugins/EHentai Downloader/main.py @@ -96,111 +96,128 @@ def download_query(item, is_exhentai): (though only once, meaning, no handler will be called upon again with the exact same URL during a single session) """ + gid, gtoken = parse_url(item.url) + download_requests = [] + + #=============================================================================== # get ehentai login login_site = URLS['ex'] if is_exhentai else URLS['eh'] login_status = hpx.command.GetLoginStatus(login_site) login_session = None if login_status: login_session = hpx.command.GetLoginSession(login_site) - - gid, gtoken = parse_url(item.url) - - download_requests = [] - - thumbnail_req = False - archive_req = False - - if login_session: - log.info("logged in, attempting to download archive") - # get the archiver key - log.info("getting archiver key") - # prepare request - eh_data = { - 'method': 'gdata', - 'gidlist': [[gid, gtoken]], - } - req_props = hpx.command.RequestProperties( - headers=HEADERS, - json=eh_data, - session=login_session - ) - api_url = URLS['ex_api' if is_exhentai else 'e_api'] - log.info(f"requesting with api url {api_url}") - r = hpx.command.SinglePOSTRequest().request(api_url, req_props) - - if r.ok: - try: - try: - response = r.json - except json.JSONDecodeError: - response = None - log.info("got empty response when trying to retrieve archiver key, this usually means that user has no access to exhentai") - if response and not 'error' in response: - for gdata in response['gmetadata']: - # Often the gallery is still available to download even though it is flagged as expunged - # This makes no sense to me, as other times when the gallery is not available, this flag is still set to false and so seems like it is totally pointless - # if "expunged" in gdata and gdata["expunged"]==True: - # item.name = "(Gallery Expunged) "+item.name - if 'title' in gdata: - item.name = gdata['title'] - if 'thumb' in gdata: + if not login_session: + log.warning("unable to get a login sesion for querying gallery data") + return () + log.info("logged in, attempting to download archive") + + #=============================================================================== + # get the gallery metadata which should have the archive key + # https://ehwiki.org/wiki/API#Gallery_Metadata + log.info("getting archiver key") + eh_data = { + 'method': 'gdata', + 'gidlist': [[gid, gtoken]], + } + req_props = hpx.command.RequestProperties( + headers=HEADERS, + json=eh_data, + session=login_session + ) + api_url = URLS['ex_api' if is_exhentai else 'e_api'] + log.info(f"requesting with api url {api_url}") + r = hpx.command.SinglePOSTRequest().request(api_url, req_props) + if not r.ok: + log.warning(f"got invalid metadata page or bad status: {r.status_code}") + log.debug(r.text) + return () + try: + response = r.json + except json.JSONDecodeError: + response = None + log.info("got empty response when trying to retrieve archiver key, this usually means that user has no access to exhentai") + return () + if not response or 'error' in response: + log.warning("response has an error of some sort, and so we have no archive key to use") + log.debug(r.text) + return () + + #=============================================================================== + # Read the metadata of the gallery to fill out the download queue item + # + # While in theory we should only ever have a single entry in the response, best keep it more general just in case this gets retrofitted to handle multiple urls at once + # The information we reliably get is the thumbnail url and the title of the gallery + # We seem to also always get an archive key, but the key is not always valid, and so the archive url request can fail + # + # Yes, there is an expunged flag in the metadata, but it is always false when the gallery/archive is not available + # It is also true sometimes and yet the gallery/archive is totally accessable and so is meaningless + for gdata in response['gmetadata']: + archive_req = False + try: + if 'title' in gdata: + item.name = gdata['title'] + if 'thumb' in gdata: + download_requests.append( + DownloadRequest( + downloaditem=item, + url=gdata['thumb'], + is_thumbnail=True, + properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session + )) + if 'archiver_key' in gdata: + log.info(f"found archiver key for gallery {(gid, gtoken)}") + a_key = gdata['archiver_key'] + a_url = URLS['ex_archiver' if is_exhentai else 'e_archiver'].format(gallery_id=gid, gallery_token=gtoken, archiver_key=a_key) + form_data = { + "dltype": "org", #original quality, instead of a resampled version + "dlcheck": "Download Original Archive" + } + req_props = hpx.command.RequestProperties( + headers=HEADERS, + data=form_data, + session=login_session + ) + r = hpx.command.SinglePOSTRequest().request(a_url, req_props) + if r.ok: + if "Insufficient funds" in r.text: + log.info("Unable to grab gallery archive due to insufficent funds (GP) on the account") + item.name = "(Insufficient GP) "+item.name + elif "Key missing, or incorrect key provided" not in r.text: + soup = BeautifulSoup(r.text, "html.parser") + dp_url = soup.find("p", id="continue") + if dp_url and dp_url.a: # finally download_requests.append( DownloadRequest( downloaditem=item, - url=gdata['thumb'], - is_thumbnail=True, + url=dp_url.a['href'] + '?start=1', properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session - )) - thumbnail_req = True - if 'archiver_key' in gdata: - log.info(f"found archiver key for gallery {(gid, gtoken)}") - a_key = gdata['archiver_key'] - a_url = URLS['ex_archiver' if is_exhentai else 'e_archiver'].format(gallery_id=gid, gallery_token=gtoken, archiver_key=a_key) - # prepare request - # get the download url - form_data = { - "dltype": "org", - "dlcheck": "Download Original Archive" - } - req_props = hpx.command.RequestProperties( - headers=HEADERS, - data=form_data, - session=login_session - ) - r = hpx.command.SinglePOSTRequest().request(a_url, req_props) - if r.ok: - if "Insufficient funds" in r.text: - log.info("Unable to grab gallery archive due to insufficent funds (GP) on the account") - item.name = "(Insufficient GP) "+item.name - elif "Key missing, or incorrect key provided" not in r.text: - soup = BeautifulSoup(r.text, "html.parser") - dp_url = soup.find("p", id="continue") - if dp_url and dp_url.a: # finally - download_requests.append( - DownloadRequest( - downloaditem=item, - url=dp_url.a['href'] + '?start=1', - properties=hpx.command.RequestProperties(method=hpx.Method.GET, headers=HEADERS, session=login_session), # we need to use the same session - filename=item.name.strip()+'.zip')) - archive_req = True - else: - log.warning(f"got invalid key page or bad status: {r.status_code}") - if r.status_code == 404 and "This gallery is currently unavailable" in r.text: - #We know that there is a valid key for us to get here, so the gallery existed at some point in the past - #This seems like it is most of the time a copyright takedown, but I have no idea why this is not marked as expunged - item.name = "(Gallery Unavailable) "+item.name - else: - log.warning(f"didn't find archiver key for data: {eh_data}") - except Exception as e: - log.debug(f"got an error, last request content: \n\t {r.text}") - raise - - if not archive_req: - pass - # TODO: download individual images instead + filename=item.name.strip()+'.zip')) + archive_req = True + log.debug(f"adding the archive url {download_requests[-1].url}") + if not archive_req: + log.info("Something went wrong and we did not actually find a URL") + #TODO Actually better handle the various cases of why we do not have a url + else: + log.warning(f"got invalid key page or bad status: {r.status_code}") + if r.status_code == 404 and "This gallery is currently unavailable" in r.text: + #We know that there is a valid key for us to get here, so the gallery existed at some point in the past + #This seems like it is most of the time a copyright takedown, but I have no idea why this is not marked as expunged + item.name = "(Gallery Unavailable) "+item.name + else: + log.warning(f"didn't find archiver key for data: {eh_data}") + item.name = "(Archive Unavailable) "+item.name + except Exception as e: + log.debug(f"got an error, last request content: \n\t {r.text}") + raise + + if not archive_req: + pass + # TODO: download individual images instead if download_requests: log.info(f"was able to prepare {len(download_requests)} requests") + else: + log.info("unable to prepare any URLs to download") return tuple(download_requests) @hpx.attach("Download.done", trigger=[EX_IDENTIFIER, EH_IDENTIFIER]) @@ -216,6 +233,8 @@ def download_done(result): """ # there's nothing special to post-process in the case of e(x)hentai downloader, so just return the result as is log.info(f"download of archive was successful for {result.downloaditem.name}") + #TODO Mark it as a failure if there was only a thumbnail to download + #TODO Archive the individual images together into a cbz or something if we grabbed individual images return result def parse_url(url):